4 * File for Parser and related classes
11 * Update this version number when the ParserOutput format
12 * changes in an incompatible way, so the parser cache
13 * can automatically discard old data.
15 define( 'MW_PARSER_VERSION', '1.4.0' );
18 * Variable substitution O(N^2) attack
20 * Without countermeasures, it would be possible to attack the parser by saving
21 * a page filled with a large number of inclusions of large pages. The size of
22 * the generated page would be proportional to the square of the input size.
23 * Hence, we limit the number of inclusions of any given page, thus bringing any
24 * attack back to O(N).
27 define( 'MAX_INCLUDE_REPEAT', 100 );
28 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
30 define( 'RLH_FOR_UPDATE', 1 );
32 # Allowed values for $mOutputType
33 define( 'OT_HTML', 1 );
34 define( 'OT_WIKI', 2 );
35 define( 'OT_MSG' , 3 );
37 # string parameter for extractTags which will cause it
38 # to strip HTML comments in addition to regular
39 # <XML>-style tags. This should not be anything we
40 # may want to use in wikisyntax
41 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
43 # prefix for escaping, used in two functions at least
44 define( 'UNIQ_PREFIX', 'NaodW29');
46 # Constants needed for external link processing
47 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
48 define( 'HTTP_PROTOCOLS', 'http|https' );
49 # Everything except bracket, space, or control characters
50 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
52 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
53 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
54 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
55 define( 'EXT_LINK_BRACKETED', '/\[(('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
56 define( 'EXT_IMAGE_REGEX',
57 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
58 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
59 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
65 * Processes wiki markup
68 * There are three main entry points into the Parser class:
70 * produces HTML output
72 * produces altered wiki markup.
74 * performs brace substitution on MediaWiki messages
77 * objects: $wgLang, $wgDateFormatter, $wgLinkCache
79 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
82 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
83 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
86 * * only within ParserOptions
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
101 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mOptions, $mTitle, $mOutputType,
105 $mTemplates, // cache of already loaded templates, avoids
106 // multiple SQL queries for the same string
107 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
108 // in this path. Used for loop detection.
118 $this->mTemplates
= array();
119 $this->mTemplatePath
= array();
120 $this->mTagHooks
= array();
129 function clearState() {
130 $this->mOutput
= new ParserOutput
;
131 $this->mAutonumber
= 0;
132 $this->mLastSection
= "";
133 $this->mDTopen
= false;
134 $this->mVariables
= false;
135 $this->mIncludeCount
= array();
136 $this->mStripState
= array();
137 $this->mArgStack
= array();
138 $this->mInPre
= false;
142 * First pass--just handle <nowiki> sections, pass the rest off
143 * to internalParse() which does all the real work.
146 * @return ParserOutput a ParserOutput
148 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
149 global $wgUseTidy, $wgContLang;
150 $fname = 'Parser::parse';
151 wfProfileIn( $fname );
157 $this->mOptions
= $options;
158 $this->mTitle
=& $title;
159 $this->mOutputType
= OT_HTML
;
162 $text = $this->strip( $text, $this->mStripState
);
164 $text = $this->internalParse( $text, $linestart );
165 $text = $this->unstrip( $text, $this->mStripState
);
166 # Clean up special characters, only run once, next-to-last before doBlockLevels
169 # french spaces, last one Guillemet-left
170 # only if there is something before the space
171 '/(.) (?=\\?|:|;|!|\\302\\273)/i' => '\\1 \\2',
172 # french spaces, Guillemet-right
173 "/(\\302\\253) /i"=>"\\1 ",
174 '/<hr *>/i' => '<hr />',
175 '/<br *>/i' => '<br />',
176 '/<center *>/i' => '<div class="center">',
177 '/<\\/center *>/i' => '</div>',
178 # Clean up spare ampersands; note that we probably ought to be
179 # more careful about named entities.
180 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&'
182 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
185 # french spaces, last one Guillemet-left
186 '/ (\\?|:|;|!|\\302\\273)/i' => ' \\1',
187 # french spaces, Guillemet-right
188 '/(\\302\\253) /i' => '\\1 ',
189 '/<center *>/i' => '<div class="center">',
190 '/<\\/center *>/i' => '</div>'
192 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
195 $text = $this->doBlockLevels( $text, $linestart );
197 $this->replaceLinkHolders( $text );
198 $text = $wgContLang->convert($text);
200 $text = $this->unstripNoWiki( $text, $this->mStripState
);
203 $text = Parser
::tidy($text);
206 $this->mOutput
->setText( $text );
207 wfProfileOut( $fname );
208 return $this->mOutput
;
212 * Get a random string
217 function getRandomString() {
218 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
222 * Replaces all occurrences of <$tag>content</$tag> in the text
223 * with a random marker and returns the new text. the output parameter
224 * $content will be an associative array filled with data on the form
225 * $unique_marker => content.
227 * If $content is already set, the additional entries will be appended
228 * If $tag is set to STRIP_COMMENTS, the function will extract
229 * <!-- HTML comments -->
234 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
235 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
242 while ( '' != $text ) {
243 if($tag==STRIP_COMMENTS
) {
244 $p = preg_split( '/<!--/i', $text, 2 );
246 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
249 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
252 if($tag==STRIP_COMMENTS
) {
253 $q = preg_split( '/-->/i', $p[1], 2 );
255 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
257 $marker = $rnd . sprintf('%08X', $n++
);
258 $content[$marker] = $q[0];
259 $stripped .= $marker;
267 * Strips and renders nowiki, pre, math, hiero
268 * If $render is set, performs necessary rendering operations on plugins
269 * Returns the text, and fills an array with data needed in unstrip()
270 * If the $state is already a valid strip state, it adds to the state
272 * @param bool $stripcomments when set, HTML comments <!-- like this -->
273 * will be stripped in addition to other tags. This is important
274 * for section editing, where these comments cause confusion when
275 * counting the sections in the wikisource
279 function strip( $text, &$state, $stripcomments = false ) {
280 $render = ($this->mOutputType
== OT_HTML
);
281 $html_content = array();
282 $nowiki_content = array();
283 $math_content = array();
284 $pre_content = array();
285 $comment_content = array();
286 $ext_content = array();
287 $gallery_content = array();
289 # Replace any instances of the placeholders
290 $uniq_prefix = UNIQ_PREFIX
;
291 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
294 global $wgRawHtml, $wgWhitelistEdit;
295 if( $wgRawHtml && $wgWhitelistEdit ) {
296 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
297 foreach( $html_content as $marker => $content ) {
299 # Raw and unchecked for validity.
300 $html_content[$marker] = $content;
302 $html_content[$marker] = '<html>'.$content.'</html>';
308 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
309 foreach( $nowiki_content as $marker => $content ) {
311 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
313 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
318 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
319 foreach( $math_content as $marker => $content ){
321 if( $this->mOptions
->getUseTeX() ) {
322 $math_content[$marker] = renderMath( $content );
324 $math_content[$marker] = '<math>'.$content.'<math>';
327 $math_content[$marker] = '<math>'.$content.'</math>';
332 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
333 foreach( $pre_content as $marker => $content ){
335 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
337 $pre_content[$marker] = '<pre>'.$content.'</pre>';
342 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
343 foreach( $gallery_content as $marker => $content ) {
344 require_once( 'ImageGallery.php' );
346 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
348 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
354 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
355 foreach( $comment_content as $marker => $content ){
356 $comment_content[$marker] = '<!--'.$content.'-->';
361 foreach ( $this->mTagHooks
as $tag => $callback ) {
362 $ext_contents[$tag] = array();
363 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
364 foreach( $ext_content[$tag] as $marker => $content ) {
366 $ext_content[$tag][$marker] = $callback( $content );
368 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
373 # Merge state with the pre-existing state, if there is one
375 $state['html'] = $state['html'] +
$html_content;
376 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
377 $state['math'] = $state['math'] +
$math_content;
378 $state['pre'] = $state['pre'] +
$pre_content;
379 $state['comment'] = $state['comment'] +
$comment_content;
380 $state['gallery'] = $state['gallery'] +
$gallery_content;
382 foreach( $ext_content as $tag => $array ) {
383 if ( array_key_exists( $tag, $state ) ) {
384 $state[$tag] = $state[$tag] +
$array;
389 'html' => $html_content,
390 'nowiki' => $nowiki_content,
391 'math' => $math_content,
392 'pre' => $pre_content,
393 'comment' => $comment_content,
394 'gallery' => $gallery_content,
401 * restores pre, math, and hiero removed by strip()
403 * always call unstripNoWiki() after this one
406 function unstrip( $text, &$state ) {
407 # Must expand in reverse order, otherwise nested tags will be corrupted
408 $contentDict = end( $state );
409 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
410 if( key($state) != 'nowiki' && key($state) != 'html') {
411 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
412 $text = str_replace( key( $contentDict ), $content, $text );
421 * always call this after unstrip() to preserve the order
425 function unstripNoWiki( $text, &$state ) {
426 # Must expand in reverse order, otherwise nested tags will be corrupted
427 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
428 $text = str_replace( key( $state['nowiki'] ), $content, $text );
433 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
434 $text = str_replace( key( $state['html'] ), $content, $text );
442 * Add an item to the strip state
443 * Returns the unique tag which must be inserted into the stripped text
444 * The tag will be replaced with the original text in unstrip()
448 function insertStripItem( $text, &$state ) {
449 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
458 $state['item'][$rnd] = $text;
463 * Return allowed HTML attributes
467 function getHTMLattrs () {
468 $htmlattrs = array( # Allowed attributes--no scripting, etc.
469 'title', 'align', 'lang', 'dir', 'width', 'height',
470 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
471 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
472 /* FONT */ 'type', 'start', 'value', 'compact',
473 /* For various lists, mostly deprecated but safe */
474 'summary', 'width', 'border', 'frame', 'rules',
475 'cellspacing', 'cellpadding', 'valign', 'char',
476 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
477 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
478 'id', 'class', 'name', 'style' /* For CSS */
484 * Remove non approved attributes and javascript in css
488 function fixTagAttributes ( $t ) {
489 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
490 $htmlattrs = $this->getHTMLattrs() ;
492 # Strip non-approved attributes from the tag
494 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
495 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
498 $t = str_replace ( '<></>' , '' , $t ) ; # This should fix bug 980557
500 # Strip javascript "expression" from stylesheets. Brute force approach:
501 # If anythin offensive is found, all attributes of the HTML tag are dropped
504 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
505 wfMungeToUtf8( $t ) ) )
514 * interface with html tidy, used if $wgUseTidy = true
519 function tidy ( $text ) {
520 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
521 global $wgInputEncoding, $wgOutputEncoding;
522 $fname = 'Parser::tidy';
523 wfProfileIn( $fname );
527 switch(strtoupper($wgOutputEncoding)) {
529 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -latin1':' -raw';
532 $opts .= ($wgInputEncoding == $wgOutputEncoding)?
' -utf8':' -raw';
538 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
539 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
540 '<head><title>test</title></head><body>'.$text.'</body></html>';
541 $descriptorspec = array(
542 0 => array('pipe', 'r'),
543 1 => array('pipe', 'w'),
544 2 => array('file', '/dev/null', 'a')
546 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
547 if (is_resource($process)) {
548 fwrite($pipes[0], $wrappedtext);
550 while (!feof($pipes[1])) {
551 $cleansource .= fgets($pipes[1], 1024);
554 $return_value = proc_close($process);
557 wfProfileOut( $fname );
559 if( $cleansource == '' && $text != '') {
560 wfDebug( "Tidy error detected!\n" );
561 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
568 * parse the wiki syntax used to render tables
572 function doTableStuff ( $t ) {
573 $fname = 'Parser::doTableStuff';
574 wfProfileIn( $fname );
576 $t = explode ( "\n" , $t ) ;
577 $td = array () ; # Is currently a td tag open?
578 $ltd = array () ; # Was it TD or TH?
579 $tr = array () ; # Is currently a tr tag open?
580 $ltr = array () ; # tr attributes
581 $indent_level = 0; # indent level of the table
582 foreach ( $t AS $k => $x )
585 $fc = substr ( $x , 0 , 1 ) ;
586 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
587 $indent_level = strlen( $matches[1] );
589 str_repeat( '<dl><dd>', $indent_level ) .
590 '<table ' . $this->fixTagAttributes ( $matches[2] ) . '>' ;
591 array_push ( $td , false ) ;
592 array_push ( $ltd , '' ) ;
593 array_push ( $tr , false ) ;
594 array_push ( $ltr , '' ) ;
596 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
597 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
599 $l = array_pop ( $ltd ) ;
600 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
601 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
603 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
605 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
606 $x = substr ( $x , 1 ) ;
607 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
609 $l = array_pop ( $ltd ) ;
610 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
611 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
614 array_push ( $tr , false ) ;
615 array_push ( $td , false ) ;
616 array_push ( $ltd , '' ) ;
617 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
619 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
621 if ( '|+' == substr ( $x , 0 , 2 ) ) {
623 $x = substr ( $x , 1 ) ;
625 $after = substr ( $x , 1 ) ;
626 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
627 $after = explode ( '||' , $after ) ;
630 # Loop through each table cell
631 foreach ( $after AS $theline )
636 $tra = array_pop ( $ltr ) ;
637 if ( !array_pop ( $tr ) ) $z = '<tr '.$tra.">\n" ;
638 array_push ( $tr , true ) ;
639 array_push ( $ltr , '' ) ;
642 $l = array_pop ( $ltd ) ;
643 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
644 if ( $fc == '|' ) $l = 'td' ;
645 else if ( $fc == '!' ) $l = 'th' ;
646 else if ( $fc == '+' ) $l = 'caption' ;
648 array_push ( $ltd , $l ) ;
651 $y = explode ( '|' , $theline , 2 ) ;
652 # Note that a '|' inside an invalid link should not
653 # be mistaken as delimiting cell parameters
654 if ( strpos( $y[0], '[[' ) !== false ) {
655 $y = array ($theline);
657 if ( count ( $y ) == 1 )
658 $y = "{$z}<{$l}>{$y[0]}" ;
659 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
661 array_push ( $td , true ) ;
666 # Closing open td, tr && table
667 while ( count ( $td ) > 0 )
669 if ( array_pop ( $td ) ) $t[] = '</td>' ;
670 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
674 $t = implode ( "\n" , $t ) ;
675 # $t = $this->removeHTMLtags( $t );
676 wfProfileOut( $fname );
681 * Helper function for parse() that transforms wiki markup into
682 * HTML. Only called for $mOutputType == OT_HTML.
686 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
689 $fname = 'Parser::internalParse';
690 wfProfileIn( $fname );
692 $text = $this->removeHTMLtags( $text );
693 $text = $this->replaceVariables( $text, $args );
695 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
697 $text = $this->doHeadings( $text );
698 if($this->mOptions
->getUseDynamicDates()) {
699 global $wgDateFormatter;
700 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
702 $text = $this->doAllQuotes( $text );
703 $text = $this->replaceInternalLinks( $text );
704 $text = $this->replaceExternalLinks( $text );
706 # replaceInternalLinks may sometimes leave behind
707 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
708 $text = str_replace("http-noparse://","http://",$text);
710 $text = $this->doMagicLinks( $text );
711 $text = $this->doTableStuff( $text );
712 $text = $this->formatHeadings( $text, $isMain );
713 $sk =& $this->mOptions
->getSkin();
714 $text = $sk->transformContent( $text );
716 wfProfileOut( $fname );
721 * Replace special strings like "ISBN xxx" and "RFC xxx" with
722 * magic external links.
726 function &doMagicLinks( &$text ) {
727 global $wgUseGeoMode;
728 $text = $this->magicISBN( $text );
729 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
730 $text = $this->magicGEO( $text );
732 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
733 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
738 * Parse ^^ tokens and return html
742 function doExponent( $text ) {
743 $fname = 'Parser::doExponent';
744 wfProfileIn( $fname );
745 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
746 wfProfileOut( $fname );
751 * Parse headers and return html
755 function doHeadings( $text ) {
756 $fname = 'Parser::doHeadings';
757 wfProfileIn( $fname );
758 for ( $i = 6; $i >= 1; --$i ) {
759 $h = substr( '======', 0, $i );
760 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
761 "<h{$i}>\\1</h{$i}>\\2", $text );
763 wfProfileOut( $fname );
768 * Replace single quotes with HTML markup
770 * @return string the altered text
772 function doAllQuotes( $text ) {
773 $fname = 'Parser::doAllQuotes';
774 wfProfileIn( $fname );
776 $lines = explode( "\n", $text );
777 foreach ( $lines as $line ) {
778 $outtext .= $this->doQuotes ( $line ) . "\n";
780 $outtext = substr($outtext, 0,-1);
781 wfProfileOut( $fname );
786 * Helper function for doAllQuotes()
789 function doQuotes( $text ) {
790 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
791 if ( count( $arr ) == 1 )
795 # First, do some preliminary work. This may shift some apostrophes from
796 # being mark-up to being text. It also counts the number of occurrences
797 # of bold and italics mark-ups.
801 foreach ( $arr as $r )
803 if ( ( $i %
2 ) == 1 )
805 # If there are ever four apostrophes, assume the first is supposed to
806 # be text, and the remaining three constitute mark-up for bold text.
807 if ( strlen( $arr[$i] ) == 4 )
812 # If there are more than 5 apostrophes in a row, assume they're all
813 # text except for the last 5.
814 else if ( strlen( $arr[$i] ) > 5 )
816 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
819 # Count the number of occurrences of bold and italics mark-ups.
820 # We are not counting sequences of five apostrophes.
821 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
822 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
823 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
828 # If there is an odd number of both bold and italics, it is likely
829 # that one of the bold ones was meant to be an apostrophe followed
830 # by italics. Which one we cannot know for certain, but it is more
831 # likely to be one that has a single-letter word before it.
832 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
835 $firstsingleletterword = -1;
836 $firstmultiletterword = -1;
838 foreach ( $arr as $r )
840 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
842 $x1 = substr ($arr[$i-1], -1);
843 $x2 = substr ($arr[$i-1], -2, 1);
845 if ($firstspace == -1) $firstspace = $i;
846 } else if ($x2 == ' ') {
847 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
849 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
855 # If there is a single-letter word, use it!
856 if ($firstsingleletterword > -1)
858 $arr [ $firstsingleletterword ] = "''";
859 $arr [ $firstsingleletterword-1 ] .= "'";
861 # If not, but there's a multi-letter word, use that one.
862 else if ($firstmultiletterword > -1)
864 $arr [ $firstmultiletterword ] = "''";
865 $arr [ $firstmultiletterword-1 ] .= "'";
867 # ... otherwise use the first one that has neither.
868 # (notice that it is possible for all three to be -1 if, for example,
869 # there is only one pentuple-apostrophe in the line)
870 else if ($firstspace > -1)
872 $arr [ $firstspace ] = "''";
873 $arr [ $firstspace-1 ] .= "'";
877 # Now let's actually convert our apostrophic mush to HTML!
886 if ($state == 'both')
893 if (strlen ($r) == 2)
896 { $output .= '</i>'; $state = ''; }
897 else if ($state == 'bi')
898 { $output .= '</i>'; $state = 'b'; }
899 else if ($state == 'ib')
900 { $output .= '</b></i><b>'; $state = 'b'; }
901 else if ($state == 'both')
902 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
903 else # $state can be 'b' or ''
904 { $output .= '<i>'; $state .= 'i'; }
906 else if (strlen ($r) == 3)
909 { $output .= '</b>'; $state = ''; }
910 else if ($state == 'bi')
911 { $output .= '</i></b><i>'; $state = 'i'; }
912 else if ($state == 'ib')
913 { $output .= '</b>'; $state = 'i'; }
914 else if ($state == 'both')
915 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
916 else # $state can be 'i' or ''
917 { $output .= '<b>'; $state .= 'b'; }
919 else if (strlen ($r) == 5)
922 { $output .= '</b><i>'; $state = 'i'; }
923 else if ($state == 'i')
924 { $output .= '</i><b>'; $state = 'b'; }
925 else if ($state == 'bi')
926 { $output .= '</i></b>'; $state = ''; }
927 else if ($state == 'ib')
928 { $output .= '</b></i>'; $state = ''; }
929 else if ($state == 'both')
930 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
931 else # ($state == '')
932 { $buffer = ''; $state = 'both'; }
937 # Now close all remaining tags. Notice that the order is important.
938 if ($state == 'b' ||
$state == 'ib')
940 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
944 if ($state == 'both')
945 $output .= '<b><i>'.$buffer.'</i></b>';
951 * Replace external links
953 * Note: this is all very hackish and the order of execution matters a lot.
954 * Make sure to run maintenance/parserTests.php if you change this code.
958 function replaceExternalLinks( $text ) {
959 $fname = 'Parser::replaceExternalLinks';
960 wfProfileIn( $fname );
962 $sk =& $this->mOptions
->getSkin();
963 $linktrail = wfMsgForContent('linktrail');
964 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
966 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
969 while ( $i<count( $bits ) ) {
971 $protocol = $bits[$i++
];
973 $trail = $bits[$i++
];
975 # The characters '<' and '>' (which were escaped by
976 # removeHTMLtags()) should not be included in
977 # URLs, per RFC 2396.
978 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
979 $text = substr($url, $m2[0][1]) . ' ' . $text;
980 $url = substr($url, 0, $m2[0][1]);
983 # If the link text is an image URL, replace it with an <img> tag
984 # This happened by accident in the original parser, but some people used it extensively
985 $img = $this->maybeMakeImageLink( $text );
986 if ( $img !== false ) {
992 # No link text, e.g. [http://domain.tld/some.link]
994 # Autonumber if allowed
995 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
996 $text = '[' . ++
$this->mAutonumber
. ']';
998 # Otherwise just use the URL
999 $text = htmlspecialchars( $url );
1002 # Have link text, e.g. [http://domain.tld/some.link text]s
1004 if ( preg_match( $linktrail, $trail, $m2 ) ) {
1010 $encUrl = htmlspecialchars( $url );
1011 # Bit in parentheses showing the URL for the printable version
1012 if( $url == $text ||
preg_match( "!$protocol://" . preg_quote( $text, '/' ) . "/?$!", $url ) ) {
1015 # Expand the URL for printable version
1016 if ( ! $sk->suppressUrlExpansion() ) {
1017 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
1023 # Process the trail (i.e. everything after this link up until start of the next link),
1024 # replacing any non-bracketed links
1025 $trail = $this->replaceFreeExternalLinks( $trail );
1027 # Use the encoded URL
1028 # This means that users can paste URLs directly into the text
1029 # Funny characters like ö aren't valid in URLs anyway
1030 # This was changed in August 2004
1031 $s .= $sk->makeExternalLink( $url, $text, false ) . $dtrail. $paren . $trail;
1034 wfProfileOut( $fname );
1039 * Replace anything that looks like a URL with a link
1042 function replaceFreeExternalLinks( $text ) {
1043 $fname = 'Parser::replaceFreeExternalLinks';
1044 wfProfileIn( $fname );
1046 $bits = preg_split( '/((?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1047 $s = array_shift( $bits );
1050 $sk =& $this->mOptions
->getSkin();
1052 while ( $i < count( $bits ) ){
1053 $protocol = $bits[$i++
];
1054 $remainder = $bits[$i++
];
1056 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1057 # Found some characters after the protocol that look promising
1058 $url = $protocol . $m[1];
1061 # The characters '<' and '>' (which were escaped by
1062 # removeHTMLtags()) should not be included in
1063 # URLs, per RFC 2396.
1064 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1065 $trail = substr($url, $m2[0][1]) . $trail;
1066 $url = substr($url, 0, $m2[0][1]);
1069 # Move trailing punctuation to $trail
1071 # If there is no left bracket, then consider right brackets fair game too
1072 if ( strpos( $url, '(' ) === false ) {
1076 $numSepChars = strspn( strrev( $url ), $sep );
1077 if ( $numSepChars ) {
1078 $trail = substr( $url, -$numSepChars ) . $trail;
1079 $url = substr( $url, 0, -$numSepChars );
1082 # Replace & from obsolete syntax with &.
1083 # All HTML entities will be escaped by makeExternalLink()
1084 # or maybeMakeImageLink()
1085 $url = str_replace( '&', '&', $url );
1087 # Is this an external image?
1088 $text = $this->maybeMakeImageLink( $url );
1089 if ( $text === false ) {
1090 # Not an image, make a link
1091 $text = $sk->makeExternalLink( $url, $url );
1093 $s .= $text . $trail;
1095 $s .= $protocol . $remainder;
1103 * make an image if it's allowed
1106 function maybeMakeImageLink( $url ) {
1107 $sk =& $this->mOptions
->getSkin();
1109 if ( $this->mOptions
->getAllowExternalImages() ) {
1110 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1112 $text = $sk->makeImage( htmlspecialchars( $url ) );
1119 * Process [[ ]] wikilinks
1124 function replaceInternalLinks( $s ) {
1125 global $wgLang, $wgContLang, $wgLinkCache;
1126 global $wgDisableLangConversion;
1127 static $fname = 'Parser::replaceInternalLinks' ;
1129 wfProfileIn( $fname );
1131 wfProfileIn( $fname.'-setup' );
1133 # the % is needed to support urlencoded titles as well
1134 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1136 $sk =& $this->mOptions
->getSkin();
1137 global $wgUseOldExistenceCheck;
1138 # "Post-parse link colour check" works only on wiki text since it's now
1139 # in Parser. Enable it, then disable it when we're done.
1140 $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
1142 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1144 #split the entire text string on occurences of [[
1145 $a = explode( '[[', ' ' . $s );
1146 #get the first element (all text up to first [[), and remove the space we added
1147 $s = array_shift( $a );
1148 $s = substr( $s, 1 );
1150 # Match a link having the form [[namespace:link|alternate]]trail
1152 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1153 # Match cases where there is no "]]", which might still be images
1154 static $e1_img = FALSE;
1155 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1156 # Match the end of a line for a word that's not followed by whitespace,
1157 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1158 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1160 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1162 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1164 if ( $useLinkPrefixExtension ) {
1165 if ( preg_match( $e2, $s, $m ) ) {
1166 $first_prefix = $m[2];
1169 $first_prefix = false;
1175 $selflink = $this->mTitle
->getPrefixedText();
1176 wfProfileOut( $fname.'-setup' );
1178 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1179 $useSubpages = $this->areSubpagesAllowed();
1181 # Loop for each link
1182 for ($k = 0; isset( $a[$k] ); $k++
) {
1184 if ( $useLinkPrefixExtension ) {
1185 wfProfileIn( $fname.'-prefixhandling' );
1186 if ( preg_match( $e2, $s, $m ) ) {
1194 $prefix = $first_prefix;
1195 $first_prefix = false;
1197 wfProfileOut( $fname.'-prefixhandling' );
1200 $might_be_img = false;
1202 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1204 # fix up urlencoded title texts
1205 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1207 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1208 $might_be_img = true;
1210 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1212 } else { # Invalid form; output directly
1213 $s .= $prefix . '[[' . $line ;
1217 # Don't allow internal links to pages containing
1218 # PROTO: where PROTO is a valid URL protocol; these
1219 # should be external links.
1220 if (preg_match('/^((?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1221 $s .= $prefix . '[[' . $line ;
1225 # Make subpage if necessary
1226 if( $useSubpages ) {
1227 $link = $this->maybeDoSubpageLink( $m[1], $text );
1232 $noforce = (substr($m[1], 0, 1) != ':');
1234 # Strip off leading ':'
1235 $link = substr($link, 1);
1238 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1240 $s .= $prefix . '[[' . $line;
1244 #check other language variants of the link
1245 #if the article does not exist
1246 if( $checkVariantLink
1247 && $nt->getArticleID() == 0 ) {
1248 $wgContLang->findVariantLink($link, $nt);
1251 $ns = $nt->getNamespace();
1252 $iw = $nt->getInterWiki();
1254 if ($might_be_img) { # if this is actually an invalid link
1255 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1257 while (isset ($a[$k+
1]) ) {
1258 #look at the next 'line' to see if we can close it there
1259 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1260 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1261 # the first ]] closes the inner link, the second the image
1263 $text .= '[[' . $m[1];
1266 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1267 #if there's exactly one ]] that's fine, we'll keep looking
1268 $text .= '[[' . $m[0];
1270 #if $next_line is invalid too, we need look no further
1271 $text .= '[[' . $next_line;
1276 # we couldn't find the end of this imageLink, so output it raw
1277 #but don't ignore what might be perfectly normal links in the text we've examined
1278 $text = $this->replaceInternalLinks($text);
1279 $s .= $prefix . '[[' . $link . '|' . $text;
1280 # note: no $trail, because without an end, there *is* no trail
1283 } else { #it's not an image, so output it raw
1284 $s .= $prefix . '[[' . $link . '|' . $text;
1285 # note: no $trail, because without an end, there *is* no trail
1290 $wasblank = ( '' == $text );
1291 if( $wasblank ) $text = $link;
1294 # Link not escaped by : , create the various objects
1298 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1299 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1300 $tmp = $prefix . $trail ;
1301 $s .= (trim($tmp) == '')?
'': $tmp;
1305 if ( $ns == NS_IMAGE
) {
1306 wfProfileIn( "$fname-image" );
1308 # recursively parse links inside the image caption
1309 # actually, this will parse them in any other parameters, too,
1310 # but it might be hard to fix that, and it doesn't matter ATM
1311 $text = $this->replaceExternalLinks($text);
1312 $text = $this->replaceInternalLinks($text);
1314 # replace the image with a link-holder so that replaceExternalLinks() can't mess with it
1315 $s .= $prefix . $this->insertStripItem( $sk->makeImageLinkObj( $nt, $text ), $this->mStripState
) . $trail;
1316 $wgLinkCache->addImageLinkObj( $nt );
1318 wfProfileOut( "$fname-image" );
1322 if ( $ns == NS_CATEGORY
) {
1323 wfProfileIn( "$fname-category" );
1324 $t = $nt->getText();
1326 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1327 $pPLC=$sk->postParseLinkColour();
1328 $sk->postParseLinkColour( false );
1329 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1330 $sk->postParseLinkColour( $pPLC );
1331 $wgLinkCache->resume();
1334 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1335 $sortkey = $this->mTitle
->getText();
1337 $sortkey = $this->mTitle
->getPrefixedText();
1342 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1343 $this->mOutput
->addCategoryLink( $t );
1344 $s .= $prefix . $trail ;
1346 wfProfileOut( "$fname-category" );
1351 if( ( $nt->getPrefixedText() === $selflink ) &&
1352 ( $nt->getFragment() === '' ) ) {
1353 # Self-links are handled specially; generally de-link and change to bold.
1354 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1358 # Special and Media are pseudo-namespaces; no pages actually exist in them
1359 if( $ns == NS_MEDIA
) {
1360 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1361 $wgLinkCache->addImageLinkObj( $nt );
1363 } elseif( $ns == NS_SPECIAL
) {
1364 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1367 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1369 $sk->postParseLinkColour( $saveParseColour );
1370 wfProfileOut( $fname );
1375 * Return true if subpage links should be expanded on this page.
1378 function areSubpagesAllowed() {
1379 # Some namespaces don't allow subpages
1380 global $wgNamespacesWithSubpages;
1381 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1385 * Handle link to subpage if necessary
1386 * @param string $target the source of the link
1387 * @param string &$text the link text, modified as necessary
1388 * @return string the full name of the link
1391 function maybeDoSubpageLink($target, &$text) {
1394 # :Foobar -- override special treatment of prefix (images, language links)
1395 # /Foobar -- convert to CurrentPage/Foobar
1396 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1398 $fname = 'Parser::maybeDoSubpageLink';
1399 wfProfileIn( $fname );
1400 # Look at the first character
1401 if( $target != '' && $target{0} == '/' ) {
1402 # / at end means we don't want the slash to be shown
1403 if(substr($target,-1,1)=='/') {
1404 $target=substr($target,1,-1);
1407 $noslash=substr($target,1);
1410 # Some namespaces don't allow subpages
1411 if( $this->areSubpagesAllowed() ) {
1412 # subpages allowed here
1413 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1414 if( '' === $text ) {
1416 } # this might be changed for ugliness reasons
1418 # no subpage allowed, use standard link
1426 wfProfileOut( $fname );
1431 * Used by doBlockLevels()
1434 /* private */ function closeParagraph() {
1436 if ( '' != $this->mLastSection
) {
1437 $result = '</' . $this->mLastSection
. ">\n";
1439 $this->mInPre
= false;
1440 $this->mLastSection
= '';
1443 # getCommon() returns the length of the longest common substring
1444 # of both arguments, starting at the beginning of both.
1446 /* private */ function getCommon( $st1, $st2 ) {
1447 $fl = strlen( $st1 );
1448 $shorter = strlen( $st2 );
1449 if ( $fl < $shorter ) { $shorter = $fl; }
1451 for ( $i = 0; $i < $shorter; ++
$i ) {
1452 if ( $st1{$i} != $st2{$i} ) { break; }
1456 # These next three functions open, continue, and close the list
1457 # element appropriate to the prefix character passed into them.
1459 /* private */ function openList( $char ) {
1460 $result = $this->closeParagraph();
1462 if ( '*' == $char ) { $result .= '<ul><li>'; }
1463 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1464 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1465 else if ( ';' == $char ) {
1466 $result .= '<dl><dt>';
1467 $this->mDTopen
= true;
1469 else { $result = '<!-- ERR 1 -->'; }
1474 /* private */ function nextItem( $char ) {
1475 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1476 else if ( ':' == $char ||
';' == $char ) {
1478 if ( $this->mDTopen
) { $close = '</dt>'; }
1479 if ( ';' == $char ) {
1480 $this->mDTopen
= true;
1481 return $close . '<dt>';
1483 $this->mDTopen
= false;
1484 return $close . '<dd>';
1487 return '<!-- ERR 2 -->';
1490 /* private */ function closeList( $char ) {
1491 if ( '*' == $char ) { $text = '</li></ul>'; }
1492 else if ( '#' == $char ) { $text = '</li></ol>'; }
1493 else if ( ':' == $char ) {
1494 if ( $this->mDTopen
) {
1495 $this->mDTopen
= false;
1496 $text = '</dt></dl>';
1498 $text = '</dd></dl>';
1501 else { return '<!-- ERR 3 -->'; }
1507 * Make lists from lines starting with ':', '*', '#', etc.
1510 * @return string the lists rendered as HTML
1512 function doBlockLevels( $text, $linestart ) {
1513 $fname = 'Parser::doBlockLevels';
1514 wfProfileIn( $fname );
1516 # Parsing through the text line by line. The main thing
1517 # happening here is handling of block-level elements p, pre,
1518 # and making lists from lines starting with * # : etc.
1520 $textLines = explode( "\n", $text );
1522 $lastPrefix = $output = $lastLine = '';
1523 $this->mDTopen
= $inBlockElem = false;
1525 $paragraphStack = false;
1527 if ( !$linestart ) {
1528 $output .= array_shift( $textLines );
1530 foreach ( $textLines as $oLine ) {
1531 $lastPrefixLength = strlen( $lastPrefix );
1532 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1533 $preOpenMatch = preg_match('/<pre/i', $oLine );
1534 if ( !$this->mInPre
) {
1535 # Multiple prefixes may abut each other for nested lists.
1536 $prefixLength = strspn( $oLine, '*#:;' );
1537 $pref = substr( $oLine, 0, $prefixLength );
1540 $pref2 = str_replace( ';', ':', $pref );
1541 $t = substr( $oLine, $prefixLength );
1542 $this->mInPre
= !empty($preOpenMatch);
1544 # Don't interpret any other prefixes in preformatted text
1546 $pref = $pref2 = '';
1551 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1552 # Same as the last item, so no need to deal with nesting or opening stuff
1553 $output .= $this->nextItem( substr( $pref, -1 ) );
1554 $paragraphStack = false;
1556 if ( substr( $pref, -1 ) == ';') {
1557 # The one nasty exception: definition lists work like this:
1558 # ; title : definition text
1559 # So we check for : in the remainder text to split up the
1560 # title and definition, without b0rking links.
1561 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1563 $output .= $term . $this->nextItem( ':' );
1566 } elseif( $prefixLength ||
$lastPrefixLength ) {
1567 # Either open or close a level...
1568 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1569 $paragraphStack = false;
1571 while( $commonPrefixLength < $lastPrefixLength ) {
1572 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1573 --$lastPrefixLength;
1575 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1576 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1578 while ( $prefixLength > $commonPrefixLength ) {
1579 $char = substr( $pref, $commonPrefixLength, 1 );
1580 $output .= $this->openList( $char );
1582 if ( ';' == $char ) {
1583 # FIXME: This is dupe of code above
1584 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1586 $output .= $term . $this->nextItem( ':' );
1589 ++
$commonPrefixLength;
1591 $lastPrefix = $pref2;
1593 if( 0 == $prefixLength ) {
1594 wfProfileIn( "$fname-paragraph" );
1595 # No prefix (not in list)--go to paragraph mode
1596 $uniq_prefix = UNIQ_PREFIX
;
1597 // XXX: use a stack for nestable elements like span, table and div
1598 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1599 $closematch = preg_match(
1600 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1601 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1602 if ( $openmatch or $closematch ) {
1603 $paragraphStack = false;
1604 $output .= $this->closeParagraph();
1605 if($preOpenMatch and !$preCloseMatch) {
1606 $this->mInPre
= true;
1608 if ( $closematch ) {
1609 $inBlockElem = false;
1611 $inBlockElem = true;
1613 } else if ( !$inBlockElem && !$this->mInPre
) {
1614 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1616 if ($this->mLastSection
!= 'pre') {
1617 $paragraphStack = false;
1618 $output .= $this->closeParagraph().'<pre>';
1619 $this->mLastSection
= 'pre';
1621 $t = substr( $t, 1 );
1624 if ( '' == trim($t) ) {
1625 if ( $paragraphStack ) {
1626 $output .= $paragraphStack.'<br />';
1627 $paragraphStack = false;
1628 $this->mLastSection
= 'p';
1630 if ($this->mLastSection
!= 'p' ) {
1631 $output .= $this->closeParagraph();
1632 $this->mLastSection
= '';
1633 $paragraphStack = '<p>';
1635 $paragraphStack = '</p><p>';
1639 if ( $paragraphStack ) {
1640 $output .= $paragraphStack;
1641 $paragraphStack = false;
1642 $this->mLastSection
= 'p';
1643 } else if ($this->mLastSection
!= 'p') {
1644 $output .= $this->closeParagraph().'<p>';
1645 $this->mLastSection
= 'p';
1650 wfProfileOut( "$fname-paragraph" );
1652 if ($paragraphStack === false) {
1656 while ( $prefixLength ) {
1657 $output .= $this->closeList( $pref2{$prefixLength-1} );
1660 if ( '' != $this->mLastSection
) {
1661 $output .= '</' . $this->mLastSection
. '>';
1662 $this->mLastSection
= '';
1665 wfProfileOut( $fname );
1670 * Split up a string on ':', ignoring any occurences inside
1671 * <a>..</a> or <span>...</span>
1672 * @param string $str the string to split
1673 * @param string &$before set to everything before the ':'
1674 * @param string &$after set to everything after the ':'
1675 * return string the position of the ':', or false if none found
1677 function findColonNoLinks($str, &$before, &$after) {
1678 # I wonder if we should make this count all tags, not just <a>
1679 # and <span>. That would prevent us from matching a ':' that
1680 # comes in the middle of italics other such formatting....
1682 $fname = 'Parser::findColonNoLinks';
1683 wfProfileIn( $fname );
1686 $colon = strpos($str, ':', $pos);
1688 if ($colon !== false) {
1689 $before = substr($str, 0, $colon);
1690 $after = substr($str, $colon +
1);
1692 # Skip any ':' within <a> or <span> pairs
1693 $a = substr_count($before, '<a');
1694 $s = substr_count($before, '<span');
1695 $ca = substr_count($before, '</a>');
1696 $cs = substr_count($before, '</span>');
1698 if ($a <= $ca and $s <= $cs) {
1699 # Tags are balanced before ':'; ok
1704 } while ($colon !== false);
1705 wfProfileOut( $fname );
1710 * Return value of a magic variable (like PAGENAME)
1714 function getVariableValue( $index ) {
1715 global $wgContLang, $wgSitename, $wgServer;
1718 * Some of these require message or data lookups and can be
1719 * expensive to check many times.
1721 static $varCache = array();
1722 if( isset( $varCache[$index] ) ) return $varCache[$index];
1725 case MAG_CURRENTMONTH
:
1726 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1727 case MAG_CURRENTMONTHNAME
:
1728 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1729 case MAG_CURRENTMONTHNAMEGEN
:
1730 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1731 case MAG_CURRENTDAY
:
1732 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1734 return $this->mTitle
->getText();
1736 return $this->mTitle
->getPartialURL();
1738 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1739 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1740 case MAG_CURRENTDAYNAME
:
1741 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1742 case MAG_CURRENTYEAR
:
1743 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1744 case MAG_CURRENTTIME
:
1745 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1746 case MAG_NUMBEROFARTICLES
:
1747 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1758 * initialise the magic variables (like CURRENTMONTHNAME)
1762 function initialiseVariables() {
1763 $fname = 'Parser::initialiseVariables';
1764 wfProfileIn( $fname );
1765 global $wgVariableIDs;
1766 $this->mVariables
= array();
1767 foreach ( $wgVariableIDs as $id ) {
1768 $mw =& MagicWord
::get( $id );
1769 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1771 wfProfileOut( $fname );
1775 * Replace magic variables, templates, and template arguments
1776 * with the appropriate text. Templates are substituted recursively,
1777 * taking care to avoid infinite loops.
1779 * Note that the substitution depends on value of $mOutputType:
1780 * OT_WIKI: only {{subst:}} templates
1781 * OT_MSG: only magic variables
1782 * OT_HTML: all templates and magic variables
1784 * @param string $tex The text to transform
1785 * @param array $args Key-value pairs representing template parameters to substitute
1788 function replaceVariables( $text, $args = array() ) {
1789 global $wgLang, $wgScript, $wgArticlePath;
1791 # Prevent too big inclusions
1792 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1796 $fname = 'Parser::replaceVariables';
1797 wfProfileIn( $fname );
1799 $titleChars = Title
::legalChars();
1801 # This function is called recursively. To keep track of arguments we need a stack:
1802 array_push( $this->mArgStack
, $args );
1804 # Variable substitution
1805 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1807 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1808 # Argument substitution
1809 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1811 # Template substitution
1812 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1813 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1815 array_pop( $this->mArgStack
);
1817 wfProfileOut( $fname );
1822 * Replace magic variables
1825 function variableSubstitution( $matches ) {
1826 if ( !$this->mVariables
) {
1827 $this->initialiseVariables();
1830 if ( $this->mOutputType
== OT_WIKI
) {
1831 # Do only magic variables prefixed by SUBST
1832 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1833 if (!$mwSubst->matchStartAndRemove( $matches[1] ))
1835 # Note that if we don't substitute the variable below,
1836 # we don't remove the {{subst:}} magic word, in case
1837 # it is a template rather than a magic variable.
1839 if ( !$skip && array_key_exists( $matches[1], $this->mVariables
) ) {
1840 $text = $this->mVariables
[$matches[1]];
1841 $this->mOutput
->mContainsOldMagic
= true;
1843 $text = $matches[0];
1848 # Split template arguments
1849 function getTemplateArgs( $argsString ) {
1850 if ( $argsString === '' ) {
1854 $args = explode( '|', substr( $argsString, 1 ) );
1856 # If any of the arguments contains a '[[' but no ']]', it needs to be
1857 # merged with the next arg because the '|' character between belongs
1858 # to the link syntax and not the template parameter syntax.
1859 $argc = count($args);
1861 for ( $i = 0; $i < $argc-1; $i++
) {
1862 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1863 $args[$i] .= '|'.$args[$i+
1];
1864 array_splice($args, $i+
1, 1);
1874 * Return the text of a template, after recursively
1875 * replacing any variables or templates within the template.
1877 * @param array $matches The parts of the template
1878 * $matches[1]: the title, i.e. the part before the |
1879 * $matches[2]: the parameters (including a leading |), if any
1880 * @return string the text of the template
1883 function braceSubstitution( $matches ) {
1884 global $wgLinkCache, $wgContLang;
1885 $fname = 'Parser::braceSubstitution';
1892 # Need to know if the template comes at the start of a line,
1893 # to treat the beginning of the template like the beginning
1894 # of a line for tables and block-level elements.
1895 $linestart = $matches[1];
1897 # $part1 is the bit before the first |, and must contain only title characters
1898 # $args is a list of arguments, starting from index 0, not including $part1
1900 $part1 = $matches[2];
1901 # If the third subpattern matched anything, it will start with |
1903 $args = $this->getTemplateArgs($matches[3]);
1904 $argc = count( $args );
1906 # Don't parse {{{}}} because that's only for template arguments
1907 if ( $linestart === '{' ) {
1908 $text = $matches[0];
1915 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1916 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1917 # One of two possibilities is true:
1918 # 1) Found SUBST but not in the PST phase
1919 # 2) Didn't find SUBST and in the PST phase
1920 # In either case, return without further processing
1921 $text = $matches[0];
1927 # MSG, MSGNW and INT
1930 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1931 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1934 # Remove obsolete MSG:
1935 $mwMsg =& MagicWord
::get( MAG_MSG
);
1936 $mwMsg->matchStartAndRemove( $part1 );
1939 # Check if it is an internal message
1940 $mwInt =& MagicWord
::get( MAG_INT
);
1941 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1942 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1943 $text = $linestart . wfMsgReal( $part1, $args, true );
1951 # Check for NS: (namespace expansion)
1952 $mwNs = MagicWord
::get( MAG_NS
);
1953 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1954 if ( intval( $part1 ) ) {
1955 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1958 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1959 if ( !is_null( $index ) ) {
1960 $text = $linestart . $wgContLang->getNsText( $index );
1967 # LOCALURL and LOCALURLE
1969 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1970 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1972 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1973 $func = 'getLocalURL';
1974 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1975 $func = 'escapeLocalURL';
1980 if ( $func !== '' ) {
1981 $title = Title
::newFromText( $part1 );
1982 if ( !is_null( $title ) ) {
1984 $text = $linestart . $title->$func( $args[0] );
1986 $text = $linestart . $title->$func();
1994 if ( !$found && $argc == 1 ) {
1995 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
1996 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1997 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2002 # Template table test
2004 # Did we encounter this template already? If yes, it is in the cache
2005 # and we need to check for loops.
2006 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2007 # set $text to cached message.
2008 $text = $linestart . $this->mTemplates
[$part1];
2011 # Infinite loop test
2012 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2015 $text .= '<!-- WARNING: template loop detected -->';
2019 # Load from database
2020 $itcamefromthedatabase = false;
2023 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2024 if ($subpage !== '') {
2025 $ns = $this->mTitle
->getNamespace();
2027 $title = Title
::newFromText( $part1, $ns );
2028 if ( !is_null( $title ) && !$title->isExternal() ) {
2029 # Check for excessive inclusion
2030 $dbk = $title->getPrefixedDBkey();
2031 if ( $this->incrementIncludeCount( $dbk ) ) {
2032 # This should never be reached.
2033 $article = new Article( $title );
2034 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2035 if ( $articleContent !== false ) {
2037 $text = $linestart . $articleContent;
2038 $itcamefromthedatabase = true;
2042 # If the title is valid but undisplayable, make a link to it
2043 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2044 $text = $linestart . '[['.$title->getPrefixedText().']]';
2048 # Template cache array insertion
2049 $this->mTemplates
[$part1] = $text;
2053 # Recursive parsing, escaping and link table handling
2054 # Only for HTML output
2055 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2056 $text = wfEscapeWikiText( $text );
2057 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2058 # Clean up argument array
2059 $assocArgs = array();
2061 foreach( $args as $arg ) {
2062 $eqpos = strpos( $arg, '=' );
2063 if ( $eqpos === false ) {
2064 $assocArgs[$index++
] = $arg;
2066 $name = trim( substr( $arg, 0, $eqpos ) );
2067 $value = trim( substr( $arg, $eqpos+
1 ) );
2068 if ( $value === false ) {
2071 if ( $name !== false ) {
2072 $assocArgs[$name] = $value;
2077 # Add a new element to the templace recursion path
2078 $this->mTemplatePath
[$part1] = 1;
2080 $text = $this->strip( $text, $this->mStripState
);
2081 $text = $this->removeHTMLtags( $text );
2082 $text = $this->replaceVariables( $text, $assocArgs );
2084 # Resume the link cache and register the inclusion as a link
2085 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2086 $wgLinkCache->addLinkObj( $title );
2089 # If the template begins with a table or block-level
2090 # element, it should be treated as beginning a new line.
2091 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2092 $text = "\n" . $text;
2096 # Empties the template path
2097 $this->mTemplatePath
= array();
2101 # replace ==section headers==
2102 # XXX this needs to go away once we have a better parser.
2103 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2104 if( !is_null( $title ) )
2105 $encodedname = base64_encode($title->getPrefixedDBkey());
2107 $encodedname = base64_encode("");
2108 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2109 PREG_SPLIT_DELIM_CAPTURE
);
2112 for( $i = 0; $i < count($m); $i +
= 2 ) {
2114 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2116 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2120 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2121 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2122 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2129 # Empties the template path
2130 $this->mTemplatePath
= array();
2140 * Triple brace replacement -- used for template arguments
2143 function argSubstitution( $matches ) {
2144 $arg = trim( $matches[1] );
2145 $text = $matches[0];
2146 $inputArgs = end( $this->mArgStack
);
2148 if ( array_key_exists( $arg, $inputArgs ) ) {
2149 $text = $inputArgs[$arg];
2156 * Returns true if the function is allowed to include this entity
2159 function incrementIncludeCount( $dbk ) {
2160 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2161 $this->mIncludeCount
[$dbk] = 0;
2163 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2172 * Cleans up HTML, removes dangerous tags and attributes, and
2173 * removes HTML comments
2176 function removeHTMLtags( $text ) {
2177 global $wgUseTidy, $wgUserHtml;
2178 $fname = 'Parser::removeHTMLtags';
2179 wfProfileIn( $fname );
2182 $htmlpairs = array( # Tags that must be closed
2183 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
2184 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
2185 'strike', 'strong', 'tt', 'var', 'div', 'center',
2186 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
2187 'ruby', 'rt' , 'rb' , 'rp', 'p'
2189 $htmlsingle = array(
2190 'br', 'hr', 'li', 'dt', 'dd'
2192 $htmlnest = array( # Tags that can be nested--??
2193 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
2194 'dl', 'font', 'big', 'small', 'sub', 'sup'
2196 $tabletags = array( # Can only appear inside table
2200 $htmlpairs = array();
2201 $htmlsingle = array();
2202 $htmlnest = array();
2203 $tabletags = array();
2206 $htmlsingle = array_merge( $tabletags, $htmlsingle );
2207 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
2209 $htmlattrs = $this->getHTMLattrs () ;
2211 # Remove HTML comments
2212 $text = $this->removeHTMLcomments( $text );
2214 $bits = explode( '<', $text );
2215 $text = array_shift( $bits );
2217 $tagstack = array(); $tablestack = array();
2218 foreach ( $bits as $x ) {
2219 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
2220 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2222 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2223 error_reporting( $prev );
2226 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2230 if ( ! in_array( $t, $htmlsingle ) &&
2231 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
2232 @array_push
( $tagstack, $ot );
2235 if ( $t == 'table' ) {
2236 $tagstack = array_pop( $tablestack );
2241 # Keep track for later
2242 if ( in_array( $t, $tabletags ) &&
2243 ! in_array( 'table', $tagstack ) ) {
2245 } else if ( in_array( $t, $tagstack ) &&
2246 ! in_array ( $t , $htmlnest ) ) {
2248 } else if ( ! in_array( $t, $htmlsingle ) ) {
2249 if ( $t == 'table' ) {
2250 array_push( $tablestack, $tagstack );
2251 $tagstack = array();
2253 array_push( $tagstack, $t );
2255 # Strip non-approved attributes from the tag
2256 $newparams = $this->fixTagAttributes($params);
2260 $rest = str_replace( '>', '>', $rest );
2261 $text .= "<$slash$t $newparams$brace$rest";
2265 $text .= '<' . str_replace( '>', '>', $x);
2267 # Close off any remaining tags
2268 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2270 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2273 # this might be possible using tidy itself
2274 foreach ( $bits as $x ) {
2275 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2277 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2278 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2279 $newparams = $this->fixTagAttributes($params);
2280 $rest = str_replace( '>', '>', $rest );
2281 $text .= "<$slash$t $newparams$brace$rest";
2283 $text .= '<' . str_replace( '>', '>', $x);
2287 wfProfileOut( $fname );
2292 * Remove '<!--', '-->', and everything between.
2293 * To avoid leaving blank lines, when a comment is both preceded
2294 * and followed by a newline (ignoring spaces), trim leading and
2295 * trailing spaces and one of the newlines.
2299 function removeHTMLcomments( $text ) {
2300 $fname='Parser::removeHTMLcomments';
2301 wfProfileIn( $fname );
2302 while (($start = strpos($text, '<!--')) !== false) {
2303 $end = strpos($text, '-->', $start +
4);
2304 if ($end === false) {
2305 # Unterminated comment; bail out
2311 # Trim space and newline if the comment is both
2312 # preceded and followed by a newline
2313 $spaceStart = max($start - 1, 0);
2314 $spaceLen = $end - $spaceStart;
2315 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
2319 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
2321 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
2322 # Remove the comment, leading and trailing
2323 # spaces, and leave only one newline.
2324 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
2327 # Remove just the comment.
2328 $text = substr_replace($text, '', $start, $end - $start);
2331 wfProfileOut( $fname );
2336 * This function accomplishes several tasks:
2337 * 1) Auto-number headings if that option is enabled
2338 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2339 * 3) Add a Table of contents on the top for users who have enabled the option
2340 * 4) Auto-anchor headings
2342 * It loops through all headlines, collects the necessary data, then splits up the
2343 * string and re-inserts the newly formatted headlines.
2346 /* private */ function formatHeadings( $text, $isMain=true ) {
2347 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders;
2349 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2350 $doShowToc = $this->mOptions
->getShowToc();
2351 $forceTocHere = false;
2352 if( !$this->mTitle
->userCanEdit() ) {
2354 $rightClickHack = 0;
2356 $showEditLink = $this->mOptions
->getEditSection();
2357 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
2360 # Inhibit editsection links if requested in the page
2361 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2362 if( $esw->matchAndRemove( $text ) ) {
2365 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2367 $mw =& MagicWord
::get( MAG_NOTOC
);
2368 if( $mw->matchAndRemove( $text ) ) {
2372 # never add the TOC to the Main Page. This is an entry page that should not
2373 # be more than 1-2 screens large anyway
2374 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
2378 # Get all headlines for numbering them and adding funky stuff like [edit]
2379 # links - this is for later, but we need the number of headlines right now
2380 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
2382 # if there are fewer than 4 headlines in the article, do not show TOC
2383 if( $numMatches < 4 ) {
2387 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2388 # override above conditions and always show TOC at that place
2389 $mw =& MagicWord
::get( MAG_TOC
);
2390 if ($mw->match( $text ) ) {
2392 $forceTocHere = true;
2394 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2395 # override above conditions and always show TOC above first header
2396 $mw =& MagicWord
::get( MAG_FORCETOC
);
2397 if ($mw->matchAndRemove( $text ) ) {
2404 # We need this to perform operations on the HTML
2405 $sk =& $this->mOptions
->getSkin();
2409 $sectionCount = 0; # headlineCount excluding template sections
2411 # Ugh .. the TOC should have neat indentation levels which can be
2412 # passed to the skin functions. These are determined here
2417 $sublevelCount = array();
2420 foreach( $matches[3] as $headline ) {
2422 $templatetitle = "";
2423 $templatesection = 0;
2425 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2427 $templatetitle = base64_decode($mat[1]);
2428 $templatesection = 1 +
(int)base64_decode($mat[2]);
2429 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2434 $prevlevel = $level;
2436 $level = $matches[1][$headlineCount];
2437 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
2438 # reset when we enter a new level
2439 $sublevelCount[$level] = 0;
2440 $toc .= $sk->tocIndent( $level - $prevlevel );
2441 $toclevel +
= $level - $prevlevel;
2443 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
2444 # reset when we step back a level
2445 $sublevelCount[$level+
1]=0;
2446 $toc .= $sk->tocUnindent( $prevlevel - $level );
2447 $toclevel -= $prevlevel - $level;
2449 # count number of headlines for each level
2450 @$sublevelCount[$level]++
;
2451 if( $doNumberHeadings ||
$doShowToc ) {
2453 for( $i = 1; $i <= $level; $i++
) {
2454 if( !empty( $sublevelCount[$i] ) ) {
2458 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2464 # The canonized header is a version of the header text safe to use for links
2465 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2466 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2467 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
2469 # Remove link placeholders by the link text.
2470 # <!--LINK number-->
2472 # link text with suffix
2473 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2474 "\$wgLinkHolders['texts'][\$1]",
2475 $canonized_headline );
2478 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2479 $tocline = trim( $canonized_headline );
2480 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2481 $replacearray = array(
2485 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2486 $refer[$headlineCount] = $canonized_headline;
2488 # count how many in assoc. array so we can track dupes in anchors
2489 @$refers[$canonized_headline]++
;
2490 $refcount[$headlineCount]=$refers[$canonized_headline];
2492 # Prepend the number to the heading text
2494 if( $doNumberHeadings ||
$doShowToc ) {
2495 $tocline = $numbering . ' ' . $tocline;
2497 # Don't number the heading if it is the only one (looks silly)
2498 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2499 # the two are different if the line contains a link
2500 $headline=$numbering . ' ' . $headline;
2504 # Create the anchor for linking from the TOC to the section
2505 $anchor = $canonized_headline;
2506 if($refcount[$headlineCount] > 1 ) {
2507 $anchor .= '_' . $refcount[$headlineCount];
2509 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2510 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2512 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2513 if ( empty( $head[$headlineCount] ) ) {
2514 $head[$headlineCount] = '';
2517 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2519 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2522 # Add the edit section span
2523 if( $rightClickHack ) {
2525 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2527 $headline = $sk->editSectionScript($this->mTitle
, $sectionCount+
1,$headline);
2530 # give headline the correct <h#> tag
2531 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2539 $toclines = $headlineCount;
2540 $toc .= $sk->tocUnindent( $toclevel );
2541 $toc = $sk->tocTable( $toc );
2544 # split up and insert constructed headlines
2546 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2549 foreach( $blocks as $block ) {
2550 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2551 # This is the [edit] link that appears for the top block of text when
2552 # section editing is enabled
2554 # Disabled because it broke block formatting
2555 # For example, a bullet point in the top line
2556 # $full .= $sk->editSectionLink(0);
2559 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2560 # Top anchor now in skin
2564 if( !empty( $head[$i] ) ) {
2570 $mw =& MagicWord
::get( MAG_TOC
);
2571 return $mw->replace( $toc, $full );
2578 * Return an HTML link for the "ISBN 123456" text
2581 function magicISBN( $text ) {
2583 $fname = 'Parser::magicISBN';
2584 wfProfileIn( $fname );
2586 $a = split( 'ISBN ', ' '.$text );
2587 if ( count ( $a ) < 2 ) {
2588 wfProfileOut( $fname );
2591 $text = substr( array_shift( $a ), 1);
2592 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2594 foreach ( $a as $x ) {
2595 $isbn = $blank = '' ;
2596 while ( ' ' == $x{0} ) {
2598 $x = substr( $x, 1 );
2600 if ( $x == '' ) { # blank isbn
2601 $text .= "ISBN $blank";
2604 while ( strstr( $valid, $x{0} ) != false ) {
2606 $x = substr( $x, 1 );
2608 $num = str_replace( '-', '', $isbn );
2609 $num = str_replace( ' ', '', $num );
2612 $text .= "ISBN $blank$x";
2614 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2615 $text .= '<a href="' .
2616 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2617 "\" class=\"internal\">ISBN $isbn</a>";
2621 wfProfileOut( $fname );
2626 * Return an HTML link for the "GEO ..." text
2629 function magicGEO( $text ) {
2630 global $wgLang, $wgUseGeoMode;
2631 $fname = 'Parser::magicGEO';
2632 wfProfileIn( $fname );
2634 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2635 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2636 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2637 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2638 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2639 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2641 $a = split( 'GEO ', ' '.$text );
2642 if ( count ( $a ) < 2 ) {
2643 wfProfileOut( $fname );
2646 $text = substr( array_shift( $a ), 1);
2647 $valid = '0123456789.+-:';
2649 foreach ( $a as $x ) {
2650 $geo = $blank = '' ;
2651 while ( ' ' == $x{0} ) {
2653 $x = substr( $x, 1 );
2655 while ( strstr( $valid, $x{0} ) != false ) {
2657 $x = substr( $x, 1 );
2659 $num = str_replace( '+', '', $geo );
2660 $num = str_replace( ' ', '', $num );
2662 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2663 $text .= "GEO $blank$x";
2665 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2666 $text .= '<a href="' .
2667 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2668 "\" class=\"internal\">GEO $geo</a>";
2672 wfProfileOut( $fname );
2677 * Return an HTML link for the "RFC 1234" text
2679 * @param string $text text to be processed
2681 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2684 $valid = '0123456789';
2687 $a = split( $keyword, ' '.$text );
2688 if ( count ( $a ) < 2 ) {
2691 $text = substr( array_shift( $a ), 1);
2693 /* Check if keyword is preceed by [[.
2694 * This test is made here cause of the array_shift above
2695 * that prevent the test to be done in the foreach.
2697 if ( substr( $text, -2 ) == '[[' ) {
2701 foreach ( $a as $x ) {
2702 /* token might be empty if we have RFC RFC 1234 */
2710 /** remove and save whitespaces in $blank */
2711 while ( $x{0} == ' ' ) {
2713 $x = substr( $x, 1 );
2716 /** remove and save the rfc number in $id */
2717 while ( strstr( $valid, $x{0} ) != false ) {
2719 $x = substr( $x, 1 );
2723 /* call back stripped spaces*/
2724 $text .= $keyword.$blank.$x;
2725 } elseif( $internal ) {
2727 $text .= $keyword.$id.$x;
2729 /* build the external link*/
2730 $url = wfmsg( $urlmsg );
2731 $url = str_replace( '$1', $id, $url);
2732 $sk =& $this->mOptions
->getSkin();
2733 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2734 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2737 /* Check if the next RFC keyword is preceed by [[ */
2738 $internal = ( substr($x,-2) == '[[' );
2744 * Transform wiki markup when saving a page by doing \r\n -> \n
2745 * conversion, substitting signatures, {{subst:}} templates, etc.
2747 * @param string $text the text to transform
2748 * @param Title &$title the Title object for the current article
2749 * @param User &$user the User object describing the current user
2750 * @param ParserOptions $options parsing options
2751 * @param bool $clearState whether to clear the parser state first
2752 * @return string the altered wiki markup
2755 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2756 $this->mOptions
= $options;
2757 $this->mTitle
=& $title;
2758 $this->mOutputType
= OT_WIKI
;
2760 if ( $clearState ) {
2761 $this->clearState();
2764 $stripState = false;
2768 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2769 $text = $this->strip( $text, $stripState, false );
2770 $text = $this->pstPass2( $text, $user );
2771 $text = $this->unstrip( $text, $stripState );
2772 $text = $this->unstripNoWiki( $text, $stripState );
2777 * Pre-save transform helper function
2780 function pstPass2( $text, &$user ) {
2781 global $wgLang, $wgContLang, $wgLocaltimezone;
2783 # Variable replacement
2784 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2785 $text = $this->replaceVariables( $text );
2789 $n = $user->getName();
2790 $k = $user->getOption( 'nickname' );
2791 if ( '' == $k ) { $k = $n; }
2792 if ( isset( $wgLocaltimezone ) ) {
2793 $oldtz = getenv( 'TZ' );
2794 putenv( 'TZ='.$wgLocaltimezone );
2796 /* Note: this is an ugly timezone hack for the European wikis */
2797 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2798 ' (' . date( 'T' ) . ')';
2799 if ( isset( $wgLocaltimezone ) ) {
2800 putenv( 'TZ='.$oldtzs );
2803 $text = preg_replace( '/~~~~~~/', $d, $text );
2804 $text = preg_replace( '/~~~~/', '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]] $d", $text );
2805 $text = preg_replace( '/~~~/', '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]", $text );
2807 # Context links: [[|name]] and [[name (context)|]]
2809 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2810 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2811 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2812 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2814 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2815 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2816 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2817 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2819 $t = $this->mTitle
->getText();
2820 if ( preg_match( $conpat, $t, $m ) ) {
2823 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2824 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2825 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2827 if ( '' == $context ) {
2828 $text = preg_replace( $p2, '[[\\1]]', $text );
2830 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2833 # Trim trailing whitespace
2834 # MAG_END (__END__) tag allows for trailing
2835 # whitespace to be deliberately included
2836 $text = rtrim( $text );
2837 $mw =& MagicWord
::get( MAG_END
);
2838 $mw->matchAndRemove( $text );
2844 * Set up some variables which are usually set up in parse()
2845 * so that an external function can call some class members with confidence
2848 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2849 $this->mTitle
=& $title;
2850 $this->mOptions
= $options;
2851 $this->mOutputType
= $outputType;
2852 if ( $clearState ) {
2853 $this->clearState();
2858 * Transform a MediaWiki message by replacing magic variables.
2860 * @param string $text the text to transform
2861 * @param ParserOptions $options options
2862 * @return string the text with variables substituted
2865 function transformMsg( $text, $options ) {
2867 static $executing = false;
2869 # Guard against infinite recursion
2875 $this->mTitle
= $wgTitle;
2876 $this->mOptions
= $options;
2877 $this->mOutputType
= OT_MSG
;
2878 $this->clearState();
2879 $text = $this->replaceVariables( $text );
2886 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2887 * Callback will be called with the text within
2888 * Transform and return the text within
2891 function setHook( $tag, $callback ) {
2892 $oldVal = @$this->mTagHooks
[$tag];
2893 $this->mTagHooks
[$tag] = $callback;
2898 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2899 * Placeholders created in Skin::makeLinkObj()
2900 * Returns an array of links found, indexed by PDBK:
2904 * $options is a bit field, RLH_FOR_UPDATE to select for update
2906 function replaceLinkHolders( &$text, $options = 0 ) {
2907 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2908 global $wgInterwikiLinkHolders;
2909 global $outputReplace;
2911 if ( $wgUseOldExistenceCheck ) {
2915 $fname = 'Parser::replaceLinkHolders';
2916 wfProfileIn( $fname );
2921 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2922 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2923 wfProfileIn( $fname.'-check' );
2924 $dbr =& wfGetDB( DB_SLAVE
);
2925 $cur = $dbr->tableName( 'cur' );
2926 $sk = $wgUser->getSkin();
2927 $threshold = $wgUser->getOption('stubthreshold');
2930 asort( $wgLinkHolders['namespaces'] );
2934 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2936 $title = $wgLinkHolders['titles'][$key];
2938 # Skip invalid entries.
2939 # Result will be ugly, but prevents crash.
2940 if ( is_null( $title ) ) {
2943 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2945 # Check if it's in the link cache already
2946 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2947 $colours[$pdbk] = 1;
2948 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2949 $colours[$pdbk] = 0;
2951 # Not in the link cache, add it to the query
2952 if ( !isset( $current ) ) {
2954 $query = "SELECT cur_id, cur_namespace, cur_title";
2955 if ( $threshold > 0 ) {
2956 $query .= ", LENGTH(cur_text) AS cur_len, cur_is_redirect";
2958 $query .= " FROM $cur WHERE (cur_namespace=$val AND cur_title IN(";
2959 } elseif ( $current != $val ) {
2961 $query .= ")) OR (cur_namespace=$val AND cur_title IN(";
2966 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2971 if ( $options & RLH_FOR_UPDATE
) {
2972 $query .= ' FOR UPDATE';
2975 $res = $dbr->query( $query, $fname );
2977 # Fetch data and form into an associative array
2978 # non-existent = broken
2981 while ( $s = $dbr->fetchObject($res) ) {
2982 $title = Title
::makeTitle( $s->cur_namespace
, $s->cur_title
);
2983 $pdbk = $title->getPrefixedDBkey();
2984 $wgLinkCache->addGoodLink( $s->cur_id
, $pdbk );
2986 if ( $threshold > 0 ) {
2987 $size = $s->cur_len
;
2988 if ( $s->cur_is_redirect ||
$s->cur_namespace
!= 0 ||
$length < $threshold ) {
2989 $colours[$pdbk] = 1;
2991 $colours[$pdbk] = 2;
2994 $colours[$pdbk] = 1;
2998 wfProfileOut( $fname.'-check' );
3000 # Construct search and replace arrays
3001 wfProfileIn( $fname.'-construct' );
3002 $outputReplace = array();
3003 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
3004 $pdbk = $pdbks[$key];
3005 $searchkey = '<!--LINK '.$key.'-->';
3006 $title = $wgLinkHolders['titles'][$key];
3007 if ( empty( $colours[$pdbk] ) ) {
3008 $wgLinkCache->addBadLink( $pdbk );
3009 $colours[$pdbk] = 0;
3010 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3011 $wgLinkHolders['texts'][$key],
3012 $wgLinkHolders['queries'][$key] );
3013 } elseif ( $colours[$pdbk] == 1 ) {
3014 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3015 $wgLinkHolders['texts'][$key],
3016 $wgLinkHolders['queries'][$key] );
3017 } elseif ( $colours[$pdbk] == 2 ) {
3018 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3019 $wgLinkHolders['texts'][$key],
3020 $wgLinkHolders['queries'][$key] );
3023 wfProfileOut( $fname.'-construct' );
3026 wfProfileIn( $fname.'-replace' );
3028 $text = preg_replace_callback(
3029 '/(<!--LINK .*?-->)/',
3030 "outputReplaceMatches",
3032 wfProfileOut( $fname.'-replace' );
3035 if ( !empty( $wgInterwikiLinkHolders ) ) {
3036 wfProfileIn( $fname.'-interwiki' );
3037 $outputReplace = $wgInterwikiLinkHolders;
3038 $text = preg_replace_callback(
3039 '/<!--IWLINK (.*?)-->/',
3040 "outputReplaceMatches",
3042 wfProfileOut( $fname.'-interwiki' );
3045 wfProfileOut( $fname );
3050 * Renders an image gallery from a text with one line per image.
3051 * text labels may be given by using |-style alternative text. E.g.
3052 * Image:one.jpg|The number "1"
3053 * Image:tree.jpg|A tree
3054 * given as text will return the HTML of a gallery with two images,
3055 * labeled 'The number "1"' and
3058 function renderImageGallery( $text ) {
3059 global $wgLinkCache;
3060 $ig = new ImageGallery();
3061 $ig->setShowBytes( false );
3062 $ig->setShowFilename( false );
3063 $lines = explode( "\n", $text );
3065 foreach ( $lines as $line ) {
3066 # match lines like these:
3067 # Image:someimage.jpg|This is some image
3068 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3070 if ( count( $matches ) == 0 ) {
3073 $nt = Title
::newFromURL( $matches[1] );
3074 if ( isset( $matches[3] ) ) {
3075 $label = $matches[3];
3079 $ig->add( Image
::newFromTitle( $nt ), $label );
3080 $wgLinkCache->addImageLinkObj( $nt );
3082 return $ig->toHTML();
3088 * @package MediaWiki
3092 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3093 var $mCacheTime; # Used in ParserCache
3094 var $mVersion; # Compatibility check
3096 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3097 $containsOldMagic = false )
3099 $this->mText
= $text;
3100 $this->mLanguageLinks
= $languageLinks;
3101 $this->mCategoryLinks
= $categoryLinks;
3102 $this->mContainsOldMagic
= $containsOldMagic;
3103 $this->mCacheTime
= '';
3104 $this->mVersion
= MW_PARSER_VERSION
;
3107 function getText() { return $this->mText
; }
3108 function getLanguageLinks() { return $this->mLanguageLinks
; }
3109 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3110 function getCacheTime() { return $this->mCacheTime
; }
3111 function containsOldMagic() { return $this->mContainsOldMagic
; }
3112 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3113 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3114 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3115 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3116 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3117 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3119 function merge( $other ) {
3120 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3121 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3122 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3126 * Return true if this cached output object predates the global or
3127 * per-article cache invalidation timestamps, or if it comes from
3128 * an incompatible older version.
3130 * @param string $touched the affected article's last touched timestamp
3134 function expired( $touched ) {
3135 global $wgCacheEpoch;
3136 return $this->getCacheTime() <= $touched ||
3137 $this->getCacheTime() <= $wgCacheEpoch ||
3138 !isset( $this->mVersion
) ||
3139 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3144 * Set options of the Parser
3146 * @package MediaWiki
3150 # All variables are private
3151 var $mUseTeX; # Use texvc to expand <math> tags
3152 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
3153 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3154 var $mAllowExternalImages; # Allow external images inline
3155 var $mSkin; # Reference to the preferred skin
3156 var $mDateFormat; # Date format index
3157 var $mEditSection; # Create "edit section" links
3158 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
3159 var $mNumberHeadings; # Automatically number headings
3160 var $mShowToc; # Show table of contents
3162 function getUseTeX() { return $this->mUseTeX
; }
3163 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3164 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3165 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3166 function getSkin() { return $this->mSkin
; }
3167 function getDateFormat() { return $this->mDateFormat
; }
3168 function getEditSection() { return $this->mEditSection
; }
3169 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
3170 function getNumberHeadings() { return $this->mNumberHeadings
; }
3171 function getShowToc() { return $this->mShowToc
; }
3173 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3174 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3175 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3176 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3177 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3178 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3179 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
3180 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3181 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
3183 function setSkin( &$x ) { $this->mSkin
=& $x; }
3185 # Get parser options
3186 /* static */ function newFromUser( &$user ) {
3187 $popts = new ParserOptions
;
3188 $popts->initialiseFromUser( $user );
3193 function initialiseFromUser( &$userInput ) {
3194 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3195 $fname = 'ParserOptions::initialiseFromUser';
3196 wfProfileIn( $fname );
3197 if ( !$userInput ) {
3199 $user->setLoaded( true );
3201 $user =& $userInput;
3204 $this->mUseTeX
= $wgUseTeX;
3205 $this->mUseDynamicDates
= $wgUseDynamicDates;
3206 $this->mInterwikiMagic
= $wgInterwikiMagic;
3207 $this->mAllowExternalImages
= $wgAllowExternalImages;
3208 wfProfileIn( $fname.'-skin' );
3209 $this->mSkin
=& $user->getSkin();
3210 wfProfileOut( $fname.'-skin' );
3211 $this->mDateFormat
= $user->getOption( 'date' );
3212 $this->mEditSection
= $user->getOption( 'editsection' );
3213 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
3214 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3215 $this->mShowToc
= $user->getOption( 'showtoc' );
3216 wfProfileOut( $fname );
3223 * Callback function used by Parser::replaceLinkHolders()
3224 * to substitute link placeholders.
3226 function &outputReplaceMatches( $matches ) {
3227 global $outputReplace;
3228 return $outputReplace[$matches[1]];
3232 * Return the total number of articles
3234 function wfNumberOfArticles() {
3235 global $wgNumberOfArticles;
3238 return $wgNumberOfArticles;
3242 * Get various statistics from the database
3245 function wfLoadSiteStats() {
3246 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3247 $fname = 'wfLoadSiteStats';
3249 if ( -1 != $wgNumberOfArticles ) return;
3250 $dbr =& wfGetDB( DB_SLAVE
);
3251 $s = $dbr->selectRow( 'site_stats',
3252 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3253 array( 'ss_row_id' => 1 ), $fname
3256 if ( $s === false ) {
3259 $wgTotalViews = $s->ss_total_views
;
3260 $wgTotalEdits = $s->ss_total_edits
;
3261 $wgNumberOfArticles = $s->ss_good_articles
;
3265 function wfEscapeHTMLTagsOnly( $in ) {
3267 array( '"', '>', '<' ),
3268 array( '"', '>', '<' ),