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
2087 $this->mTemplates
[$part1] = $text;
2091 # Recursive parsing, escaping and link table handling
2092 # Only for HTML output
2093 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2094 $text = wfEscapeWikiText( $text );
2095 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2096 # Clean up argument array
2097 $assocArgs = array();
2099 foreach( $args as $arg ) {
2100 $eqpos = strpos( $arg, '=' );
2101 if ( $eqpos === false ) {
2102 $assocArgs[$index++
] = $arg;
2104 $name = trim( substr( $arg, 0, $eqpos ) );
2105 $value = trim( substr( $arg, $eqpos+
1 ) );
2106 if ( $value === false ) {
2109 if ( $name !== false ) {
2110 $assocArgs[$name] = $value;
2115 # Add a new element to the templace recursion path
2116 $this->mTemplatePath
[$part1] = 1;
2118 $text = $this->strip( $text, $this->mStripState
);
2119 $text = $this->removeHTMLtags( $text );
2120 $text = $this->replaceVariables( $text, $assocArgs );
2122 # Resume the link cache and register the inclusion as a link
2123 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2124 $wgLinkCache->addLinkObj( $title );
2127 # If the template begins with a table or block-level
2128 # element, it should be treated as beginning a new line.
2129 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2130 $text = "\n" . $text;
2134 # Empties the template path
2135 $this->mTemplatePath
= array();
2137 wfProfileOut( $fname );
2140 # replace ==section headers==
2141 # XXX this needs to go away once we have a better parser.
2142 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2143 if( !is_null( $title ) )
2144 $encodedname = base64_encode($title->getPrefixedDBkey());
2146 $encodedname = base64_encode("");
2147 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2148 PREG_SPLIT_DELIM_CAPTURE
);
2151 for( $i = 0; $i < count($m); $i +
= 2 ) {
2153 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2155 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2159 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2160 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2161 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2168 # Empties the template path
2169 $this->mTemplatePath
= array();
2172 wfProfileOut( $fname );
2175 wfProfileOut( $fname );
2181 * Triple brace replacement -- used for template arguments
2184 function argSubstitution( $matches ) {
2185 $arg = trim( $matches[1] );
2186 $text = $matches[0];
2187 $inputArgs = end( $this->mArgStack
);
2189 if ( array_key_exists( $arg, $inputArgs ) ) {
2190 $text = $inputArgs[$arg];
2197 * Returns true if the function is allowed to include this entity
2200 function incrementIncludeCount( $dbk ) {
2201 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2202 $this->mIncludeCount
[$dbk] = 0;
2204 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2213 * Cleans up HTML, removes dangerous tags and attributes, and
2214 * removes HTML comments
2217 function removeHTMLtags( $text ) {
2218 global $wgUseTidy, $wgUserHtml;
2219 $fname = 'Parser::removeHTMLtags';
2220 wfProfileIn( $fname );
2223 $htmlpairs = array( # Tags that must be closed
2224 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
2225 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
2226 'strike', 'strong', 'tt', 'var', 'div', 'center',
2227 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
2228 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span'
2230 $htmlsingle = array(
2231 'br', 'hr', 'li', 'dt', 'dd'
2233 $htmlnest = array( # Tags that can be nested--??
2234 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
2235 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
2237 $tabletags = array( # Can only appear inside table
2241 $htmlpairs = array();
2242 $htmlsingle = array();
2243 $htmlnest = array();
2244 $tabletags = array();
2247 $htmlsingle = array_merge( $tabletags, $htmlsingle );
2248 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
2250 $htmlattrs = $this->getHTMLattrs () ;
2252 # Remove HTML comments
2253 $text = $this->removeHTMLcomments( $text );
2255 $bits = explode( '<', $text );
2256 $text = array_shift( $bits );
2258 $tagstack = array(); $tablestack = array();
2259 foreach ( $bits as $x ) {
2260 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
2261 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2263 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2264 error_reporting( $prev );
2267 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2271 if ( ! in_array( $t, $htmlsingle ) &&
2272 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
2273 @array_push
( $tagstack, $ot );
2276 if ( $t == 'table' ) {
2277 $tagstack = array_pop( $tablestack );
2282 # Keep track for later
2283 if ( in_array( $t, $tabletags ) &&
2284 ! in_array( 'table', $tagstack ) ) {
2286 } else if ( in_array( $t, $tagstack ) &&
2287 ! in_array ( $t , $htmlnest ) ) {
2289 } else if ( ! in_array( $t, $htmlsingle ) ) {
2290 if ( $t == 'table' ) {
2291 array_push( $tablestack, $tagstack );
2292 $tagstack = array();
2294 array_push( $tagstack, $t );
2296 # Strip non-approved attributes from the tag
2297 $newparams = $this->fixTagAttributes($params);
2301 $rest = str_replace( '>', '>', $rest );
2302 $text .= "<$slash$t $newparams$brace$rest";
2306 $text .= '<' . str_replace( '>', '>', $x);
2308 # Close off any remaining tags
2309 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2311 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2314 # this might be possible using tidy itself
2315 foreach ( $bits as $x ) {
2316 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2318 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2319 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2320 $newparams = $this->fixTagAttributes($params);
2321 $rest = str_replace( '>', '>', $rest );
2322 $text .= "<$slash$t $newparams$brace$rest";
2324 $text .= '<' . str_replace( '>', '>', $x);
2328 wfProfileOut( $fname );
2333 * Remove '<!--', '-->', and everything between.
2334 * To avoid leaving blank lines, when a comment is both preceded
2335 * and followed by a newline (ignoring spaces), trim leading and
2336 * trailing spaces and one of the newlines.
2340 function removeHTMLcomments( $text ) {
2341 $fname='Parser::removeHTMLcomments';
2342 wfProfileIn( $fname );
2343 while (($start = strpos($text, '<!--')) !== false) {
2344 $end = strpos($text, '-->', $start +
4);
2345 if ($end === false) {
2346 # Unterminated comment; bail out
2352 # Trim space and newline if the comment is both
2353 # preceded and followed by a newline
2354 $spaceStart = max($start - 1, 0);
2355 $spaceLen = $end - $spaceStart;
2356 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
2360 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
2362 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
2363 # Remove the comment, leading and trailing
2364 # spaces, and leave only one newline.
2365 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
2368 # Remove just the comment.
2369 $text = substr_replace($text, '', $start, $end - $start);
2372 wfProfileOut( $fname );
2377 * This function accomplishes several tasks:
2378 * 1) Auto-number headings if that option is enabled
2379 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2380 * 3) Add a Table of contents on the top for users who have enabled the option
2381 * 4) Auto-anchor headings
2383 * It loops through all headlines, collects the necessary data, then splits up the
2384 * string and re-inserts the newly formatted headlines.
2386 * @param string $text
2387 * @param boolean $isMain
2390 function formatHeadings( $text, $isMain=true ) {
2391 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2393 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2394 $doShowToc = $this->mOptions
->getShowToc();
2395 $forceTocHere = false;
2396 if( !$this->mTitle
->userCanEdit() ) {
2398 $rightClickHack = 0;
2400 $showEditLink = $this->mOptions
->getEditSection();
2401 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
2404 # Inhibit editsection links if requested in the page
2405 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2406 if( $esw->matchAndRemove( $text ) ) {
2409 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2411 $mw =& MagicWord
::get( MAG_NOTOC
);
2412 if( $mw->matchAndRemove( $text ) ) {
2416 # never add the TOC to the Main Page. This is an entry page that should not
2417 # be more than 1-2 screens large anyway
2418 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
2422 # Get all headlines for numbering them and adding funky stuff like [edit]
2423 # links - this is for later, but we need the number of headlines right now
2424 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2426 # if there are fewer than 4 headlines in the article, do not show TOC
2427 if( $numMatches < 4 ) {
2431 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2432 # override above conditions and always show TOC at that place
2434 $mw =& MagicWord
::get( MAG_TOC
);
2435 if($mw->match( $text ) ) {
2437 $forceTocHere = true;
2439 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2440 # override above conditions and always show TOC above first header
2441 $mw =& MagicWord
::get( MAG_FORCETOC
);
2442 if ($mw->matchAndRemove( $text ) ) {
2447 # Never ever show TOC if no headers
2448 if( $numMatches < 1 ) {
2452 # We need this to perform operations on the HTML
2453 $sk =& $this->mOptions
->getSkin();
2457 $sectionCount = 0; # headlineCount excluding template sections
2459 # Ugh .. the TOC should have neat indentation levels which can be
2460 # passed to the skin functions. These are determined here
2464 $sublevelCount = array();
2465 $levelCount = array();
2472 foreach( $matches[3] as $headline ) {
2474 $templatetitle = '';
2475 $templatesection = 0;
2478 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2480 $templatetitle = base64_decode($mat[1]);
2481 $templatesection = 1 +
(int)base64_decode($mat[2]);
2482 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2486 $prevlevel = $level;
2487 $prevtoclevel = $toclevel;
2489 $level = $matches[1][$headlineCount];
2491 if( $doNumberHeadings ||
$doShowToc ) {
2493 if ( $level > $prevlevel ) {
2494 # Increase TOC level
2496 $sublevelCount[$toclevel] = 0;
2497 $toc .= $sk->tocIndent();
2499 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2500 # Decrease TOC level, find level to jump to
2502 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2503 # Can only go down to level 1
2506 for ($i = $toclevel; $i > 0; $i--) {
2507 if ( $levelCount[$i] == $level ) {
2508 # Found last matching level
2512 elseif ( $levelCount[$i] < $level ) {
2513 # Found first matching level below current level
2520 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2523 # No change in level, end TOC line
2524 $toc .= $sk->tocLineEnd();
2527 $levelCount[$toclevel] = $level;
2529 # count number of headlines for each level
2530 @$sublevelCount[$toclevel]++
;
2532 for( $i = 1; $i <= $toclevel; $i++
) {
2533 if( !empty( $sublevelCount[$i] ) ) {
2537 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2543 # The canonized header is a version of the header text safe to use for links
2544 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2545 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2546 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2548 # Remove link placeholders by the link text.
2549 # <!--LINK number-->
2551 # link text with suffix
2552 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2553 "\$wgLinkHolders['texts'][\$1]",
2554 $canonized_headline );
2555 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2556 "\$wgInterwikiLinkHolders[\$1]",
2557 $canonized_headline );
2560 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2561 $tocline = trim( $canonized_headline );
2562 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2563 $replacearray = array(
2567 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2568 $refer[$headlineCount] = $canonized_headline;
2570 # count how many in assoc. array so we can track dupes in anchors
2571 @$refers[$canonized_headline]++
;
2572 $refcount[$headlineCount]=$refers[$canonized_headline];
2574 # Don't number the heading if it is the only one (looks silly)
2575 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2576 # the two are different if the line contains a link
2577 $headline=$numbering . ' ' . $headline;
2580 # Create the anchor for linking from the TOC to the section
2581 $anchor = $canonized_headline;
2582 if($refcount[$headlineCount] > 1 ) {
2583 $anchor .= '_' . $refcount[$headlineCount];
2585 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2586 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2588 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2589 if ( empty( $head[$headlineCount] ) ) {
2590 $head[$headlineCount] = '';
2593 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2595 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2598 # Add the edit section span
2599 if( $rightClickHack ) {
2601 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2603 $headline = $sk->editSectionScript($this->mTitle
, $sectionCount+
1,$headline);
2606 # give headline the correct <h#> tag
2607 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2615 $toclines = $headlineCount;
2616 $toc .= $sk->tocUnindent( $toclevel - 1 );
2617 $toc = $sk->tocList( $toc );
2620 # split up and insert constructed headlines
2622 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2625 foreach( $blocks as $block ) {
2626 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2627 # This is the [edit] link that appears for the top block of text when
2628 # section editing is enabled
2630 # Disabled because it broke block formatting
2631 # For example, a bullet point in the top line
2632 # $full .= $sk->editSectionLink(0);
2635 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2636 # Top anchor now in skin
2640 if( !empty( $head[$i] ) ) {
2646 $mw =& MagicWord
::get( MAG_TOC
);
2647 return $mw->replace( $toc, $full );
2654 * Return an HTML link for the "ISBN 123456" text
2657 function magicISBN( $text ) {
2659 $fname = 'Parser::magicISBN';
2660 wfProfileIn( $fname );
2662 $a = split( 'ISBN ', ' '.$text );
2663 if ( count ( $a ) < 2 ) {
2664 wfProfileOut( $fname );
2667 $text = substr( array_shift( $a ), 1);
2668 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2670 foreach ( $a as $x ) {
2671 $isbn = $blank = '' ;
2672 while ( ' ' == $x{0} ) {
2674 $x = substr( $x, 1 );
2676 if ( $x == '' ) { # blank isbn
2677 $text .= "ISBN $blank";
2680 while ( strstr( $valid, $x{0} ) != false ) {
2682 $x = substr( $x, 1 );
2684 $num = str_replace( '-', '', $isbn );
2685 $num = str_replace( ' ', '', $num );
2688 $text .= "ISBN $blank$x";
2690 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2691 $text .= '<a href="' .
2692 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2693 "\" class=\"internal\">ISBN $isbn</a>";
2697 wfProfileOut( $fname );
2702 * Return an HTML link for the "GEO ..." text
2705 function magicGEO( $text ) {
2706 global $wgLang, $wgUseGeoMode;
2707 $fname = 'Parser::magicGEO';
2708 wfProfileIn( $fname );
2710 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2711 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2712 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2713 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2714 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2715 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2717 $a = split( 'GEO ', ' '.$text );
2718 if ( count ( $a ) < 2 ) {
2719 wfProfileOut( $fname );
2722 $text = substr( array_shift( $a ), 1);
2723 $valid = '0123456789.+-:';
2725 foreach ( $a as $x ) {
2726 $geo = $blank = '' ;
2727 while ( ' ' == $x{0} ) {
2729 $x = substr( $x, 1 );
2731 while ( strstr( $valid, $x{0} ) != false ) {
2733 $x = substr( $x, 1 );
2735 $num = str_replace( '+', '', $geo );
2736 $num = str_replace( ' ', '', $num );
2738 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2739 $text .= "GEO $blank$x";
2741 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2742 $text .= '<a href="' .
2743 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2744 "\" class=\"internal\">GEO $geo</a>";
2748 wfProfileOut( $fname );
2753 * Return an HTML link for the "RFC 1234" text
2755 * @param string $text text to be processed
2757 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2760 $valid = '0123456789';
2763 $a = split( $keyword, ' '.$text );
2764 if ( count ( $a ) < 2 ) {
2767 $text = substr( array_shift( $a ), 1);
2769 /* Check if keyword is preceed by [[.
2770 * This test is made here cause of the array_shift above
2771 * that prevent the test to be done in the foreach.
2773 if ( substr( $text, -2 ) == '[[' ) {
2777 foreach ( $a as $x ) {
2778 /* token might be empty if we have RFC RFC 1234 */
2786 /** remove and save whitespaces in $blank */
2787 while ( $x{0} == ' ' ) {
2789 $x = substr( $x, 1 );
2792 /** remove and save the rfc number in $id */
2793 while ( strstr( $valid, $x{0} ) != false ) {
2795 $x = substr( $x, 1 );
2799 /* call back stripped spaces*/
2800 $text .= $keyword.$blank.$x;
2801 } elseif( $internal ) {
2803 $text .= $keyword.$id.$x;
2805 /* build the external link*/
2806 $url = wfmsg( $urlmsg );
2807 $url = str_replace( '$1', $id, $url);
2808 $sk =& $this->mOptions
->getSkin();
2809 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2810 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2813 /* Check if the next RFC keyword is preceed by [[ */
2814 $internal = ( substr($x,-2) == '[[' );
2820 * Transform wiki markup when saving a page by doing \r\n -> \n
2821 * conversion, substitting signatures, {{subst:}} templates, etc.
2823 * @param string $text the text to transform
2824 * @param Title &$title the Title object for the current article
2825 * @param User &$user the User object describing the current user
2826 * @param ParserOptions $options parsing options
2827 * @param bool $clearState whether to clear the parser state first
2828 * @return string the altered wiki markup
2831 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2832 $this->mOptions
= $options;
2833 $this->mTitle
=& $title;
2834 $this->mOutputType
= OT_WIKI
;
2836 if ( $clearState ) {
2837 $this->clearState();
2840 $stripState = false;
2844 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2845 $text = $this->strip( $text, $stripState, false );
2846 $text = $this->pstPass2( $text, $user );
2847 $text = $this->unstrip( $text, $stripState );
2848 $text = $this->unstripNoWiki( $text, $stripState );
2853 * Pre-save transform helper function
2856 function pstPass2( $text, &$user ) {
2857 global $wgLang, $wgContLang, $wgLocaltimezone;
2859 # Variable replacement
2860 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2861 $text = $this->replaceVariables( $text );
2865 $n = $user->getName();
2866 $k = $user->getOption( 'nickname' );
2867 if ( '' == $k ) { $k = $n; }
2868 if ( isset( $wgLocaltimezone ) ) {
2869 $oldtz = getenv( 'TZ' );
2870 putenv( 'TZ='.$wgLocaltimezone );
2872 /* Note: this is an ugly timezone hack for the European wikis */
2873 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2874 ' (' . date( 'T' ) . ')';
2875 if ( isset( $wgLocaltimezone ) ) {
2876 putenv( 'TZ='.$oldtzs );
2879 if( $user->getOption( 'fancysig' ) ) {
2882 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2884 $text = preg_replace( '/~~~~~/', $d, $text );
2885 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2886 $text = preg_replace( '/~~~/', $sigText, $text );
2888 # Context links: [[|name]] and [[name (context)|]]
2890 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2891 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2892 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2893 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2895 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2896 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2897 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2898 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2900 $t = $this->mTitle
->getText();
2901 if ( preg_match( $conpat, $t, $m ) ) {
2904 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2905 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2906 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2908 if ( '' == $context ) {
2909 $text = preg_replace( $p2, '[[\\1]]', $text );
2911 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2914 # Trim trailing whitespace
2915 # MAG_END (__END__) tag allows for trailing
2916 # whitespace to be deliberately included
2917 $text = rtrim( $text );
2918 $mw =& MagicWord
::get( MAG_END
);
2919 $mw->matchAndRemove( $text );
2925 * Set up some variables which are usually set up in parse()
2926 * so that an external function can call some class members with confidence
2929 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2930 $this->mTitle
=& $title;
2931 $this->mOptions
= $options;
2932 $this->mOutputType
= $outputType;
2933 if ( $clearState ) {
2934 $this->clearState();
2939 * Transform a MediaWiki message by replacing magic variables.
2941 * @param string $text the text to transform
2942 * @param ParserOptions $options options
2943 * @return string the text with variables substituted
2946 function transformMsg( $text, $options ) {
2948 static $executing = false;
2950 # Guard against infinite recursion
2956 $this->mTitle
= $wgTitle;
2957 $this->mOptions
= $options;
2958 $this->mOutputType
= OT_MSG
;
2959 $this->clearState();
2960 $text = $this->replaceVariables( $text );
2967 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2968 * Callback will be called with the text within
2969 * Transform and return the text within
2972 function setHook( $tag, $callback ) {
2973 $oldVal = @$this->mTagHooks
[$tag];
2974 $this->mTagHooks
[$tag] = $callback;
2979 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2980 * Placeholders created in Skin::makeLinkObj()
2981 * Returns an array of links found, indexed by PDBK:
2985 * $options is a bit field, RLH_FOR_UPDATE to select for update
2987 function replaceLinkHolders( &$text, $options = 0 ) {
2988 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2989 global $wgInterwikiLinkHolders;
2990 global $outputReplace;
2992 if ( $wgUseOldExistenceCheck ) {
2996 $fname = 'Parser::replaceLinkHolders';
2997 wfProfileIn( $fname );
3002 #if ( !empty( $tmpLinks[0] ) ) { #TODO
3003 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
3004 wfProfileIn( $fname.'-check' );
3005 $dbr =& wfGetDB( DB_SLAVE
);
3006 $page = $dbr->tableName( 'page' );
3007 $sk = $wgUser->getSkin();
3008 $threshold = $wgUser->getOption('stubthreshold');
3011 asort( $wgLinkHolders['namespaces'] );
3015 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
3017 $title = $wgLinkHolders['titles'][$key];
3019 # Skip invalid entries.
3020 # Result will be ugly, but prevents crash.
3021 if ( is_null( $title ) ) {
3024 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3026 # Check if it's in the link cache already
3027 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
3028 $colours[$pdbk] = 1;
3029 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3030 $colours[$pdbk] = 0;
3032 # Not in the link cache, add it to the query
3033 if ( !isset( $current ) ) {
3037 $query = "SELECT page_id, page_namespace, page_title";
3038 if ( $threshold > 0 ) {
3039 $textTable = $dbr->tableName( 'text' );
3040 $query .= ', LENGTH(old_text) AS page_len, page_is_redirect';
3041 $tables .= ", $textTable";
3042 $join = 'page_latest=old_id AND';
3044 $query .= " FROM $tables WHERE $join (page_namespace=$val AND page_title IN(";
3045 } elseif ( $current != $val ) {
3047 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3052 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
3057 if ( $options & RLH_FOR_UPDATE
) {
3058 $query .= ' FOR UPDATE';
3061 $res = $dbr->query( $query, $fname );
3063 # Fetch data and form into an associative array
3064 # non-existent = broken
3067 while ( $s = $dbr->fetchObject($res) ) {
3068 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3069 $pdbk = $title->getPrefixedDBkey();
3070 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
3072 if ( $threshold > 0 ) {
3073 $size = $s->page_len
;
3074 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$length < $threshold ) {
3075 $colours[$pdbk] = 1;
3077 $colours[$pdbk] = 2;
3080 $colours[$pdbk] = 1;
3084 wfProfileOut( $fname.'-check' );
3086 # Construct search and replace arrays
3087 wfProfileIn( $fname.'-construct' );
3088 $outputReplace = array();
3089 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
3090 $pdbk = $pdbks[$key];
3091 $searchkey = '<!--LINK '.$key.'-->';
3092 $title = $wgLinkHolders['titles'][$key];
3093 if ( empty( $colours[$pdbk] ) ) {
3094 $wgLinkCache->addBadLink( $pdbk );
3095 $colours[$pdbk] = 0;
3096 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3097 $wgLinkHolders['texts'][$key],
3098 $wgLinkHolders['queries'][$key] );
3099 } elseif ( $colours[$pdbk] == 1 ) {
3100 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3101 $wgLinkHolders['texts'][$key],
3102 $wgLinkHolders['queries'][$key] );
3103 } elseif ( $colours[$pdbk] == 2 ) {
3104 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3105 $wgLinkHolders['texts'][$key],
3106 $wgLinkHolders['queries'][$key] );
3109 wfProfileOut( $fname.'-construct' );
3112 wfProfileIn( $fname.'-replace' );
3114 $text = preg_replace_callback(
3115 '/(<!--LINK .*?-->)/',
3116 "outputReplaceMatches",
3118 wfProfileOut( $fname.'-replace' );
3121 if ( !empty( $wgInterwikiLinkHolders ) ) {
3122 wfProfileIn( $fname.'-interwiki' );
3123 $outputReplace = $wgInterwikiLinkHolders;
3124 $text = preg_replace_callback(
3125 '/<!--IWLINK (.*?)-->/',
3126 "outputReplaceMatches",
3128 wfProfileOut( $fname.'-interwiki' );
3131 wfProfileOut( $fname );
3136 * Renders an image gallery from a text with one line per image.
3137 * text labels may be given by using |-style alternative text. E.g.
3138 * Image:one.jpg|The number "1"
3139 * Image:tree.jpg|A tree
3140 * given as text will return the HTML of a gallery with two images,
3141 * labeled 'The number "1"' and
3144 function renderImageGallery( $text ) {
3145 global $wgLinkCache;
3146 $ig = new ImageGallery();
3147 $ig->setShowBytes( false );
3148 $ig->setShowFilename( false );
3149 $lines = explode( "\n", $text );
3151 foreach ( $lines as $line ) {
3152 # match lines like these:
3153 # Image:someimage.jpg|This is some image
3154 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3156 if ( count( $matches ) == 0 ) {
3159 $nt = Title
::newFromURL( $matches[1] );
3160 if( is_null( $nt ) ) {
3161 # Bogus title. Ignore these so we don't bomb out later.
3164 if ( isset( $matches[3] ) ) {
3165 $label = $matches[3];
3170 # FIXME: Use the full wiki parser and add its links
3171 # to the page's links.
3172 $html = $this->mOptions
->mSkin
->formatComment( $label );
3174 $ig->add( Image
::newFromTitle( $nt ), $html );
3175 $wgLinkCache->addImageLinkObj( $nt );
3177 return $ig->toHTML();
3183 * @package MediaWiki
3187 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3188 var $mCacheTime; # Used in ParserCache
3189 var $mVersion; # Compatibility check
3191 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3192 $containsOldMagic = false )
3194 $this->mText
= $text;
3195 $this->mLanguageLinks
= $languageLinks;
3196 $this->mCategoryLinks
= $categoryLinks;
3197 $this->mContainsOldMagic
= $containsOldMagic;
3198 $this->mCacheTime
= '';
3199 $this->mVersion
= MW_PARSER_VERSION
;
3202 function getText() { return $this->mText
; }
3203 function getLanguageLinks() { return $this->mLanguageLinks
; }
3204 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3205 function getCacheTime() { return $this->mCacheTime
; }
3206 function containsOldMagic() { return $this->mContainsOldMagic
; }
3207 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3208 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3209 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3210 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3211 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3212 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3214 function merge( $other ) {
3215 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3216 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3217 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3221 * Return true if this cached output object predates the global or
3222 * per-article cache invalidation timestamps, or if it comes from
3223 * an incompatible older version.
3225 * @param string $touched the affected article's last touched timestamp
3229 function expired( $touched ) {
3230 global $wgCacheEpoch;
3231 return $this->getCacheTime() <= $touched ||
3232 $this->getCacheTime() <= $wgCacheEpoch ||
3233 !isset( $this->mVersion
) ||
3234 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3239 * Set options of the Parser
3241 * @package MediaWiki
3245 # All variables are private
3246 var $mUseTeX; # Use texvc to expand <math> tags
3247 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
3248 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3249 var $mAllowExternalImages; # Allow external images inline
3250 var $mSkin; # Reference to the preferred skin
3251 var $mDateFormat; # Date format index
3252 var $mEditSection; # Create "edit section" links
3253 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
3254 var $mNumberHeadings; # Automatically number headings
3255 var $mShowToc; # Show table of contents
3257 function getUseTeX() { return $this->mUseTeX
; }
3258 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3259 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3260 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3261 function getSkin() { return $this->mSkin
; }
3262 function getDateFormat() { return $this->mDateFormat
; }
3263 function getEditSection() { return $this->mEditSection
; }
3264 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
3265 function getNumberHeadings() { return $this->mNumberHeadings
; }
3266 function getShowToc() { return $this->mShowToc
; }
3268 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3269 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3270 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3271 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3272 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3273 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3274 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
3275 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3276 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
3278 function setSkin( &$x ) { $this->mSkin
=& $x; }
3281 * Get parser options
3284 function newFromUser( &$user ) {
3285 $popts = new ParserOptions
;
3286 $popts->initialiseFromUser( $user );
3290 /** Get user options */
3291 function initialiseFromUser( &$userInput ) {
3292 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3293 $fname = 'ParserOptions::initialiseFromUser';
3294 wfProfileIn( $fname );
3295 if ( !$userInput ) {
3297 $user->setLoaded( true );
3299 $user =& $userInput;
3302 $this->mUseTeX
= $wgUseTeX;
3303 $this->mUseDynamicDates
= $wgUseDynamicDates;
3304 $this->mInterwikiMagic
= $wgInterwikiMagic;
3305 $this->mAllowExternalImages
= $wgAllowExternalImages;
3306 wfProfileIn( $fname.'-skin' );
3307 $this->mSkin
=& $user->getSkin();
3308 wfProfileOut( $fname.'-skin' );
3309 $this->mDateFormat
= $user->getOption( 'date' );
3310 $this->mEditSection
= $user->getOption( 'editsection' );
3311 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
3312 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3313 $this->mShowToc
= $user->getOption( 'showtoc' );
3314 wfProfileOut( $fname );
3319 * Callback function used by Parser::replaceLinkHolders()
3320 * to substitute link placeholders.
3322 function &outputReplaceMatches( $matches ) {
3323 global $outputReplace;
3324 return $outputReplace[$matches[1]];
3328 * Return the total number of articles
3330 function wfNumberOfArticles() {
3331 global $wgNumberOfArticles;
3334 return $wgNumberOfArticles;
3338 * Get various statistics from the database
3341 function wfLoadSiteStats() {
3342 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3343 $fname = 'wfLoadSiteStats';
3345 if ( -1 != $wgNumberOfArticles ) return;
3346 $dbr =& wfGetDB( DB_SLAVE
);
3347 $s = $dbr->selectRow( 'site_stats',
3348 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3349 array( 'ss_row_id' => 1 ), $fname
3352 if ( $s === false ) {
3355 $wgTotalViews = $s->ss_total_views
;
3356 $wgTotalEdits = $s->ss_total_edits
;
3357 $wgNumberOfArticles = $s->ss_good_articles
;
3363 * Basicly replacing " > and < with HTML entities ( ", >, <)
3365 * @param string $in Text that might contain HTML tags
3366 * @return string Escaped string
3368 function wfEscapeHTMLTagsOnly( $in ) {
3370 array( '"', '>', '<' ),
3371 array( '"', '>', '<' ),