4 * File for Parser and related classes
10 * Update this version number when the ParserOutput format
11 * changes in an incompatible way, so the parser cache
12 * can automatically discard old data.
14 define( 'MW_PARSER_VERSION', '1.4.0' );
17 * Variable substitution O(N^2) attack
19 * Without countermeasures, it would be possible to attack the parser by saving
20 * a page filled with a large number of inclusions of large pages. The size of
21 * the generated page would be proportional to the square of the input size.
22 * Hence, we limit the number of inclusions of any given page, thus bringing any
23 * attack back to O(N).
26 define( 'MAX_INCLUDE_REPEAT', 100 );
27 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
29 define( 'RLH_FOR_UPDATE', 1 );
31 # Allowed values for $mOutputType
32 define( 'OT_HTML', 1 );
33 define( 'OT_WIKI', 2 );
34 define( 'OT_MSG' , 3 );
36 # string parameter for extractTags which will cause it
37 # to strip HTML comments in addition to regular
38 # <XML>-style tags. This should not be anything we
39 # may want to use in wikisyntax
40 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
42 # prefix for escaping, used in two functions at least
43 define( 'UNIQ_PREFIX', 'NaodW29');
45 # Constants needed for external link processing
46 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
47 define( 'HTTP_PROTOCOLS', 'http|https' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
76 * objects: $wgLang, $wgDateFormatter, $wgLinkCache
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
103 var $mOptions, $mTitle, $mOutputType,
104 $mTemplates, // cache of already loaded templates, avoids
105 // multiple SQL queries for the same string
106 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
107 // in this path. Used for loop detection.
117 $this->mTemplates
= array();
118 $this->mTemplatePath
= array();
119 $this->mTagHooks
= array();
128 function clearState() {
129 $this->mOutput
= new ParserOutput
;
130 $this->mAutonumber
= 0;
131 $this->mLastSection
= '';
132 $this->mDTopen
= false;
133 $this->mVariables
= false;
134 $this->mIncludeCount
= array();
135 $this->mStripState
= array();
136 $this->mArgStack
= array();
137 $this->mInPre
= false;
141 * First pass--just handle <nowiki> sections, pass the rest off
142 * to internalParse() which does all the real work.
145 * @param string $text Text we want to parse
146 * @param Title &$title A title object
147 * @param array $options
148 * @param boolean $linestart
149 * @param boolean $clearState
150 * @return ParserOutput a ParserOutput
152 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
153 global $wgUseTidy, $wgContLang;
154 $fname = 'Parser::parse';
155 wfProfileIn( $fname );
161 $this->mOptions
= $options;
162 $this->mTitle
=& $title;
163 $this->mOutputType
= OT_HTML
;
166 global $fnord; $fnord = 1;
167 //$text = $this->strip( $text, $this->mStripState );
168 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
169 $x =& $this->mStripState
;
170 $text = $this->strip( $text, $x );
172 $text = $this->internalParse( $text, $linestart );
173 $text = $this->unstrip( $text, $this->mStripState
);
174 # Clean up special characters, only run once, next-to-last before doBlockLevels
177 # french spaces, last one Guillemet-left
178 # only if there is something before the space
179 '/(.) (?=\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
180 # french spaces, Guillemet-right
181 '/(\\302\\253) /i' => '\\1 ',
182 '/<hr *>/i' => '<hr />',
183 '/<br *>/i' => '<br />',
184 '/<center *>/i' => '<div class="center">',
185 '/<\\/center *>/i' => '</div>',
186 # Clean up spare ampersands; note that we probably ought to be
187 # more careful about named entities.
188 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
190 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
193 # french spaces, last one Guillemet-left
194 '/ (\\?|:|;|!|\\302\\273)/i' => ' \\1',
195 # french spaces, Guillemet-right
196 '/(\\302\\253) /i' => '\\1 ',
197 '/<center *>/i' => '<div class="center">',
198 '/<\\/center *>/i' => '</div>'
200 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
203 $text = $this->doBlockLevels( $text, $linestart );
205 $this->replaceLinkHolders( $text );
206 $text = $wgContLang->convert($text);
208 $text = $this->unstripNoWiki( $text, $this->mStripState
);
211 $text = Parser
::tidy($text);
214 $this->mOutput
->setText( $text );
215 wfProfileOut( $fname );
216 return $this->mOutput
;
220 * Get a random string
225 function getRandomString() {
226 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
230 * Replaces all occurrences of <$tag>content</$tag> in the text
231 * with a random marker and returns the new text. the output parameter
232 * $content will be an associative array filled with data on the form
233 * $unique_marker => content.
235 * If $content is already set, the additional entries will be appended
236 * If $tag is set to STRIP_COMMENTS, the function will extract
237 * <!-- HTML comments -->
242 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
243 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
250 while ( '' != $text ) {
251 if($tag==STRIP_COMMENTS
) {
252 $p = preg_split( '/<!--/i', $text, 2 );
254 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
257 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
260 if($tag==STRIP_COMMENTS
) {
261 $q = preg_split( '/-->/i', $p[1], 2 );
263 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
265 $marker = $rnd . sprintf('%08X', $n++
);
266 $content[$marker] = $q[0];
267 $stripped .= $marker;
275 * Strips and renders nowiki, pre, math, hiero
276 * If $render is set, performs necessary rendering operations on plugins
277 * Returns the text, and fills an array with data needed in unstrip()
278 * If the $state is already a valid strip state, it adds to the state
280 * @param bool $stripcomments when set, HTML comments <!-- like this -->
281 * will be stripped in addition to other tags. This is important
282 * for section editing, where these comments cause confusion when
283 * counting the sections in the wikisource
287 function strip( $text, &$state, $stripcomments = false ) {
288 $render = ($this->mOutputType
== OT_HTML
);
289 $html_content = array();
290 $nowiki_content = array();
291 $math_content = array();
292 $pre_content = array();
293 $comment_content = array();
294 $ext_content = array();
295 $gallery_content = array();
297 # Replace any instances of the placeholders
298 $uniq_prefix = UNIQ_PREFIX
;
299 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
302 global $wgRawHtml, $wgWhitelistEdit;
303 if( $wgRawHtml && $wgWhitelistEdit ) {
304 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
305 foreach( $html_content as $marker => $content ) {
307 # Raw and unchecked for validity.
308 $html_content[$marker] = $content;
310 $html_content[$marker] = '<html>'.$content.'</html>';
316 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
317 foreach( $nowiki_content as $marker => $content ) {
319 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
321 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
326 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
327 foreach( $math_content as $marker => $content ){
329 if( $this->mOptions
->getUseTeX() ) {
330 $math_content[$marker] = renderMath( $content );
332 $math_content[$marker] = '<math>'.$content.'<math>';
335 $math_content[$marker] = '<math>'.$content.'</math>';
340 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
341 foreach( $pre_content as $marker => $content ){
343 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
345 $pre_content[$marker] = '<pre>'.$content.'</pre>';
350 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
351 foreach( $gallery_content as $marker => $content ) {
352 require_once( 'ImageGallery.php' );
354 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
356 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
362 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
363 foreach( $comment_content as $marker => $content ){
364 $comment_content[$marker] = '<!--'.$content.'-->';
369 foreach ( $this->mTagHooks
as $tag => $callback ) {
370 $ext_contents[$tag] = array();
371 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
372 foreach( $ext_content[$tag] as $marker => $content ) {
374 $ext_content[$tag][$marker] = $callback( $content );
376 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
381 # Merge state with the pre-existing state, if there is one
383 $state['html'] = $state['html'] +
$html_content;
384 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
385 $state['math'] = $state['math'] +
$math_content;
386 $state['pre'] = $state['pre'] +
$pre_content;
387 $state['comment'] = $state['comment'] +
$comment_content;
388 $state['gallery'] = $state['gallery'] +
$gallery_content;
390 foreach( $ext_content as $tag => $array ) {
391 if ( array_key_exists( $tag, $state ) ) {
392 $state[$tag] = $state[$tag] +
$array;
397 'html' => $html_content,
398 'nowiki' => $nowiki_content,
399 'math' => $math_content,
400 'pre' => $pre_content,
401 'comment' => $comment_content,
402 'gallery' => $gallery_content,
409 * restores pre, math, and hiero removed by strip()
411 * always call unstripNoWiki() after this one
414 function unstrip( $text, &$state ) {
415 # Must expand in reverse order, otherwise nested tags will be corrupted
416 $contentDict = end( $state );
417 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
418 if( key($state) != 'nowiki' && key($state) != 'html') {
419 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
420 $text = str_replace( key( $contentDict ), $content, $text );
429 * always call this after unstrip() to preserve the order
433 function unstripNoWiki( $text, &$state ) {
434 # Must expand in reverse order, otherwise nested tags will be corrupted
435 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
436 $text = str_replace( key( $state['nowiki'] ), $content, $text );
441 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
442 $text = str_replace( key( $state['html'] ), $content, $text );
450 * Add an item to the strip state
451 * Returns the unique tag which must be inserted into the stripped text
452 * The tag will be replaced with the original text in unstrip()
456 function insertStripItem( $text, &$state ) {
457 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
466 $state['item'][$rnd] = $text;
471 * Return allowed HTML attributes
475 function getHTMLattrs () {
476 $htmlattrs = array( # Allowed attributes--no scripting, etc.
477 'title', 'align', 'lang', 'dir', 'width', 'height',
478 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
479 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
480 /* FONT */ 'type', 'start', 'value', 'compact',
481 /* For various lists, mostly deprecated but safe */
482 'summary', 'width', 'border', 'frame', 'rules',
483 'cellspacing', 'cellpadding', 'valign', 'char',
484 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
485 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
486 'id', 'class', 'name', 'style' /* For CSS */
492 * Remove non approved attributes and javascript in css
496 function fixTagAttributes ( $t ) {
497 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
498 $htmlattrs = $this->getHTMLattrs() ;
500 # Strip non-approved attributes from the tag
502 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
503 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
506 $t = str_replace ( '<></>' , '' , $t ) ; # This should fix bug 980557
508 # Strip javascript "expression" from stylesheets. Brute force approach:
509 # If anythin offensive is found, all attributes of the HTML tag are dropped
512 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
513 wfMungeToUtf8( $t ) ) )
522 * interface with html tidy, used if $wgUseTidy = true
527 function tidy ( $text ) {
528 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
529 global $wgInputEncoding, $wgOutputEncoding;
530 $fname = 'Parser::tidy';
531 wfProfileIn( $fname );
535 switch(strtoupper($wgOutputEncoding)) {
537 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
540 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
546 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
547 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
548 '<head><title>test</title></head><body>'.$text.'</body></html>';
549 $descriptorspec = array(
550 0 => array('pipe', 'r'),
551 1 => array('pipe', 'w'),
552 2 => array('file', '/dev/null', 'a')
554 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
555 if (is_resource($process)) {
556 fwrite($pipes[0], $wrappedtext);
558 while (!feof($pipes[1])) {
559 $cleansource .= fgets($pipes[1], 1024);
562 $return_value = proc_close($process);
565 wfProfileOut( $fname );
567 if( $cleansource == '' && $text != '') {
568 wfDebug( "Tidy error detected!\n" );
569 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
576 * parse the wiki syntax used to render tables
580 function doTableStuff ( $t ) {
581 $fname = 'Parser::doTableStuff';
582 wfProfileIn( $fname );
584 $t = explode ( "\n" , $t ) ;
585 $td = array () ; # Is currently a td tag open?
586 $ltd = array () ; # Was it TD or TH?
587 $tr = array () ; # Is currently a tr tag open?
588 $ltr = array () ; # tr attributes
589 $indent_level = 0; # indent level of the table
590 foreach ( $t AS $k => $x )
593 $fc = substr ( $x , 0 , 1 ) ;
594 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
595 $indent_level = strlen( $matches[1] );
597 str_repeat( '<dl><dd>', $indent_level ) .
598 '<table ' . $this->fixTagAttributes ( $matches[2] ) . '>' ;
599 array_push ( $td , false ) ;
600 array_push ( $ltd , '' ) ;
601 array_push ( $tr , false ) ;
602 array_push ( $ltr , '' ) ;
604 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
605 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
607 $l = array_pop ( $ltd ) ;
608 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
609 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
611 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
613 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
614 $x = substr ( $x , 1 ) ;
615 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
617 $l = array_pop ( $ltd ) ;
618 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
619 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
622 array_push ( $tr , false ) ;
623 array_push ( $td , false ) ;
624 array_push ( $ltd , '' ) ;
625 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
627 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
629 if ( '|+' == substr ( $x , 0 , 2 ) ) {
631 $x = substr ( $x , 1 ) ;
633 $after = substr ( $x , 1 ) ;
634 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
635 $after = explode ( '||' , $after ) ;
638 # Loop through each table cell
639 foreach ( $after AS $theline )
644 $tra = array_pop ( $ltr ) ;
645 if ( !array_pop ( $tr ) ) $z = '<tr '.$tra.">\n" ;
646 array_push ( $tr , true ) ;
647 array_push ( $ltr , '' ) ;
650 $l = array_pop ( $ltd ) ;
651 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
652 if ( $fc == '|' ) $l = 'td' ;
653 else if ( $fc == '!' ) $l = 'th' ;
654 else if ( $fc == '+' ) $l = 'caption' ;
656 array_push ( $ltd , $l ) ;
659 $y = explode ( '|' , $theline , 2 ) ;
660 # Note that a '|' inside an invalid link should not
661 # be mistaken as delimiting cell parameters
662 if ( strpos( $y[0], '[[' ) !== false ) {
663 $y = array ($theline);
665 if ( count ( $y ) == 1 )
666 $y = "{$z}<{$l}>{$y[0]}" ;
667 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
669 array_push ( $td , true ) ;
674 # Closing open td, tr && table
675 while ( count ( $td ) > 0 )
677 if ( array_pop ( $td ) ) $t[] = '</td>' ;
678 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
682 $t = implode ( "\n" , $t ) ;
683 # $t = $this->removeHTMLtags( $t );
684 wfProfileOut( $fname );
689 * Helper function for parse() that transforms wiki markup into
690 * HTML. Only called for $mOutputType == OT_HTML.
694 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
697 $fname = 'Parser::internalParse';
698 wfProfileIn( $fname );
700 $text = $this->removeHTMLtags( $text );
701 $text = $this->replaceVariables( $text, $args );
703 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
705 $text = $this->doHeadings( $text );
706 if($this->mOptions
->getUseDynamicDates()) {
707 global $wgDateFormatter;
708 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
710 $text = $this->doAllQuotes( $text );
711 $text = $this->replaceInternalLinks( $text );
712 $text = $this->replaceExternalLinks( $text );
714 # replaceInternalLinks may sometimes leave behind
715 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
716 $text = str_replace("http-noparse://","http://",$text);
718 $text = $this->doMagicLinks( $text );
719 $text = $this->doTableStuff( $text );
720 $text = $this->formatHeadings( $text, $isMain );
722 wfProfileOut( $fname );
727 * Replace special strings like "ISBN xxx" and "RFC xxx" with
728 * magic external links.
732 function &doMagicLinks( &$text ) {
733 global $wgUseGeoMode;
734 $text = $this->magicISBN( $text );
735 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
736 $text = $this->magicGEO( $text );
738 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
739 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
744 * Parse ^^ tokens and return html
748 function doExponent( $text ) {
749 $fname = 'Parser::doExponent';
750 wfProfileIn( $fname );
751 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
752 wfProfileOut( $fname );
757 * Parse headers and return html
761 function doHeadings( $text ) {
762 $fname = 'Parser::doHeadings';
763 wfProfileIn( $fname );
764 for ( $i = 6; $i >= 1; --$i ) {
765 $h = substr( '======', 0, $i );
766 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
767 "<h{$i}>\\1</h{$i}>\\2", $text );
769 wfProfileOut( $fname );
774 * Replace single quotes with HTML markup
776 * @return string the altered text
778 function doAllQuotes( $text ) {
779 $fname = 'Parser::doAllQuotes';
780 wfProfileIn( $fname );
782 $lines = explode( "\n", $text );
783 foreach ( $lines as $line ) {
784 $outtext .= $this->doQuotes ( $line ) . "\n";
786 $outtext = substr($outtext, 0,-1);
787 wfProfileOut( $fname );
792 * Helper function for doAllQuotes()
795 function doQuotes( $text ) {
796 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
797 if ( count( $arr ) == 1 )
801 # First, do some preliminary work. This may shift some apostrophes from
802 # being mark-up to being text. It also counts the number of occurrences
803 # of bold and italics mark-ups.
807 foreach ( $arr as $r )
809 if ( ( $i %
2 ) == 1 )
811 # If there are ever four apostrophes, assume the first is supposed to
812 # be text, and the remaining three constitute mark-up for bold text.
813 if ( strlen( $arr[$i] ) == 4 )
818 # If there are more than 5 apostrophes in a row, assume they're all
819 # text except for the last 5.
820 else if ( strlen( $arr[$i] ) > 5 )
822 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
825 # Count the number of occurrences of bold and italics mark-ups.
826 # We are not counting sequences of five apostrophes.
827 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
828 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
829 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
834 # If there is an odd number of both bold and italics, it is likely
835 # that one of the bold ones was meant to be an apostrophe followed
836 # by italics. Which one we cannot know for certain, but it is more
837 # likely to be one that has a single-letter word before it.
838 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
841 $firstsingleletterword = -1;
842 $firstmultiletterword = -1;
844 foreach ( $arr as $r )
846 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
848 $x1 = substr ($arr[$i-1], -1);
849 $x2 = substr ($arr[$i-1], -2, 1);
851 if ($firstspace == -1) $firstspace = $i;
852 } else if ($x2 == ' ') {
853 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
855 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
861 # If there is a single-letter word, use it!
862 if ($firstsingleletterword > -1)
864 $arr [ $firstsingleletterword ] = "''";
865 $arr [ $firstsingleletterword-1 ] .= "'";
867 # If not, but there's a multi-letter word, use that one.
868 else if ($firstmultiletterword > -1)
870 $arr [ $firstmultiletterword ] = "''";
871 $arr [ $firstmultiletterword-1 ] .= "'";
873 # ... otherwise use the first one that has neither.
874 # (notice that it is possible for all three to be -1 if, for example,
875 # there is only one pentuple-apostrophe in the line)
876 else if ($firstspace > -1)
878 $arr [ $firstspace ] = "''";
879 $arr [ $firstspace-1 ] .= "'";
883 # Now let's actually convert our apostrophic mush to HTML!
892 if ($state == 'both')
899 if (strlen ($r) == 2)
902 { $output .= '</i>'; $state = ''; }
903 else if ($state == 'bi')
904 { $output .= '</i>'; $state = 'b'; }
905 else if ($state == 'ib')
906 { $output .= '</b></i><b>'; $state = 'b'; }
907 else if ($state == 'both')
908 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
909 else # $state can be 'b' or ''
910 { $output .= '<i>'; $state .= 'i'; }
912 else if (strlen ($r) == 3)
915 { $output .= '</b>'; $state = ''; }
916 else if ($state == 'bi')
917 { $output .= '</i></b><i>'; $state = 'i'; }
918 else if ($state == 'ib')
919 { $output .= '</b>'; $state = 'i'; }
920 else if ($state == 'both')
921 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
922 else # $state can be 'i' or ''
923 { $output .= '<b>'; $state .= 'b'; }
925 else if (strlen ($r) == 5)
928 { $output .= '</b><i>'; $state = 'i'; }
929 else if ($state == 'i')
930 { $output .= '</i><b>'; $state = 'b'; }
931 else if ($state == 'bi')
932 { $output .= '</i></b>'; $state = ''; }
933 else if ($state == 'ib')
934 { $output .= '</b></i>'; $state = ''; }
935 else if ($state == 'both')
936 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
937 else # ($state == '')
938 { $buffer = ''; $state = 'both'; }
943 # Now close all remaining tags. Notice that the order is important.
944 if ($state == 'b' ||
$state == 'ib')
946 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
950 if ($state == 'both')
951 $output .= '<b><i>'.$buffer.'</i></b>';
957 * Replace external links
959 * Note: this is all very hackish and the order of execution matters a lot.
960 * Make sure to run maintenance/parserTests.php if you change this code.
964 function replaceExternalLinks( $text ) {
965 $fname = 'Parser::replaceExternalLinks';
966 wfProfileIn( $fname );
968 $sk =& $this->mOptions
->getSkin();
970 $linktrail = $wgContLang->linkTrail();
972 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
974 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
977 while ( $i<count( $bits ) ) {
979 $protocol = $bits[$i++
];
981 $trail = $bits[$i++
];
983 # The characters '<' and '>' (which were escaped by
984 # removeHTMLtags()) should not be included in
985 # URLs, per RFC 2396.
986 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
987 $text = substr($url, $m2[0][1]) . ' ' . $text;
988 $url = substr($url, 0, $m2[0][1]);
991 # If the link text is an image URL, replace it with an <img> tag
992 # This happened by accident in the original parser, but some people used it extensively
993 $img = $this->maybeMakeImageLink( $text );
994 if ( $img !== false ) {
1000 # Set linktype for CSS - if URL==text, link is essentially free
1001 $linktype = ($text == $url) ?
'free' : 'text';
1003 # No link text, e.g. [http://domain.tld/some.link]
1004 if ( $text == '' ) {
1005 # Autonumber if allowed
1006 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
1007 $text = '[' . ++
$this->mAutonumber
. ']';
1008 $linktype = 'autonumber';
1010 # Otherwise just use the URL
1011 $text = htmlspecialchars( $url );
1015 # Have link text, e.g. [http://domain.tld/some.link text]s
1017 if ( preg_match( $linktrail, $trail, $m2 ) ) {
1023 # Replace & from obsolete syntax with &.
1024 # All HTML entities will be escaped by makeExternalLink()
1025 # or maybeMakeImageLink()
1026 $url = str_replace( '&', '&', $url );
1028 # Process the trail (i.e. everything after this link up until start of the next link),
1029 # replacing any non-bracketed links
1030 $trail = $this->replaceFreeExternalLinks( $trail );
1032 # Use the encoded URL
1033 # This means that users can paste URLs directly into the text
1034 # Funny characters like ö aren't valid in URLs anyway
1035 # This was changed in August 2004
1036 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1039 wfProfileOut( $fname );
1044 * Replace anything that looks like a URL with a link
1047 function replaceFreeExternalLinks( $text ) {
1048 $fname = 'Parser::replaceFreeExternalLinks';
1049 wfProfileIn( $fname );
1051 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1052 $s = array_shift( $bits );
1055 $sk =& $this->mOptions
->getSkin();
1057 while ( $i < count( $bits ) ){
1058 $protocol = $bits[$i++
];
1059 $remainder = $bits[$i++
];
1061 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1062 # Found some characters after the protocol that look promising
1063 $url = $protocol . $m[1];
1066 # The characters '<' and '>' (which were escaped by
1067 # removeHTMLtags()) should not be included in
1068 # URLs, per RFC 2396.
1069 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1070 $trail = substr($url, $m2[0][1]) . $trail;
1071 $url = substr($url, 0, $m2[0][1]);
1074 # Move trailing punctuation to $trail
1076 # If there is no left bracket, then consider right brackets fair game too
1077 if ( strpos( $url, '(' ) === false ) {
1081 $numSepChars = strspn( strrev( $url ), $sep );
1082 if ( $numSepChars ) {
1083 $trail = substr( $url, -$numSepChars ) . $trail;
1084 $url = substr( $url, 0, -$numSepChars );
1087 # Replace & from obsolete syntax with &.
1088 # All HTML entities will be escaped by makeExternalLink()
1089 # or maybeMakeImageLink()
1090 $url = str_replace( '&', '&', $url );
1092 # Is this an external image?
1093 $text = $this->maybeMakeImageLink( $url );
1094 if ( $text === false ) {
1095 # Not an image, make a link
1096 $text = $sk->makeExternalLink( $url, $url, true, 'free' );
1098 $s .= $text . $trail;
1100 $s .= $protocol . $remainder;
1108 * make an image if it's allowed
1111 function maybeMakeImageLink( $url ) {
1112 $sk =& $this->mOptions
->getSkin();
1114 if ( $this->mOptions
->getAllowExternalImages() ) {
1115 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1117 $text = $sk->makeImage( htmlspecialchars( $url ) );
1124 * Process [[ ]] wikilinks
1128 function replaceInternalLinks( $s ) {
1129 global $wgLang, $wgContLang, $wgLinkCache;
1130 global $wgDisableLangConversion;
1131 static $fname = 'Parser::replaceInternalLinks' ;
1133 wfProfileIn( $fname );
1135 wfProfileIn( $fname.'-setup' );
1137 # the % is needed to support urlencoded titles as well
1138 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1140 $sk =& $this->mOptions
->getSkin();
1141 global $wgUseOldExistenceCheck;
1142 # "Post-parse link colour check" works only on wiki text since it's now
1143 # in Parser. Enable it, then disable it when we're done.
1144 $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
1146 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1148 #split the entire text string on occurences of [[
1149 $a = explode( '[[', ' ' . $s );
1150 #get the first element (all text up to first [[), and remove the space we added
1151 $s = array_shift( $a );
1152 $s = substr( $s, 1 );
1154 # Match a link having the form [[namespace:link|alternate]]trail
1156 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1157 # Match cases where there is no "]]", which might still be images
1158 static $e1_img = FALSE;
1159 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1160 # Match the end of a line for a word that's not followed by whitespace,
1161 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1162 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1164 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1166 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1168 if ( $useLinkPrefixExtension ) {
1169 if ( preg_match( $e2, $s, $m ) ) {
1170 $first_prefix = $m[2];
1173 $first_prefix = false;
1179 $selflink = $this->mTitle
->getPrefixedText();
1180 wfProfileOut( $fname.'-setup' );
1182 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1183 $useSubpages = $this->areSubpagesAllowed();
1185 # Loop for each link
1186 for ($k = 0; isset( $a[$k] ); $k++
) {
1188 if ( $useLinkPrefixExtension ) {
1189 wfProfileIn( $fname.'-prefixhandling' );
1190 if ( preg_match( $e2, $s, $m ) ) {
1198 $prefix = $first_prefix;
1199 $first_prefix = false;
1201 wfProfileOut( $fname.'-prefixhandling' );
1204 $might_be_img = false;
1206 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1208 # fix up urlencoded title texts
1209 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1211 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1212 $might_be_img = true;
1214 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1216 } else { # Invalid form; output directly
1217 $s .= $prefix . '[[' . $line ;
1221 # Don't allow internal links to pages containing
1222 # PROTO: where PROTO is a valid URL protocol; these
1223 # should be external links.
1224 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1225 $s .= $prefix . '[[' . $line ;
1229 # Make subpage if necessary
1230 if( $useSubpages ) {
1231 $link = $this->maybeDoSubpageLink( $m[1], $text );
1236 $noforce = (substr($m[1], 0, 1) != ':');
1238 # Strip off leading ':'
1239 $link = substr($link, 1);
1242 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1244 $s .= $prefix . '[[' . $line;
1248 #check other language variants of the link
1249 #if the article does not exist
1250 if( $checkVariantLink
1251 && $nt->getArticleID() == 0 ) {
1252 $wgContLang->findVariantLink($link, $nt);
1255 $ns = $nt->getNamespace();
1256 $iw = $nt->getInterWiki();
1258 if ($might_be_img) { # if this is actually an invalid link
1259 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1261 while (isset ($a[$k+
1]) ) {
1262 #look at the next 'line' to see if we can close it there
1263 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1264 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1265 # the first ]] closes the inner link, the second the image
1267 $text .= '[[' . $m[1];
1270 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1271 #if there's exactly one ]] that's fine, we'll keep looking
1272 $text .= '[[' . $m[0];
1274 #if $next_line is invalid too, we need look no further
1275 $text .= '[[' . $next_line;
1280 # we couldn't find the end of this imageLink, so output it raw
1281 #but don't ignore what might be perfectly normal links in the text we've examined
1282 $text = $this->replaceInternalLinks($text);
1283 $s .= $prefix . '[[' . $link . '|' . $text;
1284 # note: no $trail, because without an end, there *is* no trail
1287 } else { #it's not an image, so output it raw
1288 $s .= $prefix . '[[' . $link . '|' . $text;
1289 # note: no $trail, because without an end, there *is* no trail
1294 $wasblank = ( '' == $text );
1295 if( $wasblank ) $text = $link;
1298 # Link not escaped by : , create the various objects
1302 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1303 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1304 $tmp = $prefix . $trail ;
1305 $s .= (trim($tmp) == '')?
'': $tmp;
1309 if ( $ns == NS_IMAGE
) {
1310 wfProfileIn( "$fname-image" );
1312 # recursively parse links inside the image caption
1313 # actually, this will parse them in any other parameters, too,
1314 # but it might be hard to fix that, and it doesn't matter ATM
1315 $text = $this->replaceExternalLinks($text);
1316 $text = $this->replaceInternalLinks($text);
1318 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1319 $s .= $prefix . str_replace('http://', 'http-noparse://', $sk->makeImageLinkObj( $nt, $text ) ) . $trail;
1320 $wgLinkCache->addImageLinkObj( $nt );
1322 wfProfileOut( "$fname-image" );
1326 if ( $ns == NS_CATEGORY
) {
1327 wfProfileIn( "$fname-category" );
1328 $t = $nt->getText();
1330 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1331 $pPLC=$sk->postParseLinkColour();
1332 $sk->postParseLinkColour( false );
1333 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1334 $sk->postParseLinkColour( $pPLC );
1335 $wgLinkCache->resume();
1338 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1339 $sortkey = $this->mTitle
->getText();
1341 $sortkey = $this->mTitle
->getPrefixedText();
1346 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1347 $this->mOutput
->addCategoryLink( $t );
1348 $s .= $prefix . $trail ;
1350 wfProfileOut( "$fname-category" );
1355 if( ( $nt->getPrefixedText() === $selflink ) &&
1356 ( $nt->getFragment() === '' ) ) {
1357 # Self-links are handled specially; generally de-link and change to bold.
1358 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1362 # Special and Media are pseudo-namespaces; no pages actually exist in them
1363 if( $ns == NS_MEDIA
) {
1364 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1365 $wgLinkCache->addImageLinkObj( $nt );
1367 } elseif( $ns == NS_SPECIAL
) {
1368 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1371 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1373 $sk->postParseLinkColour( $saveParseColour );
1374 wfProfileOut( $fname );
1379 * Return true if subpage links should be expanded on this page.
1382 function areSubpagesAllowed() {
1383 # Some namespaces don't allow subpages
1384 global $wgNamespacesWithSubpages;
1385 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1389 * Handle link to subpage if necessary
1390 * @param string $target the source of the link
1391 * @param string &$text the link text, modified as necessary
1392 * @return string the full name of the link
1395 function maybeDoSubpageLink($target, &$text) {
1398 # :Foobar -- override special treatment of prefix (images, language links)
1399 # /Foobar -- convert to CurrentPage/Foobar
1400 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1401 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1402 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1404 $fname = 'Parser::maybeDoSubpageLink';
1405 wfProfileIn( $fname );
1406 $ret = $target; # default return value is no change
1408 # Some namespaces don't allow subpages,
1409 # so only perform processing if subpages are allowed
1410 if( $this->areSubpagesAllowed() ) {
1411 # Look at the first character
1412 if( $target != '' && $target{0} == '/' ) {
1413 # / at end means we don't want the slash to be shown
1414 if( substr( $target, -1, 1 ) == '/' ) {
1415 $target = substr( $target, 1, -1 );
1418 $noslash = substr( $target, 1 );
1421 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1422 if( '' === $text ) {
1424 } # this might be changed for ugliness reasons
1426 # check for .. subpage backlinks
1428 $nodotdot = $target;
1429 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1431 $nodotdot = substr( $nodotdot, 3 );
1433 if($dotdotcount > 0) {
1434 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1435 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1436 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1437 # / at the end means don't show full path
1438 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1439 $nodotdot = substr( $nodotdot, 0, -1 );
1440 if( '' === $text ) {
1444 $nodotdot = trim( $nodotdot );
1445 if( $nodotdot != '' ) {
1446 $ret .= '/' . $nodotdot;
1453 wfProfileOut( $fname );
1458 * Used by doBlockLevels()
1461 /* private */ function closeParagraph() {
1463 if ( '' != $this->mLastSection
) {
1464 $result = '</' . $this->mLastSection
. ">\n";
1466 $this->mInPre
= false;
1467 $this->mLastSection
= '';
1470 # getCommon() returns the length of the longest common substring
1471 # of both arguments, starting at the beginning of both.
1473 /* private */ function getCommon( $st1, $st2 ) {
1474 $fl = strlen( $st1 );
1475 $shorter = strlen( $st2 );
1476 if ( $fl < $shorter ) { $shorter = $fl; }
1478 for ( $i = 0; $i < $shorter; ++
$i ) {
1479 if ( $st1{$i} != $st2{$i} ) { break; }
1483 # These next three functions open, continue, and close the list
1484 # element appropriate to the prefix character passed into them.
1486 /* private */ function openList( $char ) {
1487 $result = $this->closeParagraph();
1489 if ( '*' == $char ) { $result .= '<ul><li>'; }
1490 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1491 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1492 else if ( ';' == $char ) {
1493 $result .= '<dl><dt>';
1494 $this->mDTopen
= true;
1496 else { $result = '<!-- ERR 1 -->'; }
1501 /* private */ function nextItem( $char ) {
1502 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1503 else if ( ':' == $char ||
';' == $char ) {
1505 if ( $this->mDTopen
) { $close = '</dt>'; }
1506 if ( ';' == $char ) {
1507 $this->mDTopen
= true;
1508 return $close . '<dt>';
1510 $this->mDTopen
= false;
1511 return $close . '<dd>';
1514 return '<!-- ERR 2 -->';
1517 /* private */ function closeList( $char ) {
1518 if ( '*' == $char ) { $text = '</li></ul>'; }
1519 else if ( '#' == $char ) { $text = '</li></ol>'; }
1520 else if ( ':' == $char ) {
1521 if ( $this->mDTopen
) {
1522 $this->mDTopen
= false;
1523 $text = '</dt></dl>';
1525 $text = '</dd></dl>';
1528 else { return '<!-- ERR 3 -->'; }
1534 * Make lists from lines starting with ':', '*', '#', etc.
1537 * @return string the lists rendered as HTML
1539 function doBlockLevels( $text, $linestart ) {
1540 $fname = 'Parser::doBlockLevels';
1541 wfProfileIn( $fname );
1543 # Parsing through the text line by line. The main thing
1544 # happening here is handling of block-level elements p, pre,
1545 # and making lists from lines starting with * # : etc.
1547 $textLines = explode( "\n", $text );
1549 $lastPrefix = $output = $lastLine = '';
1550 $this->mDTopen
= $inBlockElem = false;
1552 $paragraphStack = false;
1554 if ( !$linestart ) {
1555 $output .= array_shift( $textLines );
1557 foreach ( $textLines as $oLine ) {
1558 $lastPrefixLength = strlen( $lastPrefix );
1559 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1560 $preOpenMatch = preg_match('/<pre/i', $oLine );
1561 if ( !$this->mInPre
) {
1562 # Multiple prefixes may abut each other for nested lists.
1563 $prefixLength = strspn( $oLine, '*#:;' );
1564 $pref = substr( $oLine, 0, $prefixLength );
1567 $pref2 = str_replace( ';', ':', $pref );
1568 $t = substr( $oLine, $prefixLength );
1569 $this->mInPre
= !empty($preOpenMatch);
1571 # Don't interpret any other prefixes in preformatted text
1573 $pref = $pref2 = '';
1578 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1579 # Same as the last item, so no need to deal with nesting or opening stuff
1580 $output .= $this->nextItem( substr( $pref, -1 ) );
1581 $paragraphStack = false;
1583 if ( substr( $pref, -1 ) == ';') {
1584 # The one nasty exception: definition lists work like this:
1585 # ; title : definition text
1586 # So we check for : in the remainder text to split up the
1587 # title and definition, without b0rking links.
1588 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1590 $output .= $term . $this->nextItem( ':' );
1593 } elseif( $prefixLength ||
$lastPrefixLength ) {
1594 # Either open or close a level...
1595 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1596 $paragraphStack = false;
1598 while( $commonPrefixLength < $lastPrefixLength ) {
1599 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1600 --$lastPrefixLength;
1602 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1603 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1605 while ( $prefixLength > $commonPrefixLength ) {
1606 $char = substr( $pref, $commonPrefixLength, 1 );
1607 $output .= $this->openList( $char );
1609 if ( ';' == $char ) {
1610 # FIXME: This is dupe of code above
1611 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1613 $output .= $term . $this->nextItem( ':' );
1616 ++
$commonPrefixLength;
1618 $lastPrefix = $pref2;
1620 if( 0 == $prefixLength ) {
1621 wfProfileIn( "$fname-paragraph" );
1622 # No prefix (not in list)--go to paragraph mode
1623 $uniq_prefix = UNIQ_PREFIX
;
1624 // XXX: use a stack for nestable elements like span, table and div
1625 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1626 $closematch = preg_match(
1627 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1628 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1629 if ( $openmatch or $closematch ) {
1630 $paragraphStack = false;
1631 $output .= $this->closeParagraph();
1632 if($preOpenMatch and !$preCloseMatch) {
1633 $this->mInPre
= true;
1635 if ( $closematch ) {
1636 $inBlockElem = false;
1638 $inBlockElem = true;
1640 } else if ( !$inBlockElem && !$this->mInPre
) {
1641 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1643 if ($this->mLastSection
!= 'pre') {
1644 $paragraphStack = false;
1645 $output .= $this->closeParagraph().'<pre>';
1646 $this->mLastSection
= 'pre';
1648 $t = substr( $t, 1 );
1651 if ( '' == trim($t) ) {
1652 if ( $paragraphStack ) {
1653 $output .= $paragraphStack.'<br />';
1654 $paragraphStack = false;
1655 $this->mLastSection
= 'p';
1657 if ($this->mLastSection
!= 'p' ) {
1658 $output .= $this->closeParagraph();
1659 $this->mLastSection
= '';
1660 $paragraphStack = '<p>';
1662 $paragraphStack = '</p><p>';
1666 if ( $paragraphStack ) {
1667 $output .= $paragraphStack;
1668 $paragraphStack = false;
1669 $this->mLastSection
= 'p';
1670 } else if ($this->mLastSection
!= 'p') {
1671 $output .= $this->closeParagraph().'<p>';
1672 $this->mLastSection
= 'p';
1677 wfProfileOut( "$fname-paragraph" );
1679 if ($paragraphStack === false) {
1683 while ( $prefixLength ) {
1684 $output .= $this->closeList( $pref2{$prefixLength-1} );
1687 if ( '' != $this->mLastSection
) {
1688 $output .= '</' . $this->mLastSection
. '>';
1689 $this->mLastSection
= '';
1692 wfProfileOut( $fname );
1697 * Split up a string on ':', ignoring any occurences inside
1698 * <a>..</a> or <span>...</span>
1699 * @param string $str the string to split
1700 * @param string &$before set to everything before the ':'
1701 * @param string &$after set to everything after the ':'
1702 * return string the position of the ':', or false if none found
1704 function findColonNoLinks($str, &$before, &$after) {
1705 # I wonder if we should make this count all tags, not just <a>
1706 # and <span>. That would prevent us from matching a ':' that
1707 # comes in the middle of italics other such formatting....
1709 $fname = 'Parser::findColonNoLinks';
1710 wfProfileIn( $fname );
1713 $colon = strpos($str, ':', $pos);
1715 if ($colon !== false) {
1716 $before = substr($str, 0, $colon);
1717 $after = substr($str, $colon +
1);
1719 # Skip any ':' within <a> or <span> pairs
1720 $a = substr_count($before, '<a');
1721 $s = substr_count($before, '<span');
1722 $ca = substr_count($before, '</a>');
1723 $cs = substr_count($before, '</span>');
1725 if ($a <= $ca and $s <= $cs) {
1726 # Tags are balanced before ':'; ok
1731 } while ($colon !== false);
1732 wfProfileOut( $fname );
1737 * Return value of a magic variable (like PAGENAME)
1741 function getVariableValue( $index ) {
1742 global $wgContLang, $wgSitename, $wgServer;
1745 * Some of these require message or data lookups and can be
1746 * expensive to check many times.
1748 static $varCache = array();
1749 if( isset( $varCache[$index] ) ) return $varCache[$index];
1752 case MAG_CURRENTMONTH
:
1753 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1754 case MAG_CURRENTMONTHNAME
:
1755 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1756 case MAG_CURRENTMONTHNAMEGEN
:
1757 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1758 case MAG_CURRENTDAY
:
1759 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1761 return $this->mTitle
->getText();
1763 return $this->mTitle
->getPartialURL();
1765 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1766 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1767 case MAG_CURRENTDAYNAME
:
1768 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1769 case MAG_CURRENTYEAR
:
1770 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1771 case MAG_CURRENTTIME
:
1772 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1773 case MAG_CURRENTWEEK
:
1774 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1775 case MAG_CURRENTDOW
:
1776 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1777 case MAG_NUMBEROFARTICLES
:
1778 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1789 * initialise the magic variables (like CURRENTMONTHNAME)
1793 function initialiseVariables() {
1794 $fname = 'Parser::initialiseVariables';
1795 wfProfileIn( $fname );
1796 global $wgVariableIDs;
1797 $this->mVariables
= array();
1798 foreach ( $wgVariableIDs as $id ) {
1799 $mw =& MagicWord
::get( $id );
1800 $mw->addToArray( $this->mVariables
, $id );
1802 wfProfileOut( $fname );
1806 * Replace magic variables, templates, and template arguments
1807 * with the appropriate text. Templates are substituted recursively,
1808 * taking care to avoid infinite loops.
1810 * Note that the substitution depends on value of $mOutputType:
1811 * OT_WIKI: only {{subst:}} templates
1812 * OT_MSG: only magic variables
1813 * OT_HTML: all templates and magic variables
1815 * @param string $tex The text to transform
1816 * @param array $args Key-value pairs representing template parameters to substitute
1819 function replaceVariables( $text, $args = array() ) {
1820 global $wgLang, $wgScript, $wgArticlePath;
1822 # Prevent too big inclusions
1823 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1827 $fname = 'Parser::replaceVariables';
1828 wfProfileIn( $fname );
1830 $titleChars = Title
::legalChars();
1832 # This function is called recursively. To keep track of arguments we need a stack:
1833 array_push( $this->mArgStack
, $args );
1835 # Variable substitution
1836 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1838 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1839 # Argument substitution
1840 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1842 # Template substitution
1843 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1844 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1846 array_pop( $this->mArgStack
);
1848 wfProfileOut( $fname );
1853 * Replace magic variables
1856 function variableSubstitution( $matches ) {
1857 $fname = 'parser::variableSubstitution';
1858 $varname = $matches[1];
1859 wfProfileIn( $fname );
1860 if ( !$this->mVariables
) {
1861 $this->initialiseVariables();
1864 if ( $this->mOutputType
== OT_WIKI
) {
1865 # Do only magic variables prefixed by SUBST
1866 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1867 if (!$mwSubst->matchStartAndRemove( $varname ))
1869 # Note that if we don't substitute the variable below,
1870 # we don't remove the {{subst:}} magic word, in case
1871 # it is a template rather than a magic variable.
1873 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1874 $id = $this->mVariables
[$varname];
1875 $text = $this->getVariableValue( $id );
1876 $this->mOutput
->mContainsOldMagic
= true;
1878 $text = $matches[0];
1880 wfProfileOut( $fname );
1884 # Split template arguments
1885 function getTemplateArgs( $argsString ) {
1886 if ( $argsString === '' ) {
1890 $args = explode( '|', substr( $argsString, 1 ) );
1892 # If any of the arguments contains a '[[' but no ']]', it needs to be
1893 # merged with the next arg because the '|' character between belongs
1894 # to the link syntax and not the template parameter syntax.
1895 $argc = count($args);
1897 for ( $i = 0; $i < $argc-1; $i++
) {
1898 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1899 $args[$i] .= '|'.$args[$i+
1];
1900 array_splice($args, $i+
1, 1);
1910 * Return the text of a template, after recursively
1911 * replacing any variables or templates within the template.
1913 * @param array $matches The parts of the template
1914 * $matches[1]: the title, i.e. the part before the |
1915 * $matches[2]: the parameters (including a leading |), if any
1916 * @return string the text of the template
1919 function braceSubstitution( $matches ) {
1920 global $wgLinkCache, $wgContLang;
1921 $fname = 'Parser::braceSubstitution';
1922 wfProfileIn( $fname );
1930 # Need to know if the template comes at the start of a line,
1931 # to treat the beginning of the template like the beginning
1932 # of a line for tables and block-level elements.
1933 $linestart = $matches[1];
1935 # $part1 is the bit before the first |, and must contain only title characters
1936 # $args is a list of arguments, starting from index 0, not including $part1
1938 $part1 = $matches[2];
1939 # If the third subpattern matched anything, it will start with |
1941 $args = $this->getTemplateArgs($matches[3]);
1942 $argc = count( $args );
1944 # Don't parse {{{}}} because that's only for template arguments
1945 if ( $linestart === '{' ) {
1946 $text = $matches[0];
1953 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1954 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1955 # One of two possibilities is true:
1956 # 1) Found SUBST but not in the PST phase
1957 # 2) Didn't find SUBST and in the PST phase
1958 # In either case, return without further processing
1959 $text = $matches[0];
1965 # MSG, MSGNW and INT
1968 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1969 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1972 # Remove obsolete MSG:
1973 $mwMsg =& MagicWord
::get( MAG_MSG
);
1974 $mwMsg->matchStartAndRemove( $part1 );
1977 # Check if it is an internal message
1978 $mwInt =& MagicWord
::get( MAG_INT
);
1979 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1980 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1981 $text = $linestart . wfMsgReal( $part1, $args, true );
1989 # Check for NS: (namespace expansion)
1990 $mwNs = MagicWord
::get( MAG_NS
);
1991 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1992 if ( intval( $part1 ) ) {
1993 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1996 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1997 if ( !is_null( $index ) ) {
1998 $text = $linestart . $wgContLang->getNsText( $index );
2005 # LOCALURL and LOCALURLE
2007 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2008 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2010 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2011 $func = 'getLocalURL';
2012 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2013 $func = 'escapeLocalURL';
2018 if ( $func !== '' ) {
2019 $title = Title
::newFromText( $part1 );
2020 if ( !is_null( $title ) ) {
2022 $text = $linestart . $title->$func( $args[0] );
2024 $text = $linestart . $title->$func();
2032 if ( !$found && $argc == 1 ) {
2033 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2034 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2035 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2040 # Template table test
2042 # Did we encounter this template already? If yes, it is in the cache
2043 # and we need to check for loops.
2044 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2045 # set $text to cached message.
2046 $text = $linestart . $this->mTemplates
[$part1];
2049 # Infinite loop test
2050 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2053 $text .= '<!-- WARNING: template loop detected -->';
2057 # Load from database
2058 $itcamefromthedatabase = false;
2061 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2062 if ($subpage !== '') {
2063 $ns = $this->mTitle
->getNamespace();
2065 $title = Title
::newFromText( $part1, $ns );
2066 if ( !is_null( $title ) && !$title->isExternal() ) {
2067 # Check for excessive inclusion
2068 $dbk = $title->getPrefixedDBkey();
2069 if ( $this->incrementIncludeCount( $dbk ) ) {
2070 # This should never be reached.
2071 $article = new Article( $title );
2072 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2073 if ( $articleContent !== false ) {
2075 $text = $linestart . $articleContent;
2076 $itcamefromthedatabase = true;
2080 # If the title is valid but undisplayable, make a link to it
2081 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2082 $text = $linestart . '[['.$title->getPrefixedText().']]';
2086 # Template cache array insertion
2088 $this->mTemplates
[$part1] = $text;
2093 # Recursive parsing, escaping and link table handling
2094 # Only for HTML output
2095 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2096 $text = wfEscapeWikiText( $text );
2097 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2098 # Clean up argument array
2099 $assocArgs = array();
2101 foreach( $args as $arg ) {
2102 $eqpos = strpos( $arg, '=' );
2103 if ( $eqpos === false ) {
2104 $assocArgs[$index++
] = $arg;
2106 $name = trim( substr( $arg, 0, $eqpos ) );
2107 $value = trim( substr( $arg, $eqpos+
1 ) );
2108 if ( $value === false ) {
2111 if ( $name !== false ) {
2112 $assocArgs[$name] = $value;
2117 # Add a new element to the templace recursion path
2118 $this->mTemplatePath
[$part1] = 1;
2120 $text = $this->strip( $text, $this->mStripState
);
2121 $text = $this->removeHTMLtags( $text );
2122 $text = $this->replaceVariables( $text, $assocArgs );
2124 # Resume the link cache and register the inclusion as a link
2125 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2126 $wgLinkCache->addLinkObj( $title );
2129 # If the template begins with a table or block-level
2130 # element, it should be treated as beginning a new line.
2131 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2132 $text = "\n" . $text;
2136 # Empties the template path
2137 $this->mTemplatePath
= array();
2139 wfProfileOut( $fname );
2142 # replace ==section headers==
2143 # XXX this needs to go away once we have a better parser.
2144 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2145 if( !is_null( $title ) )
2146 $encodedname = base64_encode($title->getPrefixedDBkey());
2148 $encodedname = base64_encode("");
2149 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2150 PREG_SPLIT_DELIM_CAPTURE
);
2153 for( $i = 0; $i < count($m); $i +
= 2 ) {
2155 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2157 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2161 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2162 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2163 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2170 # Empties the template path
2171 $this->mTemplatePath
= array();
2174 wfProfileOut( $fname );
2177 wfProfileOut( $fname );
2183 * Triple brace replacement -- used for template arguments
2186 function argSubstitution( $matches ) {
2187 $arg = trim( $matches[1] );
2188 $text = $matches[0];
2189 $inputArgs = end( $this->mArgStack
);
2191 if ( array_key_exists( $arg, $inputArgs ) ) {
2192 $text = $inputArgs[$arg];
2199 * Returns true if the function is allowed to include this entity
2202 function incrementIncludeCount( $dbk ) {
2203 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2204 $this->mIncludeCount
[$dbk] = 0;
2206 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2215 * Cleans up HTML, removes dangerous tags and attributes, and
2216 * removes HTML comments
2219 function removeHTMLtags( $text ) {
2220 global $wgUseTidy, $wgUserHtml;
2221 $fname = 'Parser::removeHTMLtags';
2222 wfProfileIn( $fname );
2225 $htmlpairs = array( # Tags that must be closed
2226 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
2227 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
2228 'strike', 'strong', 'tt', 'var', 'div', 'center',
2229 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
2230 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span'
2232 $htmlsingle = array(
2233 'br', 'hr', 'li', 'dt', 'dd'
2235 $htmlnest = array( # Tags that can be nested--??
2236 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
2237 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
2239 $tabletags = array( # Can only appear inside table
2243 $htmlpairs = array();
2244 $htmlsingle = array();
2245 $htmlnest = array();
2246 $tabletags = array();
2249 $htmlsingle = array_merge( $tabletags, $htmlsingle );
2250 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
2252 $htmlattrs = $this->getHTMLattrs () ;
2254 # Remove HTML comments
2255 $text = $this->removeHTMLcomments( $text );
2257 $bits = explode( '<', $text );
2258 $text = array_shift( $bits );
2260 $tagstack = array(); $tablestack = array();
2261 foreach ( $bits as $x ) {
2262 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
2263 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2265 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2266 error_reporting( $prev );
2269 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2273 if ( ! in_array( $t, $htmlsingle ) &&
2274 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
2275 @array_push
( $tagstack, $ot );
2278 if ( $t == 'table' ) {
2279 $tagstack = array_pop( $tablestack );
2284 # Keep track for later
2285 if ( in_array( $t, $tabletags ) &&
2286 ! in_array( 'table', $tagstack ) ) {
2288 } else if ( in_array( $t, $tagstack ) &&
2289 ! in_array ( $t , $htmlnest ) ) {
2291 } else if ( ! in_array( $t, $htmlsingle ) ) {
2292 if ( $t == 'table' ) {
2293 array_push( $tablestack, $tagstack );
2294 $tagstack = array();
2296 array_push( $tagstack, $t );
2298 # Strip non-approved attributes from the tag
2299 $newparams = $this->fixTagAttributes($params);
2303 $rest = str_replace( '>', '>', $rest );
2304 $text .= "<$slash$t $newparams$brace$rest";
2308 $text .= '<' . str_replace( '>', '>', $x);
2310 # Close off any remaining tags
2311 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2313 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2316 # this might be possible using tidy itself
2317 foreach ( $bits as $x ) {
2318 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2320 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2321 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2322 $newparams = $this->fixTagAttributes($params);
2323 $rest = str_replace( '>', '>', $rest );
2324 $text .= "<$slash$t $newparams$brace$rest";
2326 $text .= '<' . str_replace( '>', '>', $x);
2330 wfProfileOut( $fname );
2335 * Remove '<!--', '-->', and everything between.
2336 * To avoid leaving blank lines, when a comment is both preceded
2337 * and followed by a newline (ignoring spaces), trim leading and
2338 * trailing spaces and one of the newlines.
2342 function removeHTMLcomments( $text ) {
2343 $fname='Parser::removeHTMLcomments';
2344 wfProfileIn( $fname );
2345 while (($start = strpos($text, '<!--')) !== false) {
2346 $end = strpos($text, '-->', $start +
4);
2347 if ($end === false) {
2348 # Unterminated comment; bail out
2354 # Trim space and newline if the comment is both
2355 # preceded and followed by a newline
2356 $spaceStart = max($start - 1, 0);
2357 $spaceLen = $end - $spaceStart;
2358 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
2362 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
2364 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
2365 # Remove the comment, leading and trailing
2366 # spaces, and leave only one newline.
2367 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
2370 # Remove just the comment.
2371 $text = substr_replace($text, '', $start, $end - $start);
2374 wfProfileOut( $fname );
2379 * This function accomplishes several tasks:
2380 * 1) Auto-number headings if that option is enabled
2381 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2382 * 3) Add a Table of contents on the top for users who have enabled the option
2383 * 4) Auto-anchor headings
2385 * It loops through all headlines, collects the necessary data, then splits up the
2386 * string and re-inserts the newly formatted headlines.
2388 * @param string $text
2389 * @param boolean $isMain
2392 function formatHeadings( $text, $isMain=true ) {
2393 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2395 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2396 $doShowToc = $this->mOptions
->getShowToc();
2397 $forceTocHere = false;
2398 if( !$this->mTitle
->userCanEdit() ) {
2400 $rightClickHack = 0;
2402 $showEditLink = $this->mOptions
->getEditSection();
2403 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
2406 # Inhibit editsection links if requested in the page
2407 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2408 if( $esw->matchAndRemove( $text ) ) {
2411 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2413 $mw =& MagicWord
::get( MAG_NOTOC
);
2414 if( $mw->matchAndRemove( $text ) ) {
2418 # never add the TOC to the Main Page. This is an entry page that should not
2419 # be more than 1-2 screens large anyway
2420 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
2424 # Get all headlines for numbering them and adding funky stuff like [edit]
2425 # links - this is for later, but we need the number of headlines right now
2426 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2428 # if there are fewer than 4 headlines in the article, do not show TOC
2429 if( $numMatches < 4 ) {
2433 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2434 # override above conditions and always show TOC at that place
2436 $mw =& MagicWord
::get( MAG_TOC
);
2437 if($mw->match( $text ) ) {
2439 $forceTocHere = true;
2441 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2442 # override above conditions and always show TOC above first header
2443 $mw =& MagicWord
::get( MAG_FORCETOC
);
2444 if ($mw->matchAndRemove( $text ) ) {
2449 # Never ever show TOC if no headers
2450 if( $numMatches < 1 ) {
2454 # We need this to perform operations on the HTML
2455 $sk =& $this->mOptions
->getSkin();
2459 $sectionCount = 0; # headlineCount excluding template sections
2461 # Ugh .. the TOC should have neat indentation levels which can be
2462 # passed to the skin functions. These are determined here
2466 $sublevelCount = array();
2467 $levelCount = array();
2474 foreach( $matches[3] as $headline ) {
2476 $templatetitle = '';
2477 $templatesection = 0;
2480 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2482 $templatetitle = base64_decode($mat[1]);
2483 $templatesection = 1 +
(int)base64_decode($mat[2]);
2484 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2488 $prevlevel = $level;
2489 $prevtoclevel = $toclevel;
2491 $level = $matches[1][$headlineCount];
2493 if( $doNumberHeadings ||
$doShowToc ) {
2495 if ( $level > $prevlevel ) {
2496 # Increase TOC level
2498 $sublevelCount[$toclevel] = 0;
2499 $toc .= $sk->tocIndent();
2501 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2502 # Decrease TOC level, find level to jump to
2504 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2505 # Can only go down to level 1
2508 for ($i = $toclevel; $i > 0; $i--) {
2509 if ( $levelCount[$i] == $level ) {
2510 # Found last matching level
2514 elseif ( $levelCount[$i] < $level ) {
2515 # Found first matching level below current level
2522 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2525 # No change in level, end TOC line
2526 $toc .= $sk->tocLineEnd();
2529 $levelCount[$toclevel] = $level;
2531 # count number of headlines for each level
2532 @$sublevelCount[$toclevel]++
;
2534 for( $i = 1; $i <= $toclevel; $i++
) {
2535 if( !empty( $sublevelCount[$i] ) ) {
2539 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2545 # The canonized header is a version of the header text safe to use for links
2546 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2547 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2548 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2550 # Remove link placeholders by the link text.
2551 # <!--LINK number-->
2553 # link text with suffix
2554 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2555 "\$wgLinkHolders['texts'][\$1]",
2556 $canonized_headline );
2557 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2558 "\$wgInterwikiLinkHolders[\$1]",
2559 $canonized_headline );
2562 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2563 $tocline = trim( $canonized_headline );
2564 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2565 $replacearray = array(
2569 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2570 $refer[$headlineCount] = $canonized_headline;
2572 # count how many in assoc. array so we can track dupes in anchors
2573 @$refers[$canonized_headline]++
;
2574 $refcount[$headlineCount]=$refers[$canonized_headline];
2576 # Don't number the heading if it is the only one (looks silly)
2577 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2578 # the two are different if the line contains a link
2579 $headline=$numbering . ' ' . $headline;
2582 # Create the anchor for linking from the TOC to the section
2583 $anchor = $canonized_headline;
2584 if($refcount[$headlineCount] > 1 ) {
2585 $anchor .= '_' . $refcount[$headlineCount];
2587 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2588 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2590 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2591 if ( empty( $head[$headlineCount] ) ) {
2592 $head[$headlineCount] = '';
2595 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2597 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2600 # Add the edit section span
2601 if( $rightClickHack ) {
2603 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2605 $headline = $sk->editSectionScript($this->mTitle
, $sectionCount+
1,$headline);
2608 # give headline the correct <h#> tag
2609 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2617 $toclines = $headlineCount;
2618 $toc .= $sk->tocUnindent( $toclevel - 1 );
2619 $toc = $sk->tocList( $toc );
2622 # split up and insert constructed headlines
2624 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2627 foreach( $blocks as $block ) {
2628 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2629 # This is the [edit] link that appears for the top block of text when
2630 # section editing is enabled
2632 # Disabled because it broke block formatting
2633 # For example, a bullet point in the top line
2634 # $full .= $sk->editSectionLink(0);
2637 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2638 # Top anchor now in skin
2642 if( !empty( $head[$i] ) ) {
2648 $mw =& MagicWord
::get( MAG_TOC
);
2649 return $mw->replace( $toc, $full );
2656 * Return an HTML link for the "ISBN 123456" text
2659 function magicISBN( $text ) {
2661 $fname = 'Parser::magicISBN';
2662 wfProfileIn( $fname );
2664 $a = split( 'ISBN ', ' '.$text );
2665 if ( count ( $a ) < 2 ) {
2666 wfProfileOut( $fname );
2669 $text = substr( array_shift( $a ), 1);
2670 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2672 foreach ( $a as $x ) {
2673 $isbn = $blank = '' ;
2674 while ( ' ' == $x{0} ) {
2676 $x = substr( $x, 1 );
2678 if ( $x == '' ) { # blank isbn
2679 $text .= "ISBN $blank";
2682 while ( strstr( $valid, $x{0} ) != false ) {
2684 $x = substr( $x, 1 );
2686 $num = str_replace( '-', '', $isbn );
2687 $num = str_replace( ' ', '', $num );
2690 $text .= "ISBN $blank$x";
2692 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2693 $text .= '<a href="' .
2694 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2695 "\" class=\"internal\">ISBN $isbn</a>";
2699 wfProfileOut( $fname );
2704 * Return an HTML link for the "GEO ..." text
2707 function magicGEO( $text ) {
2708 global $wgLang, $wgUseGeoMode;
2709 $fname = 'Parser::magicGEO';
2710 wfProfileIn( $fname );
2712 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2713 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2714 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2715 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2716 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2717 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2719 $a = split( 'GEO ', ' '.$text );
2720 if ( count ( $a ) < 2 ) {
2721 wfProfileOut( $fname );
2724 $text = substr( array_shift( $a ), 1);
2725 $valid = '0123456789.+-:';
2727 foreach ( $a as $x ) {
2728 $geo = $blank = '' ;
2729 while ( ' ' == $x{0} ) {
2731 $x = substr( $x, 1 );
2733 while ( strstr( $valid, $x{0} ) != false ) {
2735 $x = substr( $x, 1 );
2737 $num = str_replace( '+', '', $geo );
2738 $num = str_replace( ' ', '', $num );
2740 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2741 $text .= "GEO $blank$x";
2743 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2744 $text .= '<a href="' .
2745 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2746 "\" class=\"internal\">GEO $geo</a>";
2750 wfProfileOut( $fname );
2755 * Return an HTML link for the "RFC 1234" text
2757 * @param string $text text to be processed
2759 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2762 $valid = '0123456789';
2765 $a = split( $keyword, ' '.$text );
2766 if ( count ( $a ) < 2 ) {
2769 $text = substr( array_shift( $a ), 1);
2771 /* Check if keyword is preceed by [[.
2772 * This test is made here cause of the array_shift above
2773 * that prevent the test to be done in the foreach.
2775 if ( substr( $text, -2 ) == '[[' ) {
2779 foreach ( $a as $x ) {
2780 /* token might be empty if we have RFC RFC 1234 */
2788 /** remove and save whitespaces in $blank */
2789 while ( $x{0} == ' ' ) {
2791 $x = substr( $x, 1 );
2794 /** remove and save the rfc number in $id */
2795 while ( strstr( $valid, $x{0} ) != false ) {
2797 $x = substr( $x, 1 );
2801 /* call back stripped spaces*/
2802 $text .= $keyword.$blank.$x;
2803 } elseif( $internal ) {
2805 $text .= $keyword.$id.$x;
2807 /* build the external link*/
2808 $url = wfmsg( $urlmsg );
2809 $url = str_replace( '$1', $id, $url);
2810 $sk =& $this->mOptions
->getSkin();
2811 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2812 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2815 /* Check if the next RFC keyword is preceed by [[ */
2816 $internal = ( substr($x,-2) == '[[' );
2822 * Transform wiki markup when saving a page by doing \r\n -> \n
2823 * conversion, substitting signatures, {{subst:}} templates, etc.
2825 * @param string $text the text to transform
2826 * @param Title &$title the Title object for the current article
2827 * @param User &$user the User object describing the current user
2828 * @param ParserOptions $options parsing options
2829 * @param bool $clearState whether to clear the parser state first
2830 * @return string the altered wiki markup
2833 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2834 $this->mOptions
= $options;
2835 $this->mTitle
=& $title;
2836 $this->mOutputType
= OT_WIKI
;
2838 if ( $clearState ) {
2839 $this->clearState();
2842 $stripState = false;
2846 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2847 $text = $this->strip( $text, $stripState, false );
2848 $text = $this->pstPass2( $text, $user );
2849 $text = $this->unstrip( $text, $stripState );
2850 $text = $this->unstripNoWiki( $text, $stripState );
2855 * Pre-save transform helper function
2858 function pstPass2( $text, &$user ) {
2859 global $wgLang, $wgContLang, $wgLocaltimezone;
2861 # Variable replacement
2862 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2863 $text = $this->replaceVariables( $text );
2867 $n = $user->getName();
2868 $k = $user->getOption( 'nickname' );
2869 if ( '' == $k ) { $k = $n; }
2870 if ( isset( $wgLocaltimezone ) ) {
2871 $oldtz = getenv( 'TZ' );
2872 putenv( 'TZ='.$wgLocaltimezone );
2874 /* Note: this is an ugly timezone hack for the European wikis */
2875 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2876 ' (' . date( 'T' ) . ')';
2877 if ( isset( $wgLocaltimezone ) ) {
2878 putenv( 'TZ='.$oldtzs );
2881 if( $user->getOption( 'fancysig' ) ) {
2884 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2886 $text = preg_replace( '/~~~~~/', $d, $text );
2887 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2888 $text = preg_replace( '/~~~/', $sigText, $text );
2890 # Context links: [[|name]] and [[name (context)|]]
2892 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2893 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2894 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2895 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2897 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2898 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2899 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2900 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2902 $t = $this->mTitle
->getText();
2903 if ( preg_match( $conpat, $t, $m ) ) {
2906 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2907 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2908 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2910 if ( '' == $context ) {
2911 $text = preg_replace( $p2, '[[\\1]]', $text );
2913 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2916 # Trim trailing whitespace
2917 # MAG_END (__END__) tag allows for trailing
2918 # whitespace to be deliberately included
2919 $text = rtrim( $text );
2920 $mw =& MagicWord
::get( MAG_END
);
2921 $mw->matchAndRemove( $text );
2927 * Set up some variables which are usually set up in parse()
2928 * so that an external function can call some class members with confidence
2931 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2932 $this->mTitle
=& $title;
2933 $this->mOptions
= $options;
2934 $this->mOutputType
= $outputType;
2935 if ( $clearState ) {
2936 $this->clearState();
2941 * Transform a MediaWiki message by replacing magic variables.
2943 * @param string $text the text to transform
2944 * @param ParserOptions $options options
2945 * @return string the text with variables substituted
2948 function transformMsg( $text, $options ) {
2950 static $executing = false;
2952 # Guard against infinite recursion
2958 $this->mTitle
= $wgTitle;
2959 $this->mOptions
= $options;
2960 $this->mOutputType
= OT_MSG
;
2961 $this->clearState();
2962 $text = $this->replaceVariables( $text );
2969 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2970 * Callback will be called with the text within
2971 * Transform and return the text within
2974 function setHook( $tag, $callback ) {
2975 $oldVal = @$this->mTagHooks
[$tag];
2976 $this->mTagHooks
[$tag] = $callback;
2981 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2982 * Placeholders created in Skin::makeLinkObj()
2983 * Returns an array of links found, indexed by PDBK:
2987 * $options is a bit field, RLH_FOR_UPDATE to select for update
2989 function replaceLinkHolders( &$text, $options = 0 ) {
2990 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2991 global $wgInterwikiLinkHolders;
2992 global $outputReplace;
2994 if ( $wgUseOldExistenceCheck ) {
2998 $fname = 'Parser::replaceLinkHolders';
2999 wfProfileIn( $fname );
3004 #if ( !empty( $tmpLinks[0] ) ) { #TODO
3005 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
3006 wfProfileIn( $fname.'-check' );
3007 $dbr =& wfGetDB( DB_SLAVE
);
3008 $page = $dbr->tableName( 'page' );
3009 $sk = $wgUser->getSkin();
3010 $threshold = $wgUser->getOption('stubthreshold');
3013 asort( $wgLinkHolders['namespaces'] );
3017 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
3019 $title = $wgLinkHolders['titles'][$key];
3021 # Skip invalid entries.
3022 # Result will be ugly, but prevents crash.
3023 if ( is_null( $title ) ) {
3026 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3028 # Check if it's in the link cache already
3029 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
3030 $colours[$pdbk] = 1;
3031 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3032 $colours[$pdbk] = 0;
3034 # Not in the link cache, add it to the query
3035 if ( !isset( $current ) ) {
3039 $query = "SELECT page_id, page_namespace, page_title";
3040 if ( $threshold > 0 ) {
3041 $textTable = $dbr->tableName( 'text' );
3042 $query .= ', LENGTH(old_text) AS page_len, page_is_redirect';
3043 $tables .= ", $textTable";
3044 $join = 'page_latest=old_id AND';
3046 $query .= " FROM $tables WHERE $join (page_namespace=$val AND page_title IN(";
3047 } elseif ( $current != $val ) {
3049 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3054 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
3059 if ( $options & RLH_FOR_UPDATE
) {
3060 $query .= ' FOR UPDATE';
3063 $res = $dbr->query( $query, $fname );
3065 # Fetch data and form into an associative array
3066 # non-existent = broken
3069 while ( $s = $dbr->fetchObject($res) ) {
3070 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3071 $pdbk = $title->getPrefixedDBkey();
3072 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
3074 if ( $threshold > 0 ) {
3075 $size = $s->page_len
;
3076 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$length < $threshold ) {
3077 $colours[$pdbk] = 1;
3079 $colours[$pdbk] = 2;
3082 $colours[$pdbk] = 1;
3086 wfProfileOut( $fname.'-check' );
3088 # Construct search and replace arrays
3089 wfProfileIn( $fname.'-construct' );
3090 $outputReplace = array();
3091 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
3092 $pdbk = $pdbks[$key];
3093 $searchkey = '<!--LINK '.$key.'-->';
3094 $title = $wgLinkHolders['titles'][$key];
3095 if ( empty( $colours[$pdbk] ) ) {
3096 $wgLinkCache->addBadLink( $pdbk );
3097 $colours[$pdbk] = 0;
3098 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3099 $wgLinkHolders['texts'][$key],
3100 $wgLinkHolders['queries'][$key] );
3101 } elseif ( $colours[$pdbk] == 1 ) {
3102 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3103 $wgLinkHolders['texts'][$key],
3104 $wgLinkHolders['queries'][$key] );
3105 } elseif ( $colours[$pdbk] == 2 ) {
3106 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3107 $wgLinkHolders['texts'][$key],
3108 $wgLinkHolders['queries'][$key] );
3111 wfProfileOut( $fname.'-construct' );
3114 wfProfileIn( $fname.'-replace' );
3116 $text = preg_replace_callback(
3117 '/(<!--LINK .*?-->)/',
3118 "outputReplaceMatches",
3120 wfProfileOut( $fname.'-replace' );
3123 if ( !empty( $wgInterwikiLinkHolders ) ) {
3124 wfProfileIn( $fname.'-interwiki' );
3125 $outputReplace = $wgInterwikiLinkHolders;
3126 $text = preg_replace_callback(
3127 '/<!--IWLINK (.*?)-->/',
3128 "outputReplaceMatches",
3130 wfProfileOut( $fname.'-interwiki' );
3133 wfProfileOut( $fname );
3138 * Renders an image gallery from a text with one line per image.
3139 * text labels may be given by using |-style alternative text. E.g.
3140 * Image:one.jpg|The number "1"
3141 * Image:tree.jpg|A tree
3142 * given as text will return the HTML of a gallery with two images,
3143 * labeled 'The number "1"' and
3146 function renderImageGallery( $text ) {
3147 global $wgLinkCache;
3148 $ig = new ImageGallery();
3149 $ig->setShowBytes( false );
3150 $ig->setShowFilename( false );
3151 $lines = explode( "\n", $text );
3153 foreach ( $lines as $line ) {
3154 # match lines like these:
3155 # Image:someimage.jpg|This is some image
3156 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3158 if ( count( $matches ) == 0 ) {
3161 $nt = Title
::newFromURL( $matches[1] );
3162 if( is_null( $nt ) ) {
3163 # Bogus title. Ignore these so we don't bomb out later.
3166 if ( isset( $matches[3] ) ) {
3167 $label = $matches[3];
3172 # FIXME: Use the full wiki parser and add its links
3173 # to the page's links.
3174 $html = $this->mOptions
->mSkin
->formatComment( $label );
3176 $ig->add( Image
::newFromTitle( $nt ), $html );
3177 $wgLinkCache->addImageLinkObj( $nt );
3179 return $ig->toHTML();
3185 * @package MediaWiki
3189 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3190 var $mCacheTime; # Used in ParserCache
3191 var $mVersion; # Compatibility check
3193 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3194 $containsOldMagic = false )
3196 $this->mText
= $text;
3197 $this->mLanguageLinks
= $languageLinks;
3198 $this->mCategoryLinks
= $categoryLinks;
3199 $this->mContainsOldMagic
= $containsOldMagic;
3200 $this->mCacheTime
= '';
3201 $this->mVersion
= MW_PARSER_VERSION
;
3204 function getText() { return $this->mText
; }
3205 function getLanguageLinks() { return $this->mLanguageLinks
; }
3206 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3207 function getCacheTime() { return $this->mCacheTime
; }
3208 function containsOldMagic() { return $this->mContainsOldMagic
; }
3209 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3210 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3211 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3212 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3213 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3214 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3216 function merge( $other ) {
3217 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3218 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3219 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3223 * Return true if this cached output object predates the global or
3224 * per-article cache invalidation timestamps, or if it comes from
3225 * an incompatible older version.
3227 * @param string $touched the affected article's last touched timestamp
3231 function expired( $touched ) {
3232 global $wgCacheEpoch;
3233 return $this->getCacheTime() <= $touched ||
3234 $this->getCacheTime() <= $wgCacheEpoch ||
3235 !isset( $this->mVersion
) ||
3236 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3241 * Set options of the Parser
3243 * @package MediaWiki
3247 # All variables are private
3248 var $mUseTeX; # Use texvc to expand <math> tags
3249 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
3250 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3251 var $mAllowExternalImages; # Allow external images inline
3252 var $mSkin; # Reference to the preferred skin
3253 var $mDateFormat; # Date format index
3254 var $mEditSection; # Create "edit section" links
3255 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
3256 var $mNumberHeadings; # Automatically number headings
3257 var $mShowToc; # Show table of contents
3259 function getUseTeX() { return $this->mUseTeX
; }
3260 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3261 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3262 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3263 function getSkin() { return $this->mSkin
; }
3264 function getDateFormat() { return $this->mDateFormat
; }
3265 function getEditSection() { return $this->mEditSection
; }
3266 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
3267 function getNumberHeadings() { return $this->mNumberHeadings
; }
3268 function getShowToc() { return $this->mShowToc
; }
3270 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3271 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3272 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3273 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3274 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3275 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3276 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
3277 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3278 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
3280 function setSkin( &$x ) { $this->mSkin
=& $x; }
3283 * Get parser options
3286 function newFromUser( &$user ) {
3287 $popts = new ParserOptions
;
3288 $popts->initialiseFromUser( $user );
3292 /** Get user options */
3293 function initialiseFromUser( &$userInput ) {
3294 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3295 $fname = 'ParserOptions::initialiseFromUser';
3296 wfProfileIn( $fname );
3297 if ( !$userInput ) {
3299 $user->setLoaded( true );
3301 $user =& $userInput;
3304 $this->mUseTeX
= $wgUseTeX;
3305 $this->mUseDynamicDates
= $wgUseDynamicDates;
3306 $this->mInterwikiMagic
= $wgInterwikiMagic;
3307 $this->mAllowExternalImages
= $wgAllowExternalImages;
3308 wfProfileIn( $fname.'-skin' );
3309 $this->mSkin
=& $user->getSkin();
3310 wfProfileOut( $fname.'-skin' );
3311 $this->mDateFormat
= $user->getOption( 'date' );
3312 $this->mEditSection
= $user->getOption( 'editsection' );
3313 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
3314 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3315 $this->mShowToc
= $user->getOption( 'showtoc' );
3316 wfProfileOut( $fname );
3321 * Callback function used by Parser::replaceLinkHolders()
3322 * to substitute link placeholders.
3324 function &outputReplaceMatches( $matches ) {
3325 global $outputReplace;
3326 return $outputReplace[$matches[1]];
3330 * Return the total number of articles
3332 function wfNumberOfArticles() {
3333 global $wgNumberOfArticles;
3336 return $wgNumberOfArticles;
3340 * Get various statistics from the database
3343 function wfLoadSiteStats() {
3344 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3345 $fname = 'wfLoadSiteStats';
3347 if ( -1 != $wgNumberOfArticles ) return;
3348 $dbr =& wfGetDB( DB_SLAVE
);
3349 $s = $dbr->selectRow( 'site_stats',
3350 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3351 array( 'ss_row_id' => 1 ), $fname
3354 if ( $s === false ) {
3357 $wgTotalViews = $s->ss_total_views
;
3358 $wgTotalEdits = $s->ss_total_edits
;
3359 $wgNumberOfArticles = $s->ss_good_articles
;
3365 * Basicly replacing " > and < with HTML entities ( ", >, <)
3367 * @param string $in Text that might contain HTML tags
3368 * @return string Escaped string
3370 function wfEscapeHTMLTagsOnly( $in ) {
3372 array( '"', '>', '<' ),
3373 array( '"', '>', '<' ),