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 '/<hr *>/i' => '<hr />',
201 '/<br *>/i' => '<br />',
202 '/<center *>/i' => '<div class="center">',
203 '/<\\/center *>/i' => '</div>',
205 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
208 $text = $this->doBlockLevels( $text, $linestart );
210 $this->replaceLinkHolders( $text );
212 $dashReplace = array(
213 '/ - /' => " – ", # N dash
214 '/(?<=[\d])-(?=[\d])/' => "–", # N dash between numbers
215 '/ -- /' => " — " # M dash
217 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
219 # the position of the convert() call should not be changed. it
220 # assumes that the links are all replaces and the only thing left
221 # is the <nowiki> mark.
222 $text = $wgContLang->convert($text);
223 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
225 $text = $this->unstripNoWiki( $text, $this->mStripState
);
227 $text = Sanitizer
::normalizeCharReferences( $text );
230 $text = Parser
::tidy($text);
233 $this->mOutput
->setText( $text );
234 wfProfileOut( $fname );
235 return $this->mOutput
;
239 * Get a random string
244 function getRandomString() {
245 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
249 * Replaces all occurrences of <$tag>content</$tag> in the text
250 * with a random marker and returns the new text. the output parameter
251 * $content will be an associative array filled with data on the form
252 * $unique_marker => content.
254 * If $content is already set, the additional entries will be appended
255 * If $tag is set to STRIP_COMMENTS, the function will extract
256 * <!-- HTML comments -->
261 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
262 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
277 if( $tag == STRIP_COMMENTS
) {
281 $start = "/<$tag([^>]*)>/i";
282 $end = "/<\\/$tag\\s*>/i";
285 while ( '' != $text ) {
286 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
288 if( count( $p ) < 3 ) {
294 $marker = $rnd . sprintf('%08X', $n++
);
295 $stripped .= $marker;
297 $tags[$marker] = "<$tag$attributes>";
298 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
300 $q = preg_split( $end, $inside, 2 );
301 $content[$marker] = $q[0];
302 if( count( $q ) < 1 ) {
303 # No end tag -- let it run out to the end of the text.
313 * Wrapper function for extractTagsAndParams
314 * for cases where $tags and $params isn't needed
315 * i.e. where tags will never have params, like <nowiki>
320 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
321 $dummy_tags = array();
322 $dummy_params = array();
324 return Parser
::extractTagsAndParams( $tag, $text, $content,
325 $dummy_tags, $dummy_params, $uniq_prefix );
329 * Strips and renders nowiki, pre, math, hiero
330 * If $render is set, performs necessary rendering operations on plugins
331 * Returns the text, and fills an array with data needed in unstrip()
332 * If the $state is already a valid strip state, it adds to the state
334 * @param bool $stripcomments when set, HTML comments <!-- like this -->
335 * will be stripped in addition to other tags. This is important
336 * for section editing, where these comments cause confusion when
337 * counting the sections in the wikisource
341 function strip( $text, &$state, $stripcomments = false ) {
342 $render = ($this->mOutputType
== OT_HTML
);
343 $html_content = array();
344 $nowiki_content = array();
345 $math_content = array();
346 $pre_content = array();
347 $comment_content = array();
348 $ext_content = array();
350 $ext_params = array();
351 $gallery_content = array();
353 # Replace any instances of the placeholders
354 $uniq_prefix = UNIQ_PREFIX
;
355 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
358 global $wgRawHtml, $wgWhitelistEdit;
359 if( $wgRawHtml && $wgWhitelistEdit ) {
360 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
361 foreach( $html_content as $marker => $content ) {
363 # Raw and unchecked for validity.
364 $html_content[$marker] = $content;
366 $html_content[$marker] = '<html>'.$content.'</html>';
372 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
373 foreach( $nowiki_content as $marker => $content ) {
375 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
377 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
382 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
383 foreach( $math_content as $marker => $content ){
385 if( $this->mOptions
->getUseTeX() ) {
386 $math_content[$marker] = renderMath( $content );
388 $math_content[$marker] = '<math>'.$content.'<math>';
391 $math_content[$marker] = '<math>'.$content.'</math>';
396 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
397 foreach( $pre_content as $marker => $content ){
399 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
401 $pre_content[$marker] = '<pre>'.$content.'</pre>';
406 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
407 foreach( $gallery_content as $marker => $content ) {
408 require_once( 'ImageGallery.php' );
410 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
412 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
418 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
419 foreach( $comment_content as $marker => $content ){
420 $comment_content[$marker] = '<!--'.$content.'-->';
425 foreach ( $this->mTagHooks
as $tag => $callback ) {
426 $ext_content[$tag] = array();
427 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
428 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
429 foreach( $ext_content[$tag] as $marker => $content ) {
430 $full_tag = $ext_tags[$tag][$marker];
431 $params = $ext_params[$tag][$marker];
433 $ext_content[$tag][$marker] = $callback( $content, $params );
435 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
440 # Merge state with the pre-existing state, if there is one
442 $state['html'] = $state['html'] +
$html_content;
443 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
444 $state['math'] = $state['math'] +
$math_content;
445 $state['pre'] = $state['pre'] +
$pre_content;
446 $state['comment'] = $state['comment'] +
$comment_content;
447 $state['gallery'] = $state['gallery'] +
$gallery_content;
449 foreach( $ext_content as $tag => $array ) {
450 if ( array_key_exists( $tag, $state ) ) {
451 $state[$tag] = $state[$tag] +
$array;
456 'html' => $html_content,
457 'nowiki' => $nowiki_content,
458 'math' => $math_content,
459 'pre' => $pre_content,
460 'comment' => $comment_content,
461 'gallery' => $gallery_content,
468 * restores pre, math, and hiero removed by strip()
470 * always call unstripNoWiki() after this one
473 function unstrip( $text, &$state ) {
474 # Must expand in reverse order, otherwise nested tags will be corrupted
475 $contentDict = end( $state );
476 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
477 if( key($state) != 'nowiki' && key($state) != 'html') {
478 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
479 $text = str_replace( key( $contentDict ), $content, $text );
488 * always call this after unstrip() to preserve the order
492 function unstripNoWiki( $text, &$state ) {
493 # Must expand in reverse order, otherwise nested tags will be corrupted
494 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
495 $text = str_replace( key( $state['nowiki'] ), $content, $text );
500 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
501 $text = str_replace( key( $state['html'] ), $content, $text );
509 * Add an item to the strip state
510 * Returns the unique tag which must be inserted into the stripped text
511 * The tag will be replaced with the original text in unstrip()
515 function insertStripItem( $text, &$state ) {
516 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
525 $state['item'][$rnd] = $text;
530 * Interface with html tidy, used if $wgUseTidy = true.
531 * If tidy isn't able to correct the markup, the original will be
532 * returned in all its glory with a warning comment appended.
534 * Either the external tidy program or the in-process tidy extension
535 * will be used depending on availability. Override the default
536 * $wgTidyInternal setting to disable the internal if it's not working.
538 * @param string $text Hideous HTML input
539 * @return string Corrected HTML output
543 function tidy( $text ) {
544 global $wgTidyInternal;
545 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
546 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
547 '<head><title>test</title></head><body>'.$text.'</body></html>';
548 if( $wgTidyInternal ) {
549 $correctedtext = Parser
::internalTidy( $wrappedtext );
551 $correctedtext = Parser
::externalTidy( $wrappedtext );
553 if( is_null( $correctedtext ) ) {
554 wfDebug( "Tidy error detected!\n" );
555 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
557 return $correctedtext;
561 * Spawn an external HTML tidy process and get corrected markup back from it.
566 function externalTidy( $text ) {
567 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
568 $fname = 'Parser::externalTidy';
569 wfProfileIn( $fname );
574 $descriptorspec = array(
575 0 => array('pipe', 'r'),
576 1 => array('pipe', 'w'),
577 2 => array('file', '/dev/null', 'a')
580 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
581 if (is_resource($process)) {
582 fwrite($pipes[0], $text);
584 while (!feof($pipes[1])) {
585 $cleansource .= fgets($pipes[1], 1024);
588 proc_close($process);
591 wfProfileOut( $fname );
593 if( $cleansource == '' && $text != '') {
594 // Some kind of error happened, so we couldn't get the corrected text.
595 // Just give up; we'll use the source text and append a warning.
603 * Use the HTML tidy PECL extension to use the tidy library in-process,
604 * saving the overhead of spawning a new process. Currently written to
605 * the PHP 4.3.x version of the extension, may not work on PHP 5.
607 * 'pear install tidy' should be able to compile the extension module.
612 function internalTidy( $text ) {
614 $fname = 'Parser::internalTidy';
615 wfProfileIn( $fname );
617 tidy_load_config( $wgTidyConf );
618 tidy_set_encoding( 'utf8' );
619 tidy_parse_string( $text );
621 if( tidy_get_status() == 2 ) {
622 // 2 is magic number for fatal error
623 // http://www.php.net/manual/en/function.tidy-get-status.php
626 $cleansource = tidy_get_output();
628 wfProfileOut( $fname );
633 * parse the wiki syntax used to render tables
637 function doTableStuff ( $t ) {
638 $fname = 'Parser::doTableStuff';
639 wfProfileIn( $fname );
641 $t = explode ( "\n" , $t ) ;
642 $td = array () ; # Is currently a td tag open?
643 $ltd = array () ; # Was it TD or TH?
644 $tr = array () ; # Is currently a tr tag open?
645 $ltr = array () ; # tr attributes
646 $indent_level = 0; # indent level of the table
647 foreach ( $t AS $k => $x )
650 $fc = substr ( $x , 0 , 1 ) ;
651 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
652 $indent_level = strlen( $matches[1] );
653 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
654 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
655 array_push ( $td , false ) ;
656 array_push ( $ltd , '' ) ;
657 array_push ( $tr , false ) ;
658 array_push ( $ltr , '' ) ;
660 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
661 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
662 $z = "</table>" . substr ( $x , 2);
663 $l = array_pop ( $ltd ) ;
664 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
665 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
667 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
669 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
670 $x = substr ( $x , 1 ) ;
671 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
673 $l = array_pop ( $ltd ) ;
674 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
675 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
678 array_push ( $tr , false ) ;
679 array_push ( $td , false ) ;
680 array_push ( $ltd , '' ) ;
681 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
683 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
685 if ( '|+' == substr ( $x , 0 , 2 ) ) {
687 $x = substr ( $x , 1 ) ;
689 $after = substr ( $x , 1 ) ;
690 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
691 $after = explode ( '||' , $after ) ;
694 # Loop through each table cell
695 foreach ( $after AS $theline )
700 $tra = array_pop ( $ltr ) ;
701 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
702 array_push ( $tr , true ) ;
703 array_push ( $ltr , '' ) ;
706 $l = array_pop ( $ltd ) ;
707 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
708 if ( $fc == '|' ) $l = 'td' ;
709 else if ( $fc == '!' ) $l = 'th' ;
710 else if ( $fc == '+' ) $l = 'caption' ;
712 array_push ( $ltd , $l ) ;
715 $y = explode ( '|' , $theline , 2 ) ;
716 # Note that a '|' inside an invalid link should not
717 # be mistaken as delimiting cell parameters
718 if ( strpos( $y[0], '[[' ) !== false ) {
719 $y = array ($theline);
721 if ( count ( $y ) == 1 )
722 $y = "{$z}<{$l}>{$y[0]}" ;
723 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$y[1]}" ;
725 array_push ( $td , true ) ;
730 # Closing open td, tr && table
731 while ( count ( $td ) > 0 )
733 if ( array_pop ( $td ) ) $t[] = '</td>' ;
734 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
738 $t = implode ( "\n" , $t ) ;
739 wfProfileOut( $fname );
744 * Helper function for parse() that transforms wiki markup into
745 * HTML. Only called for $mOutputType == OT_HTML.
749 function internalParse( $text ) {
753 $fname = 'Parser::internalParse';
754 wfProfileIn( $fname );
756 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ) );
757 $text = $this->replaceVariables( $text, $args );
759 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
761 $text = $this->doHeadings( $text );
762 if($this->mOptions
->getUseDynamicDates()) {
763 $df =& DateFormatter
::getInstance();
764 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
766 $text = $this->doAllQuotes( $text );
767 $text = $this->replaceInternalLinks( $text );
768 $text = $this->replaceExternalLinks( $text );
770 # replaceInternalLinks may sometimes leave behind
771 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
772 $text = str_replace("http-noparse://","http://",$text);
774 $text = $this->doMagicLinks( $text );
775 $text = $this->doTableStuff( $text );
776 $text = $this->formatHeadings( $text, $isMain );
778 wfProfileOut( $fname );
783 * Replace special strings like "ISBN xxx" and "RFC xxx" with
784 * magic external links.
788 function &doMagicLinks( &$text ) {
789 $text = $this->magicISBN( $text );
790 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
791 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
796 * Parse ^^ tokens and return html
800 function doExponent( $text ) {
801 $fname = 'Parser::doExponent';
802 wfProfileIn( $fname );
803 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
804 wfProfileOut( $fname );
809 * Parse headers and return html
813 function doHeadings( $text ) {
814 $fname = 'Parser::doHeadings';
815 wfProfileIn( $fname );
816 for ( $i = 6; $i >= 1; --$i ) {
817 $h = substr( '======', 0, $i );
818 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
819 "<h{$i}>\\1</h{$i}>\\2", $text );
821 wfProfileOut( $fname );
826 * Replace single quotes with HTML markup
828 * @return string the altered text
830 function doAllQuotes( $text ) {
831 $fname = 'Parser::doAllQuotes';
832 wfProfileIn( $fname );
834 $lines = explode( "\n", $text );
835 foreach ( $lines as $line ) {
836 $outtext .= $this->doQuotes ( $line ) . "\n";
838 $outtext = substr($outtext, 0,-1);
839 wfProfileOut( $fname );
844 * Helper function for doAllQuotes()
847 function doQuotes( $text ) {
848 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
849 if ( count( $arr ) == 1 )
853 # First, do some preliminary work. This may shift some apostrophes from
854 # being mark-up to being text. It also counts the number of occurrences
855 # of bold and italics mark-ups.
859 foreach ( $arr as $r )
861 if ( ( $i %
2 ) == 1 )
863 # If there are ever four apostrophes, assume the first is supposed to
864 # be text, and the remaining three constitute mark-up for bold text.
865 if ( strlen( $arr[$i] ) == 4 )
870 # If there are more than 5 apostrophes in a row, assume they're all
871 # text except for the last 5.
872 else if ( strlen( $arr[$i] ) > 5 )
874 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
877 # Count the number of occurrences of bold and italics mark-ups.
878 # We are not counting sequences of five apostrophes.
879 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
880 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
881 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
886 # If there is an odd number of both bold and italics, it is likely
887 # that one of the bold ones was meant to be an apostrophe followed
888 # by italics. Which one we cannot know for certain, but it is more
889 # likely to be one that has a single-letter word before it.
890 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
893 $firstsingleletterword = -1;
894 $firstmultiletterword = -1;
896 foreach ( $arr as $r )
898 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
900 $x1 = substr ($arr[$i-1], -1);
901 $x2 = substr ($arr[$i-1], -2, 1);
903 if ($firstspace == -1) $firstspace = $i;
904 } else if ($x2 == ' ') {
905 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
907 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
913 # If there is a single-letter word, use it!
914 if ($firstsingleletterword > -1)
916 $arr [ $firstsingleletterword ] = "''";
917 $arr [ $firstsingleletterword-1 ] .= "'";
919 # If not, but there's a multi-letter word, use that one.
920 else if ($firstmultiletterword > -1)
922 $arr [ $firstmultiletterword ] = "''";
923 $arr [ $firstmultiletterword-1 ] .= "'";
925 # ... otherwise use the first one that has neither.
926 # (notice that it is possible for all three to be -1 if, for example,
927 # there is only one pentuple-apostrophe in the line)
928 else if ($firstspace > -1)
930 $arr [ $firstspace ] = "''";
931 $arr [ $firstspace-1 ] .= "'";
935 # Now let's actually convert our apostrophic mush to HTML!
944 if ($state == 'both')
951 if (strlen ($r) == 2)
954 { $output .= '</i>'; $state = ''; }
955 else if ($state == 'bi')
956 { $output .= '</i>'; $state = 'b'; }
957 else if ($state == 'ib')
958 { $output .= '</b></i><b>'; $state = 'b'; }
959 else if ($state == 'both')
960 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
961 else # $state can be 'b' or ''
962 { $output .= '<i>'; $state .= 'i'; }
964 else if (strlen ($r) == 3)
967 { $output .= '</b>'; $state = ''; }
968 else if ($state == 'bi')
969 { $output .= '</i></b><i>'; $state = 'i'; }
970 else if ($state == 'ib')
971 { $output .= '</b>'; $state = 'i'; }
972 else if ($state == 'both')
973 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
974 else # $state can be 'i' or ''
975 { $output .= '<b>'; $state .= 'b'; }
977 else if (strlen ($r) == 5)
980 { $output .= '</b><i>'; $state = 'i'; }
981 else if ($state == 'i')
982 { $output .= '</i><b>'; $state = 'b'; }
983 else if ($state == 'bi')
984 { $output .= '</i></b>'; $state = ''; }
985 else if ($state == 'ib')
986 { $output .= '</b></i>'; $state = ''; }
987 else if ($state == 'both')
988 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
989 else # ($state == '')
990 { $buffer = ''; $state = 'both'; }
995 # Now close all remaining tags. Notice that the order is important.
996 if ($state == 'b' ||
$state == 'ib')
998 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1002 if ($state == 'both')
1003 $output .= '<b><i>'.$buffer.'</i></b>';
1009 * Replace external links
1011 * Note: this is all very hackish and the order of execution matters a lot.
1012 * Make sure to run maintenance/parserTests.php if you change this code.
1016 function replaceExternalLinks( $text ) {
1018 $fname = 'Parser::replaceExternalLinks';
1019 wfProfileIn( $fname );
1021 $sk =& $this->mOptions
->getSkin();
1023 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1025 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1028 while ( $i<count( $bits ) ) {
1030 $protocol = $bits[$i++
];
1031 $text = $bits[$i++
];
1032 $trail = $bits[$i++
];
1034 # The characters '<' and '>' (which were escaped by
1035 # removeHTMLtags()) should not be included in
1036 # URLs, per RFC 2396.
1037 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1038 $text = substr($url, $m2[0][1]) . ' ' . $text;
1039 $url = substr($url, 0, $m2[0][1]);
1042 # If the link text is an image URL, replace it with an <img> tag
1043 # This happened by accident in the original parser, but some people used it extensively
1044 $img = $this->maybeMakeExternalImage( $text );
1045 if ( $img !== false ) {
1051 # Set linktype for CSS - if URL==text, link is essentially free
1052 $linktype = ($text == $url) ?
'free' : 'text';
1054 # No link text, e.g. [http://domain.tld/some.link]
1055 if ( $text == '' ) {
1056 # Autonumber if allowed
1057 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
1058 $text = '[' . ++
$this->mAutonumber
. ']';
1059 $linktype = 'autonumber';
1061 # Otherwise just use the URL
1062 $text = htmlspecialchars( $url );
1066 # Have link text, e.g. [http://domain.tld/some.link text]s
1068 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1071 $text = $wgContLang->markNoConversion($text);
1073 # Replace & from obsolete syntax with &.
1074 # All HTML entities will be escaped by makeExternalLink()
1075 # or maybeMakeExternalImage()
1076 $url = str_replace( '&', '&', $url );
1078 # Process the trail (i.e. everything after this link up until start of the next link),
1079 # replacing any non-bracketed links
1080 $trail = $this->replaceFreeExternalLinks( $trail );
1083 # Use the encoded URL
1084 # This means that users can paste URLs directly into the text
1085 # Funny characters like ö aren't valid in URLs anyway
1086 # This was changed in August 2004
1087 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1090 wfProfileOut( $fname );
1095 * Replace anything that looks like a URL with a link
1098 function replaceFreeExternalLinks( $text ) {
1100 $fname = 'Parser::replaceFreeExternalLinks';
1101 wfProfileIn( $fname );
1103 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1104 $s = array_shift( $bits );
1107 $sk =& $this->mOptions
->getSkin();
1109 while ( $i < count( $bits ) ){
1110 $protocol = $bits[$i++
];
1111 $remainder = $bits[$i++
];
1113 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1114 # Found some characters after the protocol that look promising
1115 $url = $protocol . $m[1];
1118 # The characters '<' and '>' (which were escaped by
1119 # removeHTMLtags()) should not be included in
1120 # URLs, per RFC 2396.
1121 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1122 $trail = substr($url, $m2[0][1]) . $trail;
1123 $url = substr($url, 0, $m2[0][1]);
1126 # Move trailing punctuation to $trail
1128 # If there is no left bracket, then consider right brackets fair game too
1129 if ( strpos( $url, '(' ) === false ) {
1133 $numSepChars = strspn( strrev( $url ), $sep );
1134 if ( $numSepChars ) {
1135 $trail = substr( $url, -$numSepChars ) . $trail;
1136 $url = substr( $url, 0, -$numSepChars );
1139 # Replace & from obsolete syntax with &.
1140 # All HTML entities will be escaped by makeExternalLink()
1141 # or maybeMakeExternalImage()
1142 $url = str_replace( '&', '&', $url );
1144 # Is this an external image?
1145 $text = $this->maybeMakeExternalImage( $url );
1146 if ( $text === false ) {
1147 # Not an image, make a link
1148 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1150 $s .= $text . $trail;
1152 $s .= $protocol . $remainder;
1160 * make an image if it's allowed
1163 function maybeMakeExternalImage( $url ) {
1164 $sk =& $this->mOptions
->getSkin();
1166 if ( $this->mOptions
->getAllowExternalImages() ) {
1167 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1169 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1176 * Process [[ ]] wikilinks
1180 function replaceInternalLinks( $s ) {
1181 global $wgContLang, $wgLinkCache;
1182 static $fname = 'Parser::replaceInternalLinks' ;
1184 wfProfileIn( $fname );
1186 wfProfileIn( $fname.'-setup' );
1188 # the % is needed to support urlencoded titles as well
1189 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1191 $sk =& $this->mOptions
->getSkin();
1193 #split the entire text string on occurences of [[
1194 $a = explode( '[[', ' ' . $s );
1195 #get the first element (all text up to first [[), and remove the space we added
1196 $s = array_shift( $a );
1197 $s = substr( $s, 1 );
1199 # Match a link having the form [[namespace:link|alternate]]trail
1201 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1202 # Match cases where there is no "]]", which might still be images
1203 static $e1_img = FALSE;
1204 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1205 # Match the end of a line for a word that's not followed by whitespace,
1206 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1207 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1209 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1211 if( is_null( $this->mTitle
) ) {
1212 wfDebugDieBacktrace( 'nooo' );
1214 $nottalk = !$this->mTitle
->isTalkPage();
1216 if ( $useLinkPrefixExtension ) {
1217 if ( preg_match( $e2, $s, $m ) ) {
1218 $first_prefix = $m[2];
1221 $first_prefix = false;
1227 $selflink = $this->mTitle
->getPrefixedText();
1228 wfProfileOut( $fname.'-setup' );
1230 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1231 $useSubpages = $this->areSubpagesAllowed();
1233 # Loop for each link
1234 for ($k = 0; isset( $a[$k] ); $k++
) {
1236 if ( $useLinkPrefixExtension ) {
1237 wfProfileIn( $fname.'-prefixhandling' );
1238 if ( preg_match( $e2, $s, $m ) ) {
1246 $prefix = $first_prefix;
1247 $first_prefix = false;
1249 wfProfileOut( $fname.'-prefixhandling' );
1252 $might_be_img = false;
1254 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1256 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1257 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1258 # the real problem is with the $e1 regex
1261 # Still some problems for cases where the ] is meant to be outside punctuation,
1262 # and no image is in sight. See bug 2095.
1264 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1265 $text .= ']'; # so that replaceExternalLinks($text) works later
1268 # fix up urlencoded title texts
1269 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1271 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1272 $might_be_img = true;
1274 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1276 } else { # Invalid form; output directly
1277 $s .= $prefix . '[[' . $line ;
1281 # Don't allow internal links to pages containing
1282 # PROTO: where PROTO is a valid URL protocol; these
1283 # should be external links.
1284 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1285 $s .= $prefix . '[[' . $line ;
1289 # Make subpage if necessary
1290 if( $useSubpages ) {
1291 $link = $this->maybeDoSubpageLink( $m[1], $text );
1296 $noforce = (substr($m[1], 0, 1) != ':');
1298 # Strip off leading ':'
1299 $link = substr($link, 1);
1302 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1304 $s .= $prefix . '[[' . $line;
1308 #check other language variants of the link
1309 #if the article does not exist
1310 if( $checkVariantLink
1311 && $nt->getArticleID() == 0 ) {
1312 $wgContLang->findVariantLink($link, $nt);
1315 $ns = $nt->getNamespace();
1316 $iw = $nt->getInterWiki();
1318 if ($might_be_img) { # if this is actually an invalid link
1319 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1321 while (isset ($a[$k+
1]) ) {
1322 #look at the next 'line' to see if we can close it there
1323 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1324 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1325 # the first ]] closes the inner link, the second the image
1327 $text .= '[[' . $m[1];
1330 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1331 #if there's exactly one ]] that's fine, we'll keep looking
1332 $text .= '[[' . $m[0];
1334 #if $next_line is invalid too, we need look no further
1335 $text .= '[[' . $next_line;
1340 # we couldn't find the end of this imageLink, so output it raw
1341 #but don't ignore what might be perfectly normal links in the text we've examined
1342 $text = $this->replaceInternalLinks($text);
1343 $s .= $prefix . '[[' . $link . '|' . $text;
1344 # note: no $trail, because without an end, there *is* no trail
1347 } else { #it's not an image, so output it raw
1348 $s .= $prefix . '[[' . $link . '|' . $text;
1349 # note: no $trail, because without an end, there *is* no trail
1354 $wasblank = ( '' == $text );
1355 if( $wasblank ) $text = $link;
1358 # Link not escaped by : , create the various objects
1362 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1363 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1364 $s = rtrim($s . "\n");
1365 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1369 if ( $ns == NS_IMAGE
) {
1370 wfProfileIn( "$fname-image" );
1371 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1372 # recursively parse links inside the image caption
1373 # actually, this will parse them in any other parameters, too,
1374 # but it might be hard to fix that, and it doesn't matter ATM
1375 $text = $this->replaceExternalLinks($text);
1376 $text = $this->replaceInternalLinks($text);
1378 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1379 $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
1380 $wgLinkCache->addImageLinkObj( $nt );
1382 wfProfileOut( "$fname-image" );
1385 wfProfileOut( "$fname-image" );
1389 if ( $ns == NS_CATEGORY
) {
1390 wfProfileIn( "$fname-category" );
1391 $t = $wgContLang->convert($nt->getText());
1392 $s = rtrim($s . "\n"); # bug 87
1394 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1395 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1396 $wgLinkCache->resume();
1399 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1400 $sortkey = $this->mTitle
->getText();
1402 $sortkey = $this->mTitle
->getPrefixedText();
1407 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1408 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1409 $this->mOutput
->addCategoryLink( $t );
1412 * Strip the whitespace Category links produce, see bug 87
1413 * @todo We might want to use trim($tmp, "\n") here.
1415 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1417 wfProfileOut( "$fname-category" );
1422 if( ( $nt->getPrefixedText() === $selflink ) &&
1423 ( $nt->getFragment() === '' ) ) {
1424 # Self-links are handled specially; generally de-link and change to bold.
1425 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1429 # Special and Media are pseudo-namespaces; no pages actually exist in them
1430 if( $ns == NS_MEDIA
) {
1431 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1432 $wgLinkCache->addImageLinkObj( $nt );
1434 } elseif( $ns == NS_SPECIAL
) {
1435 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1438 if ( $nt->isAlwaysKnown() ) {
1439 $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
1442 * Add a link placeholder
1443 * Later, this will be replaced by a real link, after the existence or
1444 * non-existence of all the links is known
1446 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1449 wfProfileOut( $fname );
1454 * Make a link placeholder. The text returned can be later resolved to a real link with
1455 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1456 * parsing of interwiki links, and secondly to allow all extistence checks and
1457 * article length checks (for stub links) to be bundled into a single query.
1460 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1461 if ( ! is_object($nt) ) {
1463 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1465 # Separate the link trail from the rest of the link
1466 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1468 if ( $nt->isExternal() ) {
1469 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1470 $this->mInterwikiLinkHolders
['titles'][] =& $nt;
1471 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1473 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1474 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1475 $this->mLinkHolders
['queries'][] = $query;
1476 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1477 $this->mLinkHolders
['titles'][] =& $nt;
1479 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1486 * Return true if subpage links should be expanded on this page.
1489 function areSubpagesAllowed() {
1490 # Some namespaces don't allow subpages
1491 global $wgNamespacesWithSubpages;
1492 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1496 * Handle link to subpage if necessary
1497 * @param string $target the source of the link
1498 * @param string &$text the link text, modified as necessary
1499 * @return string the full name of the link
1502 function maybeDoSubpageLink($target, &$text) {
1505 # :Foobar -- override special treatment of prefix (images, language links)
1506 # /Foobar -- convert to CurrentPage/Foobar
1507 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1508 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1509 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1511 $fname = 'Parser::maybeDoSubpageLink';
1512 wfProfileIn( $fname );
1513 $ret = $target; # default return value is no change
1515 # Some namespaces don't allow subpages,
1516 # so only perform processing if subpages are allowed
1517 if( $this->areSubpagesAllowed() ) {
1518 # Look at the first character
1519 if( $target != '' && $target{0} == '/' ) {
1520 # / at end means we don't want the slash to be shown
1521 if( substr( $target, -1, 1 ) == '/' ) {
1522 $target = substr( $target, 1, -1 );
1525 $noslash = substr( $target, 1 );
1528 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1529 if( '' === $text ) {
1531 } # this might be changed for ugliness reasons
1533 # check for .. subpage backlinks
1535 $nodotdot = $target;
1536 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1538 $nodotdot = substr( $nodotdot, 3 );
1540 if($dotdotcount > 0) {
1541 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1542 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1543 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1544 # / at the end means don't show full path
1545 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1546 $nodotdot = substr( $nodotdot, 0, -1 );
1547 if( '' === $text ) {
1551 $nodotdot = trim( $nodotdot );
1552 if( $nodotdot != '' ) {
1553 $ret .= '/' . $nodotdot;
1560 wfProfileOut( $fname );
1565 * Used by doBlockLevels()
1568 /* private */ function closeParagraph() {
1570 if ( '' != $this->mLastSection
) {
1571 $result = '</' . $this->mLastSection
. ">\n";
1573 $this->mInPre
= false;
1574 $this->mLastSection
= '';
1577 # getCommon() returns the length of the longest common substring
1578 # of both arguments, starting at the beginning of both.
1580 /* private */ function getCommon( $st1, $st2 ) {
1581 $fl = strlen( $st1 );
1582 $shorter = strlen( $st2 );
1583 if ( $fl < $shorter ) { $shorter = $fl; }
1585 for ( $i = 0; $i < $shorter; ++
$i ) {
1586 if ( $st1{$i} != $st2{$i} ) { break; }
1590 # These next three functions open, continue, and close the list
1591 # element appropriate to the prefix character passed into them.
1593 /* private */ function openList( $char ) {
1594 $result = $this->closeParagraph();
1596 if ( '*' == $char ) { $result .= '<ul><li>'; }
1597 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1598 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1599 else if ( ';' == $char ) {
1600 $result .= '<dl><dt>';
1601 $this->mDTopen
= true;
1603 else { $result = '<!-- ERR 1 -->'; }
1608 /* private */ function nextItem( $char ) {
1609 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1610 else if ( ':' == $char ||
';' == $char ) {
1612 if ( $this->mDTopen
) { $close = '</dt>'; }
1613 if ( ';' == $char ) {
1614 $this->mDTopen
= true;
1615 return $close . '<dt>';
1617 $this->mDTopen
= false;
1618 return $close . '<dd>';
1621 return '<!-- ERR 2 -->';
1624 /* private */ function closeList( $char ) {
1625 if ( '*' == $char ) { $text = '</li></ul>'; }
1626 else if ( '#' == $char ) { $text = '</li></ol>'; }
1627 else if ( ':' == $char ) {
1628 if ( $this->mDTopen
) {
1629 $this->mDTopen
= false;
1630 $text = '</dt></dl>';
1632 $text = '</dd></dl>';
1635 else { return '<!-- ERR 3 -->'; }
1641 * Make lists from lines starting with ':', '*', '#', etc.
1644 * @return string the lists rendered as HTML
1646 function doBlockLevels( $text, $linestart ) {
1647 $fname = 'Parser::doBlockLevels';
1648 wfProfileIn( $fname );
1650 # Parsing through the text line by line. The main thing
1651 # happening here is handling of block-level elements p, pre,
1652 # and making lists from lines starting with * # : etc.
1654 $textLines = explode( "\n", $text );
1656 $lastPrefix = $output = '';
1657 $this->mDTopen
= $inBlockElem = false;
1659 $paragraphStack = false;
1661 if ( !$linestart ) {
1662 $output .= array_shift( $textLines );
1664 foreach ( $textLines as $oLine ) {
1665 $lastPrefixLength = strlen( $lastPrefix );
1666 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1667 $preOpenMatch = preg_match('/<pre/i', $oLine );
1668 if ( !$this->mInPre
) {
1669 # Multiple prefixes may abut each other for nested lists.
1670 $prefixLength = strspn( $oLine, '*#:;' );
1671 $pref = substr( $oLine, 0, $prefixLength );
1674 $pref2 = str_replace( ';', ':', $pref );
1675 $t = substr( $oLine, $prefixLength );
1676 $this->mInPre
= !empty($preOpenMatch);
1678 # Don't interpret any other prefixes in preformatted text
1680 $pref = $pref2 = '';
1685 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1686 # Same as the last item, so no need to deal with nesting or opening stuff
1687 $output .= $this->nextItem( substr( $pref, -1 ) );
1688 $paragraphStack = false;
1690 if ( substr( $pref, -1 ) == ';') {
1691 # The one nasty exception: definition lists work like this:
1692 # ; title : definition text
1693 # So we check for : in the remainder text to split up the
1694 # title and definition, without b0rking links.
1696 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1698 $output .= $term . $this->nextItem( ':' );
1701 } elseif( $prefixLength ||
$lastPrefixLength ) {
1702 # Either open or close a level...
1703 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1704 $paragraphStack = false;
1706 while( $commonPrefixLength < $lastPrefixLength ) {
1707 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1708 --$lastPrefixLength;
1710 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1711 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1713 while ( $prefixLength > $commonPrefixLength ) {
1714 $char = substr( $pref, $commonPrefixLength, 1 );
1715 $output .= $this->openList( $char );
1717 if ( ';' == $char ) {
1718 # FIXME: This is dupe of code above
1719 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1721 $output .= $term . $this->nextItem( ':' );
1724 ++
$commonPrefixLength;
1726 $lastPrefix = $pref2;
1728 if( 0 == $prefixLength ) {
1729 wfProfileIn( "$fname-paragraph" );
1730 # No prefix (not in list)--go to paragraph mode
1731 $uniq_prefix = UNIQ_PREFIX
;
1732 // XXX: use a stack for nestable elements like span, table and div
1733 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1734 $closematch = preg_match(
1735 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1736 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1737 if ( $openmatch or $closematch ) {
1738 $paragraphStack = false;
1739 $output .= $this->closeParagraph();
1740 if($preOpenMatch and !$preCloseMatch) {
1741 $this->mInPre
= true;
1743 if ( $closematch ) {
1744 $inBlockElem = false;
1746 $inBlockElem = true;
1748 } else if ( !$inBlockElem && !$this->mInPre
) {
1749 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1751 if ($this->mLastSection
!= 'pre') {
1752 $paragraphStack = false;
1753 $output .= $this->closeParagraph().'<pre>';
1754 $this->mLastSection
= 'pre';
1756 $t = substr( $t, 1 );
1759 if ( '' == trim($t) ) {
1760 if ( $paragraphStack ) {
1761 $output .= $paragraphStack.'<br />';
1762 $paragraphStack = false;
1763 $this->mLastSection
= 'p';
1765 if ($this->mLastSection
!= 'p' ) {
1766 $output .= $this->closeParagraph();
1767 $this->mLastSection
= '';
1768 $paragraphStack = '<p>';
1770 $paragraphStack = '</p><p>';
1774 if ( $paragraphStack ) {
1775 $output .= $paragraphStack;
1776 $paragraphStack = false;
1777 $this->mLastSection
= 'p';
1778 } else if ($this->mLastSection
!= 'p') {
1779 $output .= $this->closeParagraph().'<p>';
1780 $this->mLastSection
= 'p';
1785 wfProfileOut( "$fname-paragraph" );
1787 if ($paragraphStack === false) {
1791 while ( $prefixLength ) {
1792 $output .= $this->closeList( $pref2{$prefixLength-1} );
1795 if ( '' != $this->mLastSection
) {
1796 $output .= '</' . $this->mLastSection
. '>';
1797 $this->mLastSection
= '';
1800 wfProfileOut( $fname );
1805 * Split up a string on ':', ignoring any occurences inside
1806 * <a>..</a> or <span>...</span>
1807 * @param string $str the string to split
1808 * @param string &$before set to everything before the ':'
1809 * @param string &$after set to everything after the ':'
1810 * return string the position of the ':', or false if none found
1812 function findColonNoLinks($str, &$before, &$after) {
1813 # I wonder if we should make this count all tags, not just <a>
1814 # and <span>. That would prevent us from matching a ':' that
1815 # comes in the middle of italics other such formatting....
1817 $fname = 'Parser::findColonNoLinks';
1818 wfProfileIn( $fname );
1821 $colon = strpos($str, ':', $pos);
1823 if ($colon !== false) {
1824 $before = substr($str, 0, $colon);
1825 $after = substr($str, $colon +
1);
1827 # Skip any ':' within <a> or <span> pairs
1828 $a = substr_count($before, '<a');
1829 $s = substr_count($before, '<span');
1830 $ca = substr_count($before, '</a>');
1831 $cs = substr_count($before, '</span>');
1833 if ($a <= $ca and $s <= $cs) {
1834 # Tags are balanced before ':'; ok
1839 } while ($colon !== false);
1840 wfProfileOut( $fname );
1845 * Return value of a magic variable (like PAGENAME)
1849 function getVariableValue( $index ) {
1850 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1853 * Some of these require message or data lookups and can be
1854 * expensive to check many times.
1856 static $varCache = array();
1857 if( isset( $varCache[$index] ) ) return $varCache[$index];
1860 case MAG_CURRENTMONTH
:
1861 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1862 case MAG_CURRENTMONTHNAME
:
1863 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1864 case MAG_CURRENTMONTHNAMEGEN
:
1865 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1866 case MAG_CURRENTMONTHABBREV
:
1867 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1868 case MAG_CURRENTDAY
:
1869 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1871 return $this->mTitle
->getText();
1873 return $this->mTitle
->getPartialURL();
1874 case MAG_REVISIONID
:
1875 return $wgArticle->getRevIdFetched();
1877 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1878 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1879 case MAG_CURRENTDAYNAME
:
1880 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1881 case MAG_CURRENTYEAR
:
1882 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1883 case MAG_CURRENTTIME
:
1884 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1885 case MAG_CURRENTWEEK
:
1886 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1887 case MAG_CURRENTDOW
:
1888 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1889 case MAG_NUMBEROFARTICLES
:
1890 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1901 * initialise the magic variables (like CURRENTMONTHNAME)
1905 function initialiseVariables() {
1906 $fname = 'Parser::initialiseVariables';
1907 wfProfileIn( $fname );
1908 global $wgVariableIDs;
1909 $this->mVariables
= array();
1910 foreach ( $wgVariableIDs as $id ) {
1911 $mw =& MagicWord
::get( $id );
1912 $mw->addToArray( $this->mVariables
, $id );
1914 wfProfileOut( $fname );
1918 * Replace magic variables, templates, and template arguments
1919 * with the appropriate text. Templates are substituted recursively,
1920 * taking care to avoid infinite loops.
1922 * Note that the substitution depends on value of $mOutputType:
1923 * OT_WIKI: only {{subst:}} templates
1924 * OT_MSG: only magic variables
1925 * OT_HTML: all templates and magic variables
1927 * @param string $tex The text to transform
1928 * @param array $args Key-value pairs representing template parameters to substitute
1931 function replaceVariables( $text, $args = array() ) {
1933 # Prevent too big inclusions
1934 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1938 $fname = 'Parser::replaceVariables';
1939 wfProfileIn( $fname );
1941 $titleChars = Title
::legalChars();
1943 # This function is called recursively. To keep track of arguments we need a stack:
1944 array_push( $this->mArgStack
, $args );
1946 # Variable substitution
1947 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1949 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1950 # Argument substitution
1951 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1953 # Template substitution
1954 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1955 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1957 array_pop( $this->mArgStack
);
1959 wfProfileOut( $fname );
1964 * Replace magic variables
1967 function variableSubstitution( $matches ) {
1968 $fname = 'parser::variableSubstitution';
1969 $varname = $matches[1];
1970 wfProfileIn( $fname );
1971 if ( !$this->mVariables
) {
1972 $this->initialiseVariables();
1975 if ( $this->mOutputType
== OT_WIKI
) {
1976 # Do only magic variables prefixed by SUBST
1977 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1978 if (!$mwSubst->matchStartAndRemove( $varname ))
1980 # Note that if we don't substitute the variable below,
1981 # we don't remove the {{subst:}} magic word, in case
1982 # it is a template rather than a magic variable.
1984 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1985 $id = $this->mVariables
[$varname];
1986 $text = $this->getVariableValue( $id );
1987 $this->mOutput
->mContainsOldMagic
= true;
1989 $text = $matches[0];
1991 wfProfileOut( $fname );
1995 # Split template arguments
1996 function getTemplateArgs( $argsString ) {
1997 if ( $argsString === '' ) {
2001 $args = explode( '|', substr( $argsString, 1 ) );
2003 # If any of the arguments contains a '[[' but no ']]', it needs to be
2004 # merged with the next arg because the '|' character between belongs
2005 # to the link syntax and not the template parameter syntax.
2006 $argc = count($args);
2008 for ( $i = 0; $i < $argc-1; $i++
) {
2009 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2010 $args[$i] .= '|'.$args[$i+
1];
2011 array_splice($args, $i+
1, 1);
2021 * Return the text of a template, after recursively
2022 * replacing any variables or templates within the template.
2024 * @param array $matches The parts of the template
2025 * $matches[1]: the title, i.e. the part before the |
2026 * $matches[2]: the parameters (including a leading |), if any
2027 * @return string the text of the template
2030 function braceSubstitution( $matches ) {
2031 global $wgLinkCache, $wgContLang;
2032 $fname = 'Parser::braceSubstitution';
2033 wfProfileIn( $fname );
2041 # Need to know if the template comes at the start of a line,
2042 # to treat the beginning of the template like the beginning
2043 # of a line for tables and block-level elements.
2044 $linestart = $matches[1];
2046 # $part1 is the bit before the first |, and must contain only title characters
2047 # $args is a list of arguments, starting from index 0, not including $part1
2049 $part1 = $matches[2];
2050 # If the third subpattern matched anything, it will start with |
2052 $args = $this->getTemplateArgs($matches[3]);
2053 $argc = count( $args );
2055 # Don't parse {{{}}} because that's only for template arguments
2056 if ( $linestart === '{' ) {
2057 $text = $matches[0];
2064 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2065 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2066 # One of two possibilities is true:
2067 # 1) Found SUBST but not in the PST phase
2068 # 2) Didn't find SUBST and in the PST phase
2069 # In either case, return without further processing
2070 $text = $matches[0];
2076 # MSG, MSGNW and INT
2079 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2080 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2084 # int: is the wikitext equivalent of wfMsg()
2085 $mwInt =& MagicWord
::get( MAG_INT
);
2086 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2087 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2088 $text = $linestart . wfMsgReal( $part1, $args, true );
2093 # msg: is the wikitext equivalent of wfMsgForContent()
2094 $mwMsg =& MagicWord
::get( MAG_MSG
);
2095 if ( $mwMsg->matchStartAndRemove( $part1 ) ) {
2096 if ( $this->incrementIncludeCount( 'msg:'.$part1 ) ) {
2097 $text = $linestart . wfMsgReal( $part1, $args, true, true );
2105 # Check for NS: (namespace expansion)
2106 $mwNs = MagicWord
::get( MAG_NS
);
2107 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2108 if ( intval( $part1 ) ) {
2109 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2112 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2113 if ( !is_null( $index ) ) {
2114 $text = $linestart . $wgContLang->getNsText( $index );
2121 # LOCALURL and LOCALURLE
2123 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2124 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2126 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2127 $func = 'getLocalURL';
2128 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2129 $func = 'escapeLocalURL';
2134 if ( $func !== '' ) {
2135 $title = Title
::newFromText( $part1 );
2136 if ( !is_null( $title ) ) {
2138 $text = $linestart . $title->$func( $args[0] );
2140 $text = $linestart . $title->$func();
2148 if ( !$found && $argc == 1 ) {
2149 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2150 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2151 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2156 # Template table test
2158 # Did we encounter this template already? If yes, it is in the cache
2159 # and we need to check for loops.
2160 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2163 # Infinite loop test
2164 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2167 $text = $linestart .
2169 '<!-- WARNING: template loop detected -->';
2170 wfDebug( "$fname: template loop broken at '$part1'\n" );
2172 # set $text to cached message.
2173 $text = $linestart . $this->mTemplates
[$part1];
2177 # Load from database
2178 $replaceHeadings = false;
2180 $lastPathLevel = $this->mTemplatePath
;
2183 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2184 if ($subpage !== '') {
2185 $ns = $this->mTitle
->getNamespace();
2187 $title = Title
::newFromText( $part1, $ns );
2188 if ( !is_null( $title ) && !$title->isExternal() ) {
2189 # Check for excessive inclusion
2190 $dbk = $title->getPrefixedDBkey();
2191 if ( $this->incrementIncludeCount( $dbk ) ) {
2192 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2193 # Capture special page output
2194 $text = SpecialPage
::capturePath( $title );
2195 if ( $text && !is_object( $text ) ) {
2199 $this->mOutput
->setCacheTime( -1 );
2202 $article = new Article( $title );
2203 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2204 if ( $articleContent !== false ) {
2206 $text = $articleContent;
2207 $replaceHeadings = true;
2212 # If the title is valid but undisplayable, make a link to it
2213 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2214 $text = '[['.$title->getPrefixedText().']]';
2218 # Template cache array insertion
2220 $this->mTemplates
[$part1] = $text;
2221 $text = $linestart . $text;
2226 # Recursive parsing, escaping and link table handling
2227 # Only for HTML output
2228 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2229 $text = wfEscapeWikiText( $text );
2230 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2231 # Clean up argument array
2232 $assocArgs = array();
2234 foreach( $args as $arg ) {
2235 $eqpos = strpos( $arg, '=' );
2236 if ( $eqpos === false ) {
2237 $assocArgs[$index++
] = $arg;
2239 $name = trim( substr( $arg, 0, $eqpos ) );
2240 $value = trim( substr( $arg, $eqpos+
1 ) );
2241 if ( $value === false ) {
2244 if ( $name !== false ) {
2245 $assocArgs[$name] = $value;
2250 # Add a new element to the templace recursion path
2251 $this->mTemplatePath
[$part1] = 1;
2253 if( $this->mOutputType
== OT_HTML
) {
2254 $text = $this->strip( $text, $this->mStripState
);
2255 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2257 $text = $this->replaceVariables( $text, $assocArgs );
2259 # Resume the link cache and register the inclusion as a link
2260 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2261 $wgLinkCache->addLinkObj( $title );
2264 # If the template begins with a table or block-level
2265 # element, it should be treated as beginning a new line.
2266 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2267 $text = "\n" . $text;
2270 # Prune lower levels off the recursion check path
2271 $this->mTemplatePath
= $lastPathLevel;
2274 wfProfileOut( $fname );
2278 # Replace raw HTML by a placeholder
2279 # Add a blank line preceding, to prevent it from mucking up
2280 # immediately preceding headings
2281 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2283 # replace ==section headers==
2284 # XXX this needs to go away once we have a better parser.
2285 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2286 if( !is_null( $title ) )
2287 $encodedname = base64_encode($title->getPrefixedDBkey());
2289 $encodedname = base64_encode("");
2290 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2291 PREG_SPLIT_DELIM_CAPTURE
);
2294 for( $i = 0; $i < count($m); $i +
= 2 ) {
2296 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2298 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2302 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2303 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2304 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2312 # Prune lower levels off the recursion check path
2313 $this->mTemplatePath
= $lastPathLevel;
2316 wfProfileOut( $fname );
2319 wfProfileOut( $fname );
2325 * Triple brace replacement -- used for template arguments
2328 function argSubstitution( $matches ) {
2329 $arg = trim( $matches[1] );
2330 $text = $matches[0];
2331 $inputArgs = end( $this->mArgStack
);
2333 if ( array_key_exists( $arg, $inputArgs ) ) {
2334 $text = $inputArgs[$arg];
2341 * Returns true if the function is allowed to include this entity
2344 function incrementIncludeCount( $dbk ) {
2345 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2346 $this->mIncludeCount
[$dbk] = 0;
2348 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2356 * This function accomplishes several tasks:
2357 * 1) Auto-number headings if that option is enabled
2358 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2359 * 3) Add a Table of contents on the top for users who have enabled the option
2360 * 4) Auto-anchor headings
2362 * It loops through all headlines, collects the necessary data, then splits up the
2363 * string and re-inserts the newly formatted headlines.
2365 * @param string $text
2366 * @param boolean $isMain
2369 function formatHeadings( $text, $isMain=true ) {
2370 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2372 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2374 $forceTocHere = false;
2375 if( !$this->mTitle
->userCanEdit() ) {
2378 $showEditLink = $this->mOptions
->getEditSection();
2381 # Inhibit editsection links if requested in the page
2382 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2383 if( $esw->matchAndRemove( $text ) ) {
2386 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2388 $mw =& MagicWord
::get( MAG_NOTOC
);
2389 if( $mw->matchAndRemove( $text ) ) {
2393 # Get all headlines for numbering them and adding funky stuff like [edit]
2394 # links - this is for later, but we need the number of headlines right now
2395 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2397 # if there are fewer than 4 headlines in the article, do not show TOC
2398 if( $numMatches < 4 ) {
2402 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2403 # override above conditions and always show TOC at that place
2405 $mw =& MagicWord
::get( MAG_TOC
);
2406 if($mw->match( $text ) ) {
2408 $forceTocHere = true;
2410 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2411 # override above conditions and always show TOC above first header
2412 $mw =& MagicWord
::get( MAG_FORCETOC
);
2413 if ($mw->matchAndRemove( $text ) ) {
2418 # Never ever show TOC if no headers
2419 if( $numMatches < 1 ) {
2423 # We need this to perform operations on the HTML
2424 $sk =& $this->mOptions
->getSkin();
2428 $sectionCount = 0; # headlineCount excluding template sections
2430 # Ugh .. the TOC should have neat indentation levels which can be
2431 # passed to the skin functions. These are determined here
2435 $sublevelCount = array();
2436 $levelCount = array();
2443 foreach( $matches[3] as $headline ) {
2445 $templatetitle = '';
2446 $templatesection = 0;
2449 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2451 $templatetitle = base64_decode($mat[1]);
2452 $templatesection = 1 +
(int)base64_decode($mat[2]);
2453 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2457 $prevlevel = $level;
2458 $prevtoclevel = $toclevel;
2460 $level = $matches[1][$headlineCount];
2462 if( $doNumberHeadings ||
$doShowToc ) {
2464 if ( $level > $prevlevel ) {
2465 # Increase TOC level
2467 $sublevelCount[$toclevel] = 0;
2468 $toc .= $sk->tocIndent();
2470 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2471 # Decrease TOC level, find level to jump to
2473 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2474 # Can only go down to level 1
2477 for ($i = $toclevel; $i > 0; $i--) {
2478 if ( $levelCount[$i] == $level ) {
2479 # Found last matching level
2483 elseif ( $levelCount[$i] < $level ) {
2484 # Found first matching level below current level
2491 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2494 # No change in level, end TOC line
2495 $toc .= $sk->tocLineEnd();
2498 $levelCount[$toclevel] = $level;
2500 # count number of headlines for each level
2501 @$sublevelCount[$toclevel]++
;
2503 for( $i = 1; $i <= $toclevel; $i++
) {
2504 if( !empty( $sublevelCount[$i] ) ) {
2508 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2514 # The canonized header is a version of the header text safe to use for links
2515 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2516 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2517 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2519 # Remove link placeholders by the link text.
2520 # <!--LINK number-->
2522 # link text with suffix
2523 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2524 "\$this->mLinkHolders['texts'][\$1]",
2525 $canonized_headline );
2526 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2527 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2528 $canonized_headline );
2531 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2532 $tocline = trim( $canonized_headline );
2533 $canonized_headline = urlencode( Sanitizer
::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2534 $replacearray = array(
2538 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2539 $refers[$headlineCount] = $canonized_headline;
2541 # count how many in assoc. array so we can track dupes in anchors
2542 @$refers[$canonized_headline]++
;
2543 $refcount[$headlineCount]=$refers[$canonized_headline];
2545 # Don't number the heading if it is the only one (looks silly)
2546 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2547 # the two are different if the line contains a link
2548 $headline=$numbering . ' ' . $headline;
2551 # Create the anchor for linking from the TOC to the section
2552 $anchor = $canonized_headline;
2553 if($refcount[$headlineCount] > 1 ) {
2554 $anchor .= '_' . $refcount[$headlineCount];
2556 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2557 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2559 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2560 if ( empty( $head[$headlineCount] ) ) {
2561 $head[$headlineCount] = '';
2564 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2566 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2569 # give headline the correct <h#> tag
2570 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2578 $toc .= $sk->tocUnindent( $toclevel - 1 );
2579 $toc = $sk->tocList( $toc );
2582 # split up and insert constructed headlines
2584 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2587 foreach( $blocks as $block ) {
2588 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2589 # This is the [edit] link that appears for the top block of text when
2590 # section editing is enabled
2592 # Disabled because it broke block formatting
2593 # For example, a bullet point in the top line
2594 # $full .= $sk->editSectionLink(0);
2597 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2598 # Top anchor now in skin
2602 if( !empty( $head[$i] ) ) {
2608 $mw =& MagicWord
::get( MAG_TOC
);
2609 return $mw->replace( $toc, $full );
2616 * Return an HTML link for the "ISBN 123456" text
2619 function magicISBN( $text ) {
2620 $fname = 'Parser::magicISBN';
2621 wfProfileIn( $fname );
2623 $a = split( 'ISBN ', ' '.$text );
2624 if ( count ( $a ) < 2 ) {
2625 wfProfileOut( $fname );
2628 $text = substr( array_shift( $a ), 1);
2629 $valid = '0123456789-Xx';
2631 foreach ( $a as $x ) {
2632 $isbn = $blank = '' ;
2633 while ( ' ' == $x{0} ) {
2635 $x = substr( $x, 1 );
2637 if ( $x == '' ) { # blank isbn
2638 $text .= "ISBN $blank";
2641 while ( strstr( $valid, $x{0} ) != false ) {
2643 $x = substr( $x, 1 );
2645 $num = str_replace( '-', '', $isbn );
2646 $num = str_replace( ' ', '', $num );
2647 $num = str_replace( 'x', 'X', $num );
2650 $text .= "ISBN $blank$x";
2652 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2653 $text .= '<a href="' .
2654 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2655 "\" class=\"internal\">ISBN $isbn</a>";
2659 wfProfileOut( $fname );
2664 * Return an HTML link for the "RFC 1234" text
2667 * @param string $text Text to be processed
2668 * @param string $keyword Magic keyword to use (default RFC)
2669 * @param string $urlmsg Interface message to use (default rfcurl)
2672 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2674 $valid = '0123456789';
2677 $a = split( $keyword, ' '.$text );
2678 if ( count ( $a ) < 2 ) {
2681 $text = substr( array_shift( $a ), 1);
2683 /* Check if keyword is preceed by [[.
2684 * This test is made here cause of the array_shift above
2685 * that prevent the test to be done in the foreach.
2687 if ( substr( $text, -2 ) == '[[' ) {
2691 foreach ( $a as $x ) {
2692 /* token might be empty if we have RFC RFC 1234 */
2700 /** remove and save whitespaces in $blank */
2701 while ( $x{0} == ' ' ) {
2703 $x = substr( $x, 1 );
2706 /** remove and save the rfc number in $id */
2707 while ( strstr( $valid, $x{0} ) != false ) {
2709 $x = substr( $x, 1 );
2713 /* call back stripped spaces*/
2714 $text .= $keyword.$blank.$x;
2715 } elseif( $internal ) {
2717 $text .= $keyword.$id.$x;
2719 /* build the external link*/
2720 $url = wfMsg( $urlmsg, $id);
2721 $sk =& $this->mOptions
->getSkin();
2722 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2723 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2726 /* Check if the next RFC keyword is preceed by [[ */
2727 $internal = ( substr($x,-2) == '[[' );
2733 * Transform wiki markup when saving a page by doing \r\n -> \n
2734 * conversion, substitting signatures, {{subst:}} templates, etc.
2736 * @param string $text the text to transform
2737 * @param Title &$title the Title object for the current article
2738 * @param User &$user the User object describing the current user
2739 * @param ParserOptions $options parsing options
2740 * @param bool $clearState whether to clear the parser state first
2741 * @return string the altered wiki markup
2744 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2745 $this->mOptions
= $options;
2746 $this->mTitle
=& $title;
2747 $this->mOutputType
= OT_WIKI
;
2749 if ( $clearState ) {
2750 $this->clearState();
2753 $stripState = false;
2757 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2758 $text = $this->strip( $text, $stripState, false );
2759 $text = $this->pstPass2( $text, $user );
2760 $text = $this->unstrip( $text, $stripState );
2761 $text = $this->unstripNoWiki( $text, $stripState );
2766 * Pre-save transform helper function
2769 function pstPass2( $text, &$user ) {
2770 global $wgContLang, $wgLocaltimezone;
2772 # Variable replacement
2773 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2774 $text = $this->replaceVariables( $text );
2778 $n = $user->getName();
2779 $k = $user->getOption( 'nickname' );
2780 if ( '' == $k ) { $k = $n; }
2781 if ( isset( $wgLocaltimezone ) ) {
2782 $oldtz = getenv( 'TZ' );
2783 putenv( 'TZ='.$wgLocaltimezone );
2786 /* Note: This is the timestamp saved as hardcoded wikitext to
2787 * the database, we use $wgContLang here in order to give
2788 * everyone the same signiture and use the default one rather
2789 * than the one selected in each users preferences.
2791 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2792 ' (' . date( 'T' ) . ')';
2793 if ( isset( $wgLocaltimezone ) ) {
2794 putenv( 'TZ='.$oldtz );
2797 if( $user->getOption( 'fancysig' ) ) {
2800 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2802 $text = preg_replace( '/~~~~~/', $d, $text );
2803 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2804 $text = preg_replace( '/~~~/', $sigText, $text );
2806 # Context links: [[|name]] and [[name (context)|]]
2808 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2809 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2810 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2811 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2813 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2814 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2815 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2816 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2818 $t = $this->mTitle
->getText();
2819 if ( preg_match( $conpat, $t, $m ) ) {
2822 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2823 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2824 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2826 if ( '' == $context ) {
2827 $text = preg_replace( $p2, '[[\\1]]', $text );
2829 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2832 # Trim trailing whitespace
2833 # MAG_END (__END__) tag allows for trailing
2834 # whitespace to be deliberately included
2835 $text = rtrim( $text );
2836 $mw =& MagicWord
::get( MAG_END
);
2837 $mw->matchAndRemove( $text );
2843 * Set up some variables which are usually set up in parse()
2844 * so that an external function can call some class members with confidence
2847 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2848 $this->mTitle
=& $title;
2849 $this->mOptions
= $options;
2850 $this->mOutputType
= $outputType;
2851 if ( $clearState ) {
2852 $this->clearState();
2857 * Transform a MediaWiki message by replacing magic variables.
2859 * @param string $text the text to transform
2860 * @param ParserOptions $options options
2861 * @return string the text with variables substituted
2864 function transformMsg( $text, $options ) {
2866 static $executing = false;
2868 # Guard against infinite recursion
2874 $this->mTitle
= $wgTitle;
2875 $this->mOptions
= $options;
2876 $this->mOutputType
= OT_MSG
;
2877 $this->clearState();
2878 $text = $this->replaceVariables( $text );
2885 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2886 * Callback will be called with the text within
2887 * Transform and return the text within
2890 function setHook( $tag, $callback ) {
2891 $oldVal = @$this->mTagHooks
[$tag];
2892 $this->mTagHooks
[$tag] = $callback;
2897 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2898 * Placeholders created in Skin::makeLinkObj()
2899 * Returns an array of links found, indexed by PDBK:
2903 * $options is a bit field, RLH_FOR_UPDATE to select for update
2905 function replaceLinkHolders( &$text, $options = 0 ) {
2906 global $wgUser, $wgLinkCache;
2907 global $wgOutputReplace;
2909 $fname = 'Parser::replaceLinkHolders';
2910 wfProfileIn( $fname );
2914 $sk = $this->mOptions
->getSkin();
2916 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
2917 wfProfileIn( $fname.'-check' );
2918 $dbr =& wfGetDB( DB_SLAVE
);
2919 $page = $dbr->tableName( 'page' );
2920 $threshold = $wgUser->getOption('stubthreshold');
2923 asort( $this->mLinkHolders
['namespaces'] );
2927 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
2929 $title = $this->mLinkHolders
['titles'][$key];
2931 # Skip invalid entries.
2932 # Result will be ugly, but prevents crash.
2933 if ( is_null( $title ) ) {
2936 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2938 # Check if it's in the link cache already
2939 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2940 $colours[$pdbk] = 1;
2941 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2942 $colours[$pdbk] = 0;
2944 # Not in the link cache, add it to the query
2945 if ( !isset( $current ) ) {
2947 $query = "SELECT page_id, page_namespace, page_title";
2948 if ( $threshold > 0 ) {
2949 $query .= ', page_len, page_is_redirect';
2951 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2952 } elseif ( $current != $val ) {
2954 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2959 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
2964 if ( $options & RLH_FOR_UPDATE
) {
2965 $query .= ' FOR UPDATE';
2968 $res = $dbr->query( $query, $fname );
2970 # Fetch data and form into an associative array
2971 # non-existent = broken
2974 while ( $s = $dbr->fetchObject($res) ) {
2975 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2976 $pdbk = $title->getPrefixedDBkey();
2977 $wgLinkCache->addGoodLinkObj( $s->page_id
, $title );
2979 if ( $threshold > 0 ) {
2980 $size = $s->page_len
;
2981 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
2982 $colours[$pdbk] = 1;
2984 $colours[$pdbk] = 2;
2987 $colours[$pdbk] = 1;
2991 wfProfileOut( $fname.'-check' );
2993 # Construct search and replace arrays
2994 wfProfileIn( $fname.'-construct' );
2995 $wgOutputReplace = array();
2996 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
2997 $pdbk = $pdbks[$key];
2998 $searchkey = "<!--LINK $key-->";
2999 $title = $this->mLinkHolders
['titles'][$key];
3000 if ( empty( $colours[$pdbk] ) ) {
3001 $wgLinkCache->addBadLinkObj( $title );
3002 $colours[$pdbk] = 0;
3003 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3004 $this->mLinkHolders
['texts'][$key],
3005 $this->mLinkHolders
['queries'][$key] );
3006 } elseif ( $colours[$pdbk] == 1 ) {
3007 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3008 $this->mLinkHolders
['texts'][$key],
3009 $this->mLinkHolders
['queries'][$key] );
3010 } elseif ( $colours[$pdbk] == 2 ) {
3011 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3012 $this->mLinkHolders
['texts'][$key],
3013 $this->mLinkHolders
['queries'][$key] );
3016 wfProfileOut( $fname.'-construct' );
3019 wfProfileIn( $fname.'-replace' );
3021 $text = preg_replace_callback(
3022 '/(<!--LINK .*?-->)/',
3023 "wfOutputReplaceMatches",
3026 wfProfileOut( $fname.'-replace' );
3029 # Now process interwiki link holders
3030 # This is quite a bit simpler than internal links
3031 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3032 wfProfileIn( $fname.'-interwiki' );
3033 # Make interwiki link HTML
3034 $wgOutputReplace = array();
3035 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3036 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3037 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3040 $text = preg_replace_callback(
3041 '/<!--IWLINK (.*?)-->/',
3042 "wfOutputReplaceMatches",
3044 wfProfileOut( $fname.'-interwiki' );
3047 wfProfileOut( $fname );
3052 * Replace <!--LINK--> link placeholders with plain text of links
3053 * (not HTML-formatted).
3054 * @param string $text
3057 function replaceLinkHoldersText( $text ) {
3058 global $wgUser, $wgLinkCache;
3059 global $wgOutputReplace;
3061 $fname = 'Parser::replaceLinkHoldersText';
3062 wfProfileIn( $fname );
3064 $text = preg_replace_callback(
3065 '/<!--(LINK|IWLINK) (.*?)-->/',
3066 array( &$this, 'replaceLinkHoldersTextCallback' ),
3069 wfProfileOut( $fname );
3074 * @param array $matches
3078 function replaceLinkHoldersTextCallback( $matches ) {
3079 $type = $matches[1];
3081 if( $type == 'LINK' ) {
3082 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3083 return $this->mLinkHolders
['texts'][$key];
3085 } elseif( $type == 'IWLINK' ) {
3086 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3087 return $this->mInterwikiLinkHolders
['texts'][$key];
3094 * Renders an image gallery from a text with one line per image.
3095 * text labels may be given by using |-style alternative text. E.g.
3096 * Image:one.jpg|The number "1"
3097 * Image:tree.jpg|A tree
3098 * given as text will return the HTML of a gallery with two images,
3099 * labeled 'The number "1"' and
3104 function renderImageGallery( $text ) {
3106 global $wgUser, $wgParser, $wgTitle;
3107 $parserOptions = ParserOptions
::newFromUser( $wgUser );
3109 global $wgLinkCache;
3110 $ig = new ImageGallery();
3111 $ig->setShowBytes( false );
3112 $ig->setShowFilename( false );
3113 $lines = explode( "\n", $text );
3115 foreach ( $lines as $line ) {
3116 # match lines like these:
3117 # Image:someimage.jpg|This is some image
3118 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3120 if ( count( $matches ) == 0 ) {
3123 $nt = Title
::newFromURL( $matches[1] );
3124 if( is_null( $nt ) ) {
3125 # Bogus title. Ignore these so we don't bomb out later.
3128 if ( isset( $matches[3] ) ) {
3129 $label = $matches[3];
3134 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
3135 $html = $html->mText
;
3137 $ig->add( new Image( $nt ), $html );
3138 $wgLinkCache->addImageLinkObj( $nt );
3140 return $ig->toHTML();
3144 * Parse image options text and use it to make an image
3146 function makeImage( &$nt, $options ) {
3147 global $wgContLang, $wgUseImageResize;
3148 global $wgUser, $wgThumbLimits;
3152 # Check if the options text is of the form "options|alt text"
3154 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3155 # * left no resizing, just left align. label is used for alt= only
3156 # * right same, but right aligned
3157 # * none same, but not aligned
3158 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3159 # * center center the image
3160 # * framed Keep original image size, no magnify-button.
3162 $part = explode( '|', $options);
3164 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3165 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3166 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3167 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3168 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3169 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3170 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3173 $width = $height = $framed = $thumb = false;
3174 $manual_thumb = "" ;
3176 foreach( $part as $key => $val ) {
3177 $val_parts = explode ( "=" , $val , 2 ) ;
3178 $left_part = array_shift ( $val_parts ) ;
3179 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3181 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3182 # use manually specified thumbnail
3184 $manual_thumb = array_shift ( $val_parts ) ;
3185 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3186 # remember to set an alignment, don't render immediately
3188 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3189 # remember to set an alignment, don't render immediately
3191 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3192 # remember to set an alignment, don't render immediately
3194 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3195 # remember to set an alignment, don't render immediately
3197 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3198 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3199 # $match is the image width in pixels
3200 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3201 $width = intval( $m[1] );
3202 $height = intval( $m[2] );
3204 $width = intval($match);
3206 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3212 # Strip bad stuff out of the alt text
3213 $alt = $this->replaceLinkHoldersText( $caption );
3214 $alt = Sanitizer
::stripAllTags( $alt );
3216 # Linker does the rest
3217 $sk =& $this->mOptions
->getSkin();
3218 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3224 * @package MediaWiki
3228 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3229 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3230 var $mVersion; # Compatibility check
3231 var $mTitleText; # title text of the chosen language variant
3233 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3234 $containsOldMagic = false, $titletext = '' )
3236 $this->mText
= $text;
3237 $this->mLanguageLinks
= $languageLinks;
3238 $this->mCategoryLinks
= $categoryLinks;
3239 $this->mContainsOldMagic
= $containsOldMagic;
3240 $this->mCacheTime
= '';
3241 $this->mVersion
= MW_PARSER_VERSION
;
3242 $this->mTitleText
= $titletext;
3245 function getText() { return $this->mText
; }
3246 function getLanguageLinks() { return $this->mLanguageLinks
; }
3247 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3248 function getCacheTime() { return $this->mCacheTime
; }
3249 function getTitleText() { return $this->mTitleText
; }
3250 function containsOldMagic() { return $this->mContainsOldMagic
; }
3251 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3252 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3253 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3254 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3255 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3256 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3258 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3260 function merge( $other ) {
3261 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3262 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3263 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3267 * Return true if this cached output object predates the global or
3268 * per-article cache invalidation timestamps, or if it comes from
3269 * an incompatible older version.
3271 * @param string $touched the affected article's last touched timestamp
3275 function expired( $touched ) {
3276 global $wgCacheEpoch;
3277 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3278 $this->getCacheTime() <= $touched ||
3279 $this->getCacheTime() <= $wgCacheEpoch ||
3280 !isset( $this->mVersion
) ||
3281 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3286 * Set options of the Parser
3288 * @package MediaWiki
3292 # All variables are private
3293 var $mUseTeX; # Use texvc to expand <math> tags
3294 var $mUseDynamicDates; # Use DateFormatter to format dates
3295 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3296 var $mAllowExternalImages; # Allow external images inline
3297 var $mSkin; # Reference to the preferred skin
3298 var $mDateFormat; # Date format index
3299 var $mEditSection; # Create "edit section" links
3300 var $mNumberHeadings; # Automatically number headings
3301 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3303 function getUseTeX() { return $this->mUseTeX
; }
3304 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3305 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3306 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3307 function getSkin() { return $this->mSkin
; }
3308 function getDateFormat() { return $this->mDateFormat
; }
3309 function getEditSection() { return $this->mEditSection
; }
3310 function getNumberHeadings() { return $this->mNumberHeadings
; }
3311 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3314 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3315 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3316 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3317 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3318 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3319 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3320 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3321 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3323 function setSkin( &$x ) { $this->mSkin
=& $x; }
3325 function ParserOptions() {
3327 $this->initialiseFromUser( $wgUser );
3331 * Get parser options
3334 function newFromUser( &$user ) {
3335 $popts = new ParserOptions
;
3336 $popts->initialiseFromUser( $user );
3340 /** Get user options */
3341 function initialiseFromUser( &$userInput ) {
3342 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3343 $wgAllowSpecialInclusion;
3344 $fname = 'ParserOptions::initialiseFromUser';
3345 wfProfileIn( $fname );
3346 if ( !$userInput ) {
3348 $user->setLoaded( true );
3350 $user =& $userInput;
3353 $this->mUseTeX
= $wgUseTeX;
3354 $this->mUseDynamicDates
= $wgUseDynamicDates;
3355 $this->mInterwikiMagic
= $wgInterwikiMagic;
3356 $this->mAllowExternalImages
= $wgAllowExternalImages;
3357 wfProfileIn( $fname.'-skin' );
3358 $this->mSkin
=& $user->getSkin();
3359 wfProfileOut( $fname.'-skin' );
3360 $this->mDateFormat
= $user->getOption( 'date' );
3361 $this->mEditSection
= $user->getOption( 'editsection' );
3362 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3363 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3364 wfProfileOut( $fname );
3369 * Callback function used by Parser::replaceLinkHolders()
3370 * to substitute link placeholders.
3372 function &wfOutputReplaceMatches( $matches ) {
3373 global $wgOutputReplace;
3374 return $wgOutputReplace[$matches[1]];
3378 * Return the total number of articles
3380 function wfNumberOfArticles() {
3381 global $wgNumberOfArticles;
3384 return $wgNumberOfArticles;
3388 * Get various statistics from the database
3391 function wfLoadSiteStats() {
3392 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3393 $fname = 'wfLoadSiteStats';
3395 if ( -1 != $wgNumberOfArticles ) return;
3396 $dbr =& wfGetDB( DB_SLAVE
);
3397 $s = $dbr->selectRow( 'site_stats',
3398 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3399 array( 'ss_row_id' => 1 ), $fname
3402 if ( $s === false ) {
3405 $wgTotalViews = $s->ss_total_views
;
3406 $wgTotalEdits = $s->ss_total_edits
;
3407 $wgNumberOfArticles = $s->ss_good_articles
;
3413 * Basicly replacing " > and < with HTML entities ( ", >, <)
3415 * @param string $in Text that might contain HTML tags
3416 * @return string Escaped string
3418 function wfEscapeHTMLTagsOnly( $in ) {
3420 array( '"', '>', '<' ),
3421 array( '"', '>', '<' ),