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 $bits = preg_split( '/((?:'.URL_PROTOCOLS
.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1044 $s = array_shift( $bits );
1047 $sk =& $this->mOptions
->getSkin();
1049 while ( $i < count( $bits ) ){
1050 $protocol = $bits[$i++
];
1051 $remainder = $bits[$i++
];
1053 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1054 # Found some characters after the protocol that look promising
1055 $url = $protocol . $m[1];
1058 # The characters '<' and '>' (which were escaped by
1059 # removeHTMLtags()) should not be included in
1060 # URLs, per RFC 2396.
1061 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1062 $trail = substr($url, $m2[0][1]) . $trail;
1063 $url = substr($url, 0, $m2[0][1]);
1066 # Move trailing punctuation to $trail
1068 # If there is no left bracket, then consider right brackets fair game too
1069 if ( strpos( $url, '(' ) === false ) {
1073 $numSepChars = strspn( strrev( $url ), $sep );
1074 if ( $numSepChars ) {
1075 $trail = substr( $url, -$numSepChars ) . $trail;
1076 $url = substr( $url, 0, -$numSepChars );
1079 # Replace & from obsolete syntax with &.
1080 # All HTML entities will be escaped by makeExternalLink()
1081 # or maybeMakeImageLink()
1082 $url = str_replace( '&', '&', $url );
1084 # Is this an external image?
1085 $text = $this->maybeMakeImageLink( $url );
1086 if ( $text === false ) {
1087 # Not an image, make a link
1088 $text = $sk->makeExternalLink( $url, $url );
1090 $s .= $text . $trail;
1092 $s .= $protocol . $remainder;
1099 * make an image if it's allowed
1102 function maybeMakeImageLink( $url ) {
1103 $sk =& $this->mOptions
->getSkin();
1105 if ( $this->mOptions
->getAllowExternalImages() ) {
1106 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1108 $text = $sk->makeImage( htmlspecialchars( $url ) );
1115 * Process [[ ]] wikilinks
1120 function replaceInternalLinks( $s ) {
1121 global $wgLang, $wgContLang, $wgLinkCache;
1122 global $wgDisableLangConversion;
1123 static $fname = 'Parser::replaceInternalLinks' ;
1125 wfProfileIn( $fname );
1127 wfProfileIn( $fname.'-setup' );
1129 # the % is needed to support urlencoded titles as well
1130 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1132 $sk =& $this->mOptions
->getSkin();
1133 global $wgUseOldExistenceCheck;
1134 # "Post-parse link colour check" works only on wiki text since it's now
1135 # in Parser. Enable it, then disable it when we're done.
1136 $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
1138 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1140 #split the entire text string on occurences of [[
1141 $a = explode( '[[', ' ' . $s );
1142 #get the first element (all text up to first [[), and remove the space we added
1143 $s = array_shift( $a );
1144 $s = substr( $s, 1 );
1146 # Match a link having the form [[namespace:link|alternate]]trail
1148 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1149 # Match cases where there is no "]]", which might still be images
1150 static $e1_img = FALSE;
1151 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1152 # Match the end of a line for a word that's not followed by whitespace,
1153 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1154 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1156 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1158 $nottalk = !Namespace::isTalk( $this->mTitle
->getNamespace() );
1160 if ( $useLinkPrefixExtension ) {
1161 if ( preg_match( $e2, $s, $m ) ) {
1162 $first_prefix = $m[2];
1165 $first_prefix = false;
1171 $selflink = $this->mTitle
->getPrefixedText();
1172 wfProfileOut( $fname.'-setup' );
1174 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1175 # Loop for each link
1176 for ($k = 0; isset( $a[$k] ); $k++
) {
1178 if ( $useLinkPrefixExtension ) {
1179 wfProfileIn( $fname.'-prefixhandling' );
1180 if ( preg_match( $e2, $s, $m ) ) {
1188 $prefix = $first_prefix;
1189 $first_prefix = false;
1191 wfProfileOut( $fname.'-prefixhandling' );
1194 $might_be_img = false;
1196 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1198 # fix up urlencoded title texts
1199 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1201 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1202 $might_be_img = true;
1204 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1206 } else { # Invalid form; output directly
1207 $s .= $prefix . '[[' . $line ;
1211 # Don't allow internal links to pages containing
1212 # PROTO: where PROTO is a valid URL protocol; these
1213 # should be external links.
1214 if (preg_match('/^((?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1215 $s .= $prefix . '[[' . $line ;
1219 # Make subpage if necessary
1220 $link = $this->maybeDoSubpageLink( $m[1], $text );
1222 $noforce = (substr($m[1], 0, 1) != ':');
1224 # Strip off leading ':'
1225 $link = substr($link, 1);
1228 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1230 $s .= $prefix . '[[' . $line;
1234 #check other language variants of the link
1235 #if the article does not exist
1236 if( $checkVariantLink
1237 && $nt->getArticleID() == 0 ) {
1238 $wgContLang->findVariantLink($link, $nt);
1241 $ns = $nt->getNamespace();
1242 $iw = $nt->getInterWiki();
1244 if ($might_be_img) { # if this is actually an invalid link
1245 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1247 while (isset ($a[$k+
1]) ) {
1248 #look at the next 'line' to see if we can close it there
1249 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1250 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1251 # the first ]] closes the inner link, the second the image
1253 $text .= '[[' . $m[1];
1256 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1257 #if there's exactly one ]] that's fine, we'll keep looking
1258 $text .= '[[' . $m[0];
1260 #if $next_line is invalid too, we need look no further
1261 $text .= '[[' . $next_line;
1266 # we couldn't find the end of this imageLink, so output it raw
1267 #but don't ignore what might be perfectly normal links in the text we've examined
1268 $text = $this->replaceInternalLinks($text);
1269 $s .= $prefix . '[[' . $link . '|' . $text;
1270 # note: no $trail, because without an end, there *is* no trail
1273 } else { #it's not an image, so output it raw
1274 $s .= $prefix . '[[' . $link . '|' . $text;
1275 # note: no $trail, because without an end, there *is* no trail
1280 $wasblank = ( '' == $text );
1281 if( $wasblank ) $text = $link;
1284 # Link not escaped by : , create the various objects
1288 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1289 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1290 $tmp = $prefix . $trail ;
1291 $s .= (trim($tmp) == '')?
'': $tmp;
1295 if ( $ns == NS_IMAGE
) {
1296 wfProfileIn( "$fname-image" );
1298 # recursively parse links inside the image caption
1299 # actually, this will parse them in any other parameters, too,
1300 # but it might be hard to fix that, and it doesn't matter ATM
1301 $text = $this->replaceExternalLinks($text);
1302 $text = $this->replaceInternalLinks($text);
1304 # replace the image with a link-holder so that replaceExternalLinks() can't mess with it
1305 $s .= $prefix . $this->insertStripItem( $sk->makeImageLinkObj( $nt, $text ), $this->mStripState
) . $trail;
1306 $wgLinkCache->addImageLinkObj( $nt );
1308 wfProfileOut( "$fname-image" );
1312 if ( $ns == NS_CATEGORY
) {
1313 wfProfileIn( "$fname-category" );
1314 $t = $nt->getText();
1316 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1317 $pPLC=$sk->postParseLinkColour();
1318 $sk->postParseLinkColour( false );
1319 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1320 $sk->postParseLinkColour( $pPLC );
1321 $wgLinkCache->resume();
1324 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1325 $sortkey = $this->mTitle
->getText();
1327 $sortkey = $this->mTitle
->getPrefixedText();
1332 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1333 $this->mOutput
->addCategoryLink( $t );
1334 $s .= $prefix . $trail ;
1336 wfProfileOut( "$fname-category" );
1341 if( ( $nt->getPrefixedText() === $selflink ) &&
1342 ( $nt->getFragment() === '' ) ) {
1343 # Self-links are handled specially; generally de-link and change to bold.
1344 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1348 # Special and Media are pseudo-namespaces; no pages actually exist in them
1349 if( $ns == NS_MEDIA
) {
1350 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1351 $wgLinkCache->addImageLinkObj( $nt );
1353 } elseif( $ns == NS_SPECIAL
) {
1354 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1357 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1359 $sk->postParseLinkColour( $saveParseColour );
1360 wfProfileOut( $fname );
1365 * Handle link to subpage if necessary
1366 * @param string $target the source of the link
1367 * @param string &$text the link text, modified as necessary
1368 * @return string the full name of the link
1371 function maybeDoSubpageLink($target, &$text) {
1374 # :Foobar -- override special treatment of prefix (images, language links)
1375 # /Foobar -- convert to CurrentPage/Foobar
1376 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1377 global $wgNamespacesWithSubpages;
1379 $fname = 'Parser::maybeDoSubpageLink';
1380 wfProfileIn( $fname );
1381 # Look at the first character
1382 if( $target{0} == '/' ) {
1383 # / at end means we don't want the slash to be shown
1384 if(substr($target,-1,1)=='/') {
1385 $target=substr($target,1,-1);
1388 $noslash=substr($target,1);
1391 # Some namespaces don't allow subpages
1392 if(!empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()])) {
1393 # subpages allowed here
1394 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1395 if( '' === $text ) {
1397 } # this might be changed for ugliness reasons
1399 # no subpage allowed, use standard link
1407 wfProfileOut( $fname );
1412 * Used by doBlockLevels()
1415 /* private */ function closeParagraph() {
1417 if ( '' != $this->mLastSection
) {
1418 $result = '</' . $this->mLastSection
. ">\n";
1420 $this->mInPre
= false;
1421 $this->mLastSection
= '';
1424 # getCommon() returns the length of the longest common substring
1425 # of both arguments, starting at the beginning of both.
1427 /* private */ function getCommon( $st1, $st2 ) {
1428 $fl = strlen( $st1 );
1429 $shorter = strlen( $st2 );
1430 if ( $fl < $shorter ) { $shorter = $fl; }
1432 for ( $i = 0; $i < $shorter; ++
$i ) {
1433 if ( $st1{$i} != $st2{$i} ) { break; }
1437 # These next three functions open, continue, and close the list
1438 # element appropriate to the prefix character passed into them.
1440 /* private */ function openList( $char ) {
1441 $result = $this->closeParagraph();
1443 if ( '*' == $char ) { $result .= '<ul><li>'; }
1444 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1445 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1446 else if ( ';' == $char ) {
1447 $result .= '<dl><dt>';
1448 $this->mDTopen
= true;
1450 else { $result = '<!-- ERR 1 -->'; }
1455 /* private */ function nextItem( $char ) {
1456 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1457 else if ( ':' == $char ||
';' == $char ) {
1459 if ( $this->mDTopen
) { $close = '</dt>'; }
1460 if ( ';' == $char ) {
1461 $this->mDTopen
= true;
1462 return $close . '<dt>';
1464 $this->mDTopen
= false;
1465 return $close . '<dd>';
1468 return '<!-- ERR 2 -->';
1471 /* private */ function closeList( $char ) {
1472 if ( '*' == $char ) { $text = '</li></ul>'; }
1473 else if ( '#' == $char ) { $text = '</li></ol>'; }
1474 else if ( ':' == $char ) {
1475 if ( $this->mDTopen
) {
1476 $this->mDTopen
= false;
1477 $text = '</dt></dl>';
1479 $text = '</dd></dl>';
1482 else { return '<!-- ERR 3 -->'; }
1488 * Make lists from lines starting with ':', '*', '#', etc.
1491 * @return string the lists rendered as HTML
1493 function doBlockLevels( $text, $linestart ) {
1494 $fname = 'Parser::doBlockLevels';
1495 wfProfileIn( $fname );
1497 # Parsing through the text line by line. The main thing
1498 # happening here is handling of block-level elements p, pre,
1499 # and making lists from lines starting with * # : etc.
1501 $textLines = explode( "\n", $text );
1503 $lastPrefix = $output = $lastLine = '';
1504 $this->mDTopen
= $inBlockElem = false;
1506 $paragraphStack = false;
1508 if ( !$linestart ) {
1509 $output .= array_shift( $textLines );
1511 foreach ( $textLines as $oLine ) {
1512 $lastPrefixLength = strlen( $lastPrefix );
1513 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1514 $preOpenMatch = preg_match('/<pre/i', $oLine );
1515 if ( !$this->mInPre
) {
1516 # Multiple prefixes may abut each other for nested lists.
1517 $prefixLength = strspn( $oLine, '*#:;' );
1518 $pref = substr( $oLine, 0, $prefixLength );
1521 $pref2 = str_replace( ';', ':', $pref );
1522 $t = substr( $oLine, $prefixLength );
1523 $this->mInPre
= !empty($preOpenMatch);
1525 # Don't interpret any other prefixes in preformatted text
1527 $pref = $pref2 = '';
1532 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1533 # Same as the last item, so no need to deal with nesting or opening stuff
1534 $output .= $this->nextItem( substr( $pref, -1 ) );
1535 $paragraphStack = false;
1537 if ( substr( $pref, -1 ) == ';') {
1538 # The one nasty exception: definition lists work like this:
1539 # ; title : definition text
1540 # So we check for : in the remainder text to split up the
1541 # title and definition, without b0rking links.
1542 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1544 $output .= $term . $this->nextItem( ':' );
1547 } elseif( $prefixLength ||
$lastPrefixLength ) {
1548 # Either open or close a level...
1549 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1550 $paragraphStack = false;
1552 while( $commonPrefixLength < $lastPrefixLength ) {
1553 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1554 --$lastPrefixLength;
1556 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1557 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1559 while ( $prefixLength > $commonPrefixLength ) {
1560 $char = substr( $pref, $commonPrefixLength, 1 );
1561 $output .= $this->openList( $char );
1563 if ( ';' == $char ) {
1564 # FIXME: This is dupe of code above
1565 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1567 $output .= $term . $this->nextItem( ':' );
1570 ++
$commonPrefixLength;
1572 $lastPrefix = $pref2;
1574 if( 0 == $prefixLength ) {
1575 wfProfileIn( "$fname-paragraph" );
1576 # No prefix (not in list)--go to paragraph mode
1577 $uniq_prefix = UNIQ_PREFIX
;
1578 // XXX: use a stack for nestable elements like span, table and div
1579 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1580 $closematch = preg_match(
1581 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1582 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1583 if ( $openmatch or $closematch ) {
1584 $paragraphStack = false;
1585 $output .= $this->closeParagraph();
1586 if($preOpenMatch and !$preCloseMatch) {
1587 $this->mInPre
= true;
1589 if ( $closematch ) {
1590 $inBlockElem = false;
1592 $inBlockElem = true;
1594 } else if ( !$inBlockElem && !$this->mInPre
) {
1595 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1597 if ($this->mLastSection
!= 'pre') {
1598 $paragraphStack = false;
1599 $output .= $this->closeParagraph().'<pre>';
1600 $this->mLastSection
= 'pre';
1602 $t = substr( $t, 1 );
1605 if ( '' == trim($t) ) {
1606 if ( $paragraphStack ) {
1607 $output .= $paragraphStack.'<br />';
1608 $paragraphStack = false;
1609 $this->mLastSection
= 'p';
1611 if ($this->mLastSection
!= 'p' ) {
1612 $output .= $this->closeParagraph();
1613 $this->mLastSection
= '';
1614 $paragraphStack = '<p>';
1616 $paragraphStack = '</p><p>';
1620 if ( $paragraphStack ) {
1621 $output .= $paragraphStack;
1622 $paragraphStack = false;
1623 $this->mLastSection
= 'p';
1624 } else if ($this->mLastSection
!= 'p') {
1625 $output .= $this->closeParagraph().'<p>';
1626 $this->mLastSection
= 'p';
1631 wfProfileOut( "$fname-paragraph" );
1633 if ($paragraphStack === false) {
1637 while ( $prefixLength ) {
1638 $output .= $this->closeList( $pref2{$prefixLength-1} );
1641 if ( '' != $this->mLastSection
) {
1642 $output .= '</' . $this->mLastSection
. '>';
1643 $this->mLastSection
= '';
1646 wfProfileOut( $fname );
1651 * Split up a string on ':', ignoring any occurences inside
1652 * <a>..</a> or <span>...</span>
1653 * @param string $str the string to split
1654 * @param string &$before set to everything before the ':'
1655 * @param string &$after set to everything after the ':'
1656 * return string the position of the ':', or false if none found
1658 function findColonNoLinks($str, &$before, &$after) {
1659 # I wonder if we should make this count all tags, not just <a>
1660 # and <span>. That would prevent us from matching a ':' that
1661 # comes in the middle of italics other such formatting....
1663 $fname = 'Parser::findColonNoLinks';
1664 wfProfileIn( $fname );
1667 $colon = strpos($str, ':', $pos);
1669 if ($colon !== false) {
1670 $before = substr($str, 0, $colon);
1671 $after = substr($str, $colon +
1);
1673 # Skip any ':' within <a> or <span> pairs
1674 $a = substr_count($before, '<a');
1675 $s = substr_count($before, '<span');
1676 $ca = substr_count($before, '</a>');
1677 $cs = substr_count($before, '</span>');
1679 if ($a <= $ca and $s <= $cs) {
1680 # Tags are balanced before ':'; ok
1685 } while ($colon !== false);
1686 wfProfileOut( $fname );
1691 * Return value of a magic variable (like PAGENAME)
1695 function getVariableValue( $index ) {
1696 global $wgContLang, $wgSitename, $wgServer;
1699 * Some of these require message or data lookups and can be
1700 * expensive to check many times.
1702 static $varCache = array();
1703 if( isset( $varCache[$index] ) ) return $varCache[$index];
1706 case MAG_CURRENTMONTH
:
1707 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1708 case MAG_CURRENTMONTHNAME
:
1709 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1710 case MAG_CURRENTMONTHNAMEGEN
:
1711 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1712 case MAG_CURRENTDAY
:
1713 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1715 return $this->mTitle
->getText();
1717 return $this->mTitle
->getPartialURL();
1719 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1720 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1721 case MAG_CURRENTDAYNAME
:
1722 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1723 case MAG_CURRENTYEAR
:
1724 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1725 case MAG_CURRENTTIME
:
1726 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1727 case MAG_NUMBEROFARTICLES
:
1728 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1739 * initialise the magic variables (like CURRENTMONTHNAME)
1743 function initialiseVariables() {
1744 $fname = 'Parser::initialiseVariables';
1745 wfProfileIn( $fname );
1746 global $wgVariableIDs;
1747 $this->mVariables
= array();
1748 foreach ( $wgVariableIDs as $id ) {
1749 $mw =& MagicWord
::get( $id );
1750 $mw->addToArray( $this->mVariables
, $this->getVariableValue( $id ) );
1752 wfProfileOut( $fname );
1756 * Replace magic variables, templates, and template arguments
1757 * with the appropriate text. Templates are substituted recursively,
1758 * taking care to avoid infinite loops.
1760 * Note that the substitution depends on value of $mOutputType:
1761 * OT_WIKI: only {{subst:}} templates
1762 * OT_MSG: only magic variables
1763 * OT_HTML: all templates and magic variables
1765 * @param string $tex The text to transform
1766 * @param array $args Key-value pairs representing template parameters to substitute
1769 function replaceVariables( $text, $args = array() ) {
1770 global $wgLang, $wgScript, $wgArticlePath;
1772 # Prevent too big inclusions
1773 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1777 $fname = 'Parser::replaceVariables';
1778 wfProfileIn( $fname );
1780 $titleChars = Title
::legalChars();
1782 # This function is called recursively. To keep track of arguments we need a stack:
1783 array_push( $this->mArgStack
, $args );
1785 # Variable substitution
1786 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1788 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1789 # Argument substitution
1790 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1792 # Template substitution
1793 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1794 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1796 array_pop( $this->mArgStack
);
1798 wfProfileOut( $fname );
1803 * Replace magic variables
1806 function variableSubstitution( $matches ) {
1807 if ( !$this->mVariables
) {
1808 $this->initialiseVariables();
1811 if ( $this->mOutputType
== OT_WIKI
) {
1812 # Do only magic variables prefixed by SUBST
1813 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1814 if (!$mwSubst->matchStartAndRemove( $matches[1] ))
1816 # Note that if we don't substitute the variable below,
1817 # we don't remove the {{subst:}} magic word, in case
1818 # it is a template rather than a magic variable.
1820 if ( !$skip && array_key_exists( $matches[1], $this->mVariables
) ) {
1821 $text = $this->mVariables
[$matches[1]];
1822 $this->mOutput
->mContainsOldMagic
= true;
1824 $text = $matches[0];
1829 # Split template arguments
1830 function getTemplateArgs( $argsString ) {
1831 if ( $argsString === '' ) {
1835 $args = explode( '|', substr( $argsString, 1 ) );
1837 # If any of the arguments contains a '[[' but no ']]', it needs to be
1838 # merged with the next arg because the '|' character between belongs
1839 # to the link syntax and not the template parameter syntax.
1840 $argc = count($args);
1842 for ( $i = 0; $i < $argc-1; $i++
) {
1843 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1844 $args[$i] .= '|'.$args[$i+
1];
1845 array_splice($args, $i+
1, 1);
1855 * Return the text of a template, after recursively
1856 * replacing any variables or templates within the template.
1858 * @param array $matches The parts of the template
1859 * $matches[1]: the title, i.e. the part before the |
1860 * $matches[2]: the parameters (including a leading |), if any
1861 * @return string the text of the template
1864 function braceSubstitution( $matches ) {
1865 global $wgLinkCache, $wgContLang;
1866 $fname = 'Parser::braceSubstitution';
1873 # Need to know if the template comes at the start of a line,
1874 # to treat the beginning of the template like the beginning
1875 # of a line for tables and block-level elements.
1876 $linestart = $matches[1];
1878 # $part1 is the bit before the first |, and must contain only title characters
1879 # $args is a list of arguments, starting from index 0, not including $part1
1881 $part1 = $matches[2];
1882 # If the third subpattern matched anything, it will start with |
1884 $args = $this->getTemplateArgs($matches[3]);
1885 $argc = count( $args );
1887 # Don't parse {{{}}} because that's only for template arguments
1888 if ( $linestart === '{' ) {
1889 $text = $matches[0];
1896 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1897 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1898 # One of two possibilities is true:
1899 # 1) Found SUBST but not in the PST phase
1900 # 2) Didn't find SUBST and in the PST phase
1901 # In either case, return without further processing
1902 $text = $matches[0];
1908 # MSG, MSGNW and INT
1911 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1912 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1915 # Remove obsolete MSG:
1916 $mwMsg =& MagicWord
::get( MAG_MSG
);
1917 $mwMsg->matchStartAndRemove( $part1 );
1920 # Check if it is an internal message
1921 $mwInt =& MagicWord
::get( MAG_INT
);
1922 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1923 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1924 $text = $linestart . wfMsgReal( $part1, $args, true );
1932 # Check for NS: (namespace expansion)
1933 $mwNs = MagicWord
::get( MAG_NS
);
1934 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1935 if ( intval( $part1 ) ) {
1936 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1939 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1940 if ( !is_null( $index ) ) {
1941 $text = $linestart . $wgContLang->getNsText( $index );
1948 # LOCALURL and LOCALURLE
1950 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1951 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1953 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1954 $func = 'getLocalURL';
1955 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1956 $func = 'escapeLocalURL';
1961 if ( $func !== '' ) {
1962 $title = Title
::newFromText( $part1 );
1963 if ( !is_null( $title ) ) {
1965 $text = $linestart . $title->$func( $args[0] );
1967 $text = $linestart . $title->$func();
1975 if ( !$found && $argc == 1 ) {
1976 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
1977 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1978 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
1983 # Template table test
1985 # Did we encounter this template already? If yes, it is in the cache
1986 # and we need to check for loops.
1987 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
1988 # set $text to cached message.
1989 $text = $linestart . $this->mTemplates
[$part1];
1992 # Infinite loop test
1993 if ( isset( $this->mTemplatePath
[$part1] ) ) {
1996 $text .= '<!-- WARNING: template loop detected -->';
2000 # Load from database
2001 $itcamefromthedatabase = false;
2004 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2005 if ($subpage !== '') {
2006 $ns = $this->mTitle
->getNamespace();
2008 $title = Title
::newFromText( $part1, $ns );
2009 if ( !is_null( $title ) && !$title->isExternal() ) {
2010 # Check for excessive inclusion
2011 $dbk = $title->getPrefixedDBkey();
2012 if ( $this->incrementIncludeCount( $dbk ) ) {
2013 # This should never be reached.
2014 $article = new Article( $title );
2015 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2016 if ( $articleContent !== false ) {
2018 $text = $linestart . $articleContent;
2019 $itcamefromthedatabase = true;
2023 # If the title is valid but undisplayable, make a link to it
2024 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2025 $text = $linestart . '[['.$title->getPrefixedText().']]';
2029 # Template cache array insertion
2030 $this->mTemplates
[$part1] = $text;
2034 # Recursive parsing, escaping and link table handling
2035 # Only for HTML output
2036 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2037 $text = wfEscapeWikiText( $text );
2038 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2039 # Clean up argument array
2040 $assocArgs = array();
2042 foreach( $args as $arg ) {
2043 $eqpos = strpos( $arg, '=' );
2044 if ( $eqpos === false ) {
2045 $assocArgs[$index++
] = $arg;
2047 $name = trim( substr( $arg, 0, $eqpos ) );
2048 $value = trim( substr( $arg, $eqpos+
1 ) );
2049 if ( $value === false ) {
2052 if ( $name !== false ) {
2053 $assocArgs[$name] = $value;
2058 # Add a new element to the templace recursion path
2059 $this->mTemplatePath
[$part1] = 1;
2061 $text = $this->strip( $text, $this->mStripState
);
2062 $text = $this->removeHTMLtags( $text );
2063 $text = $this->replaceVariables( $text, $assocArgs );
2065 # Resume the link cache and register the inclusion as a link
2066 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2067 $wgLinkCache->addLinkObj( $title );
2070 # If the template begins with a table or block-level
2071 # element, it should be treated as beginning a new line.
2072 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2073 $text = "\n" . $text;
2077 # Empties the template path
2078 $this->mTemplatePath
= array();
2082 # replace ==section headers==
2083 # XXX this needs to go away once we have a better parser.
2084 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2085 if( !is_null( $title ) )
2086 $encodedname = base64_encode($title->getPrefixedDBkey());
2088 $encodedname = base64_encode("");
2089 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2090 PREG_SPLIT_DELIM_CAPTURE
);
2093 for( $i = 0; $i < count($m); $i +
= 2 ) {
2095 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2097 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2101 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2102 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2103 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2110 # Empties the template path
2111 $this->mTemplatePath
= array();
2121 * Triple brace replacement -- used for template arguments
2124 function argSubstitution( $matches ) {
2125 $arg = trim( $matches[1] );
2126 $text = $matches[0];
2127 $inputArgs = end( $this->mArgStack
);
2129 if ( array_key_exists( $arg, $inputArgs ) ) {
2130 $text = $inputArgs[$arg];
2137 * Returns true if the function is allowed to include this entity
2140 function incrementIncludeCount( $dbk ) {
2141 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2142 $this->mIncludeCount
[$dbk] = 0;
2144 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2153 * Cleans up HTML, removes dangerous tags and attributes, and
2154 * removes HTML comments
2157 function removeHTMLtags( $text ) {
2158 global $wgUseTidy, $wgUserHtml;
2159 $fname = 'Parser::removeHTMLtags';
2160 wfProfileIn( $fname );
2163 $htmlpairs = array( # Tags that must be closed
2164 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
2165 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
2166 'strike', 'strong', 'tt', 'var', 'div', 'center',
2167 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
2168 'ruby', 'rt' , 'rb' , 'rp', 'p'
2170 $htmlsingle = array(
2171 'br', 'hr', 'li', 'dt', 'dd'
2173 $htmlnest = array( # Tags that can be nested--??
2174 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
2175 'dl', 'font', 'big', 'small', 'sub', 'sup'
2177 $tabletags = array( # Can only appear inside table
2181 $htmlpairs = array();
2182 $htmlsingle = array();
2183 $htmlnest = array();
2184 $tabletags = array();
2187 $htmlsingle = array_merge( $tabletags, $htmlsingle );
2188 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
2190 $htmlattrs = $this->getHTMLattrs () ;
2192 # Remove HTML comments
2193 $text = $this->removeHTMLcomments( $text );
2195 $bits = explode( '<', $text );
2196 $text = array_shift( $bits );
2198 $tagstack = array(); $tablestack = array();
2199 foreach ( $bits as $x ) {
2200 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
2201 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2203 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2204 error_reporting( $prev );
2207 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2211 if ( ! in_array( $t, $htmlsingle ) &&
2212 ( $ot = @array_pop
( $tagstack ) ) != $t ) {
2213 @array_push
( $tagstack, $ot );
2216 if ( $t == 'table' ) {
2217 $tagstack = array_pop( $tablestack );
2222 # Keep track for later
2223 if ( in_array( $t, $tabletags ) &&
2224 ! in_array( 'table', $tagstack ) ) {
2226 } else if ( in_array( $t, $tagstack ) &&
2227 ! in_array ( $t , $htmlnest ) ) {
2229 } else if ( ! in_array( $t, $htmlsingle ) ) {
2230 if ( $t == 'table' ) {
2231 array_push( $tablestack, $tagstack );
2232 $tagstack = array();
2234 array_push( $tagstack, $t );
2236 # Strip non-approved attributes from the tag
2237 $newparams = $this->fixTagAttributes($params);
2241 $rest = str_replace( '>', '>', $rest );
2242 $text .= "<$slash$t $newparams$brace$rest";
2246 $text .= '<' . str_replace( '>', '>', $x);
2248 # Close off any remaining tags
2249 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2251 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2254 # this might be possible using tidy itself
2255 foreach ( $bits as $x ) {
2256 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2258 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2259 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2260 $newparams = $this->fixTagAttributes($params);
2261 $rest = str_replace( '>', '>', $rest );
2262 $text .= "<$slash$t $newparams$brace$rest";
2264 $text .= '<' . str_replace( '>', '>', $x);
2268 wfProfileOut( $fname );
2273 * Remove '<!--', '-->', and everything between.
2274 * To avoid leaving blank lines, when a comment is both preceded
2275 * and followed by a newline (ignoring spaces), trim leading and
2276 * trailing spaces and one of the newlines.
2280 function removeHTMLcomments( $text ) {
2281 $fname='Parser::removeHTMLcomments';
2282 wfProfileIn( $fname );
2283 while (($start = strpos($text, '<!--')) !== false) {
2284 $end = strpos($text, '-->', $start +
4);
2285 if ($end === false) {
2286 # Unterminated comment; bail out
2292 # Trim space and newline if the comment is both
2293 # preceded and followed by a newline
2294 $spaceStart = max($start - 1, 0);
2295 $spaceLen = $end - $spaceStart;
2296 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
2300 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
2302 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
2303 # Remove the comment, leading and trailing
2304 # spaces, and leave only one newline.
2305 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
2308 # Remove just the comment.
2309 $text = substr_replace($text, '', $start, $end - $start);
2312 wfProfileOut( $fname );
2317 * This function accomplishes several tasks:
2318 * 1) Auto-number headings if that option is enabled
2319 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2320 * 3) Add a Table of contents on the top for users who have enabled the option
2321 * 4) Auto-anchor headings
2323 * It loops through all headlines, collects the necessary data, then splits up the
2324 * string and re-inserts the newly formatted headlines.
2327 /* private */ function formatHeadings( $text, $isMain=true ) {
2328 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders;
2330 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2331 $doShowToc = $this->mOptions
->getShowToc();
2332 $forceTocHere = false;
2333 if( !$this->mTitle
->userCanEdit() ) {
2335 $rightClickHack = 0;
2337 $showEditLink = $this->mOptions
->getEditSection();
2338 $rightClickHack = $this->mOptions
->getEditSectionOnRightClick();
2341 # Inhibit editsection links if requested in the page
2342 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2343 if( $esw->matchAndRemove( $text ) ) {
2346 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2348 $mw =& MagicWord
::get( MAG_NOTOC
);
2349 if( $mw->matchAndRemove( $text ) ) {
2353 # never add the TOC to the Main Page. This is an entry page that should not
2354 # be more than 1-2 screens large anyway
2355 if( $this->mTitle
->getPrefixedText() == wfMsg('mainpage') ) {
2359 # Get all headlines for numbering them and adding funky stuff like [edit]
2360 # links - this is for later, but we need the number of headlines right now
2361 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
2363 # if there are fewer than 4 headlines in the article, do not show TOC
2364 if( $numMatches < 4 ) {
2368 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2369 # override above conditions and always show TOC at that place
2370 $mw =& MagicWord
::get( MAG_TOC
);
2371 if ($mw->match( $text ) ) {
2373 $forceTocHere = true;
2375 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2376 # override above conditions and always show TOC above first header
2377 $mw =& MagicWord
::get( MAG_FORCETOC
);
2378 if ($mw->matchAndRemove( $text ) ) {
2385 # We need this to perform operations on the HTML
2386 $sk =& $this->mOptions
->getSkin();
2390 $sectionCount = 0; # headlineCount excluding template sections
2392 # Ugh .. the TOC should have neat indentation levels which can be
2393 # passed to the skin functions. These are determined here
2398 $sublevelCount = array();
2401 foreach( $matches[3] as $headline ) {
2403 $templatetitle = "";
2404 $templatesection = 0;
2406 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2408 $templatetitle = base64_decode($mat[1]);
2409 $templatesection = 1 +
(int)base64_decode($mat[2]);
2410 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2415 $prevlevel = $level;
2417 $level = $matches[1][$headlineCount];
2418 if( ( $doNumberHeadings ||
$doShowToc ) && $prevlevel && $level > $prevlevel ) {
2419 # reset when we enter a new level
2420 $sublevelCount[$level] = 0;
2421 $toc .= $sk->tocIndent( $level - $prevlevel );
2422 $toclevel +
= $level - $prevlevel;
2424 if( ( $doNumberHeadings ||
$doShowToc ) && $level < $prevlevel ) {
2425 # reset when we step back a level
2426 $sublevelCount[$level+
1]=0;
2427 $toc .= $sk->tocUnindent( $prevlevel - $level );
2428 $toclevel -= $prevlevel - $level;
2430 # count number of headlines for each level
2431 @$sublevelCount[$level]++
;
2432 if( $doNumberHeadings ||
$doShowToc ) {
2434 for( $i = 1; $i <= $level; $i++
) {
2435 if( !empty( $sublevelCount[$i] ) ) {
2439 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2445 # The canonized header is a version of the header text safe to use for links
2446 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2447 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2448 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState
);
2450 # Remove link placeholders by the link text.
2451 # <!--LINK number-->
2453 # link text with suffix
2454 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2455 "\$wgLinkHolders['texts'][\$1]",
2456 $canonized_headline );
2459 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2460 $tocline = trim( $canonized_headline );
2461 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2462 $replacearray = array(
2466 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2467 $refer[$headlineCount] = $canonized_headline;
2469 # count how many in assoc. array so we can track dupes in anchors
2470 @$refers[$canonized_headline]++
;
2471 $refcount[$headlineCount]=$refers[$canonized_headline];
2473 # Prepend the number to the heading text
2475 if( $doNumberHeadings ||
$doShowToc ) {
2476 $tocline = $numbering . ' ' . $tocline;
2478 # Don't number the heading if it is the only one (looks silly)
2479 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2480 # the two are different if the line contains a link
2481 $headline=$numbering . ' ' . $headline;
2485 # Create the anchor for linking from the TOC to the section
2486 $anchor = $canonized_headline;
2487 if($refcount[$headlineCount] > 1 ) {
2488 $anchor .= '_' . $refcount[$headlineCount];
2490 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2491 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2493 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2494 if ( empty( $head[$headlineCount] ) ) {
2495 $head[$headlineCount] = '';
2498 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2500 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2503 # Add the edit section span
2504 if( $rightClickHack ) {
2506 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2508 $headline = $sk->editSectionScript($this->mTitle
, $sectionCount+
1,$headline);
2511 # give headline the correct <h#> tag
2512 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2520 $toclines = $headlineCount;
2521 $toc .= $sk->tocUnindent( $toclevel );
2522 $toc = $sk->tocTable( $toc );
2525 # split up and insert constructed headlines
2527 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2530 foreach( $blocks as $block ) {
2531 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2532 # This is the [edit] link that appears for the top block of text when
2533 # section editing is enabled
2535 # Disabled because it broke block formatting
2536 # For example, a bullet point in the top line
2537 # $full .= $sk->editSectionLink(0);
2540 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2541 # Top anchor now in skin
2545 if( !empty( $head[$i] ) ) {
2551 $mw =& MagicWord
::get( MAG_TOC
);
2552 return $mw->replace( $toc, $full );
2559 * Return an HTML link for the "ISBN 123456" text
2562 function magicISBN( $text ) {
2564 $fname = 'Parser::magicISBN';
2565 wfProfileIn( $fname );
2567 $a = split( 'ISBN ', ' '.$text );
2568 if ( count ( $a ) < 2 ) {
2569 wfProfileOut( $fname );
2572 $text = substr( array_shift( $a ), 1);
2573 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2575 foreach ( $a as $x ) {
2576 $isbn = $blank = '' ;
2577 while ( ' ' == $x{0} ) {
2579 $x = substr( $x, 1 );
2581 if ( $x == '' ) { # blank isbn
2582 $text .= "ISBN $blank";
2585 while ( strstr( $valid, $x{0} ) != false ) {
2587 $x = substr( $x, 1 );
2589 $num = str_replace( '-', '', $isbn );
2590 $num = str_replace( ' ', '', $num );
2593 $text .= "ISBN $blank$x";
2595 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2596 $text .= '<a href="' .
2597 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2598 "\" class=\"internal\">ISBN $isbn</a>";
2602 wfProfileOut( $fname );
2607 * Return an HTML link for the "GEO ..." text
2610 function magicGEO( $text ) {
2611 global $wgLang, $wgUseGeoMode;
2612 $fname = 'Parser::magicGEO';
2613 wfProfileIn( $fname );
2615 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2616 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2617 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2618 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['N']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2619 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2620 $text = preg_replace ( "/(\d+)°(\d+)'(\d+)\" {$directions['S']}, (\d+)°(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2622 $a = split( 'GEO ', ' '.$text );
2623 if ( count ( $a ) < 2 ) {
2624 wfProfileOut( $fname );
2627 $text = substr( array_shift( $a ), 1);
2628 $valid = '0123456789.+-:';
2630 foreach ( $a as $x ) {
2631 $geo = $blank = '' ;
2632 while ( ' ' == $x{0} ) {
2634 $x = substr( $x, 1 );
2636 while ( strstr( $valid, $x{0} ) != false ) {
2638 $x = substr( $x, 1 );
2640 $num = str_replace( '+', '', $geo );
2641 $num = str_replace( ' ', '', $num );
2643 if ( '' == $num ||
count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2644 $text .= "GEO $blank$x";
2646 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Geo' );
2647 $text .= '<a href="' .
2648 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2649 "\" class=\"internal\">GEO $geo</a>";
2653 wfProfileOut( $fname );
2658 * Return an HTML link for the "RFC 1234" text
2660 * @param string $text text to be processed
2662 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2665 $valid = '0123456789';
2668 $a = split( $keyword, ' '.$text );
2669 if ( count ( $a ) < 2 ) {
2672 $text = substr( array_shift( $a ), 1);
2674 /* Check if keyword is preceed by [[.
2675 * This test is made here cause of the array_shift above
2676 * that prevent the test to be done in the foreach.
2678 if ( substr( $text, -2 ) == '[[' ) {
2682 foreach ( $a as $x ) {
2683 /* token might be empty if we have RFC RFC 1234 */
2691 /** remove and save whitespaces in $blank */
2692 while ( $x{0} == ' ' ) {
2694 $x = substr( $x, 1 );
2697 /** remove and save the rfc number in $id */
2698 while ( strstr( $valid, $x{0} ) != false ) {
2700 $x = substr( $x, 1 );
2704 /* call back stripped spaces*/
2705 $text .= $keyword.$blank.$x;
2706 } elseif( $internal ) {
2708 $text .= $keyword.$id.$x;
2710 /* build the external link*/
2711 $url = wfmsg( $urlmsg );
2712 $url = str_replace( '$1', $id, $url);
2713 $sk =& $this->mOptions
->getSkin();
2714 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2715 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2718 /* Check if the next RFC keyword is preceed by [[ */
2719 $internal = ( substr($x,-2) == '[[' );
2725 * Transform wiki markup when saving a page by doing \r\n -> \n
2726 * conversion, substitting signatures, {{subst:}} templates, etc.
2728 * @param string $text the text to transform
2729 * @param Title &$title the Title object for the current article
2730 * @param User &$user the User object describing the current user
2731 * @param ParserOptions $options parsing options
2732 * @param bool $clearState whether to clear the parser state first
2733 * @return string the altered wiki markup
2736 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2737 $this->mOptions
= $options;
2738 $this->mTitle
=& $title;
2739 $this->mOutputType
= OT_WIKI
;
2741 if ( $clearState ) {
2742 $this->clearState();
2745 $stripState = false;
2749 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2750 $text = $this->strip( $text, $stripState, false );
2751 $text = $this->pstPass2( $text, $user );
2752 $text = $this->unstrip( $text, $stripState );
2753 $text = $this->unstripNoWiki( $text, $stripState );
2758 * Pre-save transform helper function
2761 function pstPass2( $text, &$user ) {
2762 global $wgLang, $wgContLang, $wgLocaltimezone;
2764 # Variable replacement
2765 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2766 $text = $this->replaceVariables( $text );
2770 $n = $user->getName();
2771 $k = $user->getOption( 'nickname' );
2772 if ( '' == $k ) { $k = $n; }
2773 if ( isset( $wgLocaltimezone ) ) {
2774 $oldtz = getenv( 'TZ' );
2775 putenv( 'TZ='.$wgLocaltimezone );
2777 /* Note: this is an ugly timezone hack for the European wikis */
2778 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2779 ' (' . date( 'T' ) . ')';
2780 if ( isset( $wgLocaltimezone ) ) {
2781 putenv( 'TZ='.$oldtzs );
2784 $text = preg_replace( '/~~~~~~/', $d, $text );
2785 $text = preg_replace( '/~~~~/', '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]] $d", $text );
2786 $text = preg_replace( '/~~~/', '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]", $text );
2788 # Context links: [[|name]] and [[name (context)|]]
2790 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2791 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2792 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2793 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2795 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2796 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2797 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2798 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2800 $t = $this->mTitle
->getText();
2801 if ( preg_match( $conpat, $t, $m ) ) {
2804 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2805 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2806 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2808 if ( '' == $context ) {
2809 $text = preg_replace( $p2, '[[\\1]]', $text );
2811 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2814 # Trim trailing whitespace
2815 # MAG_END (__END__) tag allows for trailing
2816 # whitespace to be deliberately included
2817 $text = rtrim( $text );
2818 $mw =& MagicWord
::get( MAG_END
);
2819 $mw->matchAndRemove( $text );
2825 * Set up some variables which are usually set up in parse()
2826 * so that an external function can call some class members with confidence
2829 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2830 $this->mTitle
=& $title;
2831 $this->mOptions
= $options;
2832 $this->mOutputType
= $outputType;
2833 if ( $clearState ) {
2834 $this->clearState();
2839 * Transform a MediaWiki message by replacing magic variables.
2841 * @param string $text the text to transform
2842 * @param ParserOptions $options options
2843 * @return string the text with variables substituted
2846 function transformMsg( $text, $options ) {
2848 static $executing = false;
2850 # Guard against infinite recursion
2856 $this->mTitle
= $wgTitle;
2857 $this->mOptions
= $options;
2858 $this->mOutputType
= OT_MSG
;
2859 $this->clearState();
2860 $text = $this->replaceVariables( $text );
2867 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2868 * Callback will be called with the text within
2869 * Transform and return the text within
2872 function setHook( $tag, $callback ) {
2873 $oldVal = @$this->mTagHooks
[$tag];
2874 $this->mTagHooks
[$tag] = $callback;
2879 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2880 * Placeholders created in Skin::makeLinkObj()
2881 * Returns an array of links found, indexed by PDBK:
2885 * $options is a bit field, RLH_FOR_UPDATE to select for update
2887 function replaceLinkHolders( &$text, $options = 0 ) {
2888 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2889 global $wgInterwikiLinkHolders;
2890 global $outputReplace;
2892 if ( $wgUseOldExistenceCheck ) {
2896 $fname = 'Parser::replaceLinkHolders';
2897 wfProfileIn( $fname );
2902 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2903 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2904 wfProfileIn( $fname.'-check' );
2905 $dbr =& wfGetDB( DB_SLAVE
);
2906 $cur = $dbr->tableName( 'cur' );
2907 $sk = $wgUser->getSkin();
2908 $threshold = $wgUser->getOption('stubthreshold');
2911 asort( $wgLinkHolders['namespaces'] );
2915 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2917 $title = $wgLinkHolders['titles'][$key];
2919 # Skip invalid entries.
2920 # Result will be ugly, but prevents crash.
2921 if ( is_null( $title ) ) {
2924 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2926 # Check if it's in the link cache already
2927 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2928 $colours[$pdbk] = 1;
2929 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2930 $colours[$pdbk] = 0;
2932 # Not in the link cache, add it to the query
2933 if ( !isset( $current ) ) {
2935 $query = "SELECT cur_id, cur_namespace, cur_title";
2936 if ( $threshold > 0 ) {
2937 $query .= ", LENGTH(cur_text) AS cur_len, cur_is_redirect";
2939 $query .= " FROM $cur WHERE (cur_namespace=$val AND cur_title IN(";
2940 } elseif ( $current != $val ) {
2942 $query .= ")) OR (cur_namespace=$val AND cur_title IN(";
2947 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2952 if ( $options & RLH_FOR_UPDATE
) {
2953 $query .= ' FOR UPDATE';
2956 $res = $dbr->query( $query, $fname );
2958 # Fetch data and form into an associative array
2959 # non-existent = broken
2962 while ( $s = $dbr->fetchObject($res) ) {
2963 $title = Title
::makeTitle( $s->cur_namespace
, $s->cur_title
);
2964 $pdbk = $title->getPrefixedDBkey();
2965 $wgLinkCache->addGoodLink( $s->cur_id
, $pdbk );
2967 if ( $threshold > 0 ) {
2968 $size = $s->cur_len
;
2969 if ( $s->cur_is_redirect ||
$s->cur_namespace
!= 0 ||
$length < $threshold ) {
2970 $colours[$pdbk] = 1;
2972 $colours[$pdbk] = 2;
2975 $colours[$pdbk] = 1;
2979 wfProfileOut( $fname.'-check' );
2981 # Construct search and replace arrays
2982 wfProfileIn( $fname.'-construct' );
2983 $outputReplace = array();
2984 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2985 $pdbk = $pdbks[$key];
2986 $searchkey = '<!--LINK '.$key.'-->';
2987 $title = $wgLinkHolders['titles'][$key];
2988 if ( empty( $colours[$pdbk] ) ) {
2989 $wgLinkCache->addBadLink( $pdbk );
2990 $colours[$pdbk] = 0;
2991 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2992 $wgLinkHolders['texts'][$key],
2993 $wgLinkHolders['queries'][$key] );
2994 } elseif ( $colours[$pdbk] == 1 ) {
2995 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2996 $wgLinkHolders['texts'][$key],
2997 $wgLinkHolders['queries'][$key] );
2998 } elseif ( $colours[$pdbk] == 2 ) {
2999 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3000 $wgLinkHolders['texts'][$key],
3001 $wgLinkHolders['queries'][$key] );
3004 wfProfileOut( $fname.'-construct' );
3007 wfProfileIn( $fname.'-replace' );
3009 $text = preg_replace_callback(
3010 '/(<!--LINK .*?-->)/',
3011 "outputReplaceMatches",
3013 wfProfileOut( $fname.'-replace' );
3016 if ( !empty( $wgInterwikiLinkHolders ) ) {
3017 wfProfileIn( $fname.'-interwiki' );
3018 $outputReplace = $wgInterwikiLinkHolders;
3019 $text = preg_replace_callback(
3020 '/<!--IWLINK (.*?)-->/',
3021 "outputReplaceMatches",
3023 wfProfileOut( $fname.'-interwiki' );
3026 wfProfileOut( $fname );
3031 * Renders an image gallery from a text with one line per image.
3032 * text labels may be given by using |-style alternative text. E.g.
3033 * Image:one.jpg|The number "1"
3034 * Image:tree.jpg|A tree
3035 * given as text will return the HTML of a gallery with two images,
3036 * labeled 'The number "1"' and
3039 function renderImageGallery( $text ) {
3040 global $wgLinkCache;
3041 $ig = new ImageGallery();
3042 $ig->setShowBytes( false );
3043 $ig->setShowFilename( false );
3044 $lines = explode( "\n", $text );
3046 foreach ( $lines as $line ) {
3047 # match lines like these:
3048 # Image:someimage.jpg|This is some image
3049 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3051 if ( count( $matches ) == 0 ) {
3054 $nt = Title
::newFromURL( $matches[1] );
3055 if ( isset( $matches[3] ) ) {
3056 $label = $matches[3];
3060 $ig->add( Image
::newFromTitle( $nt ), $label );
3061 $wgLinkCache->addImageLinkObj( $nt );
3063 return $ig->toHTML();
3069 * @package MediaWiki
3073 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3074 var $mCacheTime; # Used in ParserCache
3075 var $mVersion; # Compatibility check
3077 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3078 $containsOldMagic = false )
3080 $this->mText
= $text;
3081 $this->mLanguageLinks
= $languageLinks;
3082 $this->mCategoryLinks
= $categoryLinks;
3083 $this->mContainsOldMagic
= $containsOldMagic;
3084 $this->mCacheTime
= '';
3085 $this->mVersion
= MW_PARSER_VERSION
;
3088 function getText() { return $this->mText
; }
3089 function getLanguageLinks() { return $this->mLanguageLinks
; }
3090 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3091 function getCacheTime() { return $this->mCacheTime
; }
3092 function containsOldMagic() { return $this->mContainsOldMagic
; }
3093 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3094 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3095 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3096 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3097 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3098 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3100 function merge( $other ) {
3101 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3102 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3103 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3107 * Return true if this cached output object predates the global or
3108 * per-article cache invalidation timestamps, or if it comes from
3109 * an incompatible older version.
3111 * @param string $touched the affected article's last touched timestamp
3115 function expired( $touched ) {
3116 global $wgCacheEpoch;
3117 return $this->getCacheTime() <= $touched ||
3118 $this->getCacheTime() <= $wgCacheEpoch ||
3119 !isset( $this->mVersion
) ||
3120 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3125 * Set options of the Parser
3127 * @package MediaWiki
3131 # All variables are private
3132 var $mUseTeX; # Use texvc to expand <math> tags
3133 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
3134 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3135 var $mAllowExternalImages; # Allow external images inline
3136 var $mSkin; # Reference to the preferred skin
3137 var $mDateFormat; # Date format index
3138 var $mEditSection; # Create "edit section" links
3139 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
3140 var $mNumberHeadings; # Automatically number headings
3141 var $mShowToc; # Show table of contents
3143 function getUseTeX() { return $this->mUseTeX
; }
3144 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3145 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3146 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3147 function getSkin() { return $this->mSkin
; }
3148 function getDateFormat() { return $this->mDateFormat
; }
3149 function getEditSection() { return $this->mEditSection
; }
3150 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick
; }
3151 function getNumberHeadings() { return $this->mNumberHeadings
; }
3152 function getShowToc() { return $this->mShowToc
; }
3154 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3155 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3156 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3157 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3158 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3159 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3160 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick
, $x ); }
3161 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3162 function setShowToc( $x ) { return wfSetVar( $this->mShowToc
, $x ); }
3164 function setSkin( &$x ) { $this->mSkin
=& $x; }
3166 # Get parser options
3167 /* static */ function newFromUser( &$user ) {
3168 $popts = new ParserOptions
;
3169 $popts->initialiseFromUser( $user );
3174 function initialiseFromUser( &$userInput ) {
3175 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3176 $fname = 'ParserOptions::initialiseFromUser';
3177 wfProfileIn( $fname );
3178 if ( !$userInput ) {
3180 $user->setLoaded( true );
3182 $user =& $userInput;
3185 $this->mUseTeX
= $wgUseTeX;
3186 $this->mUseDynamicDates
= $wgUseDynamicDates;
3187 $this->mInterwikiMagic
= $wgInterwikiMagic;
3188 $this->mAllowExternalImages
= $wgAllowExternalImages;
3189 wfProfileIn( $fname.'-skin' );
3190 $this->mSkin
=& $user->getSkin();
3191 wfProfileOut( $fname.'-skin' );
3192 $this->mDateFormat
= $user->getOption( 'date' );
3193 $this->mEditSection
= $user->getOption( 'editsection' );
3194 $this->mEditSectionOnRightClick
= $user->getOption( 'editsectiononrightclick' );
3195 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3196 $this->mShowToc
= $user->getOption( 'showtoc' );
3197 wfProfileOut( $fname );
3204 * Callback function used by Parser::replaceLinkHolders()
3205 * to substitute link placeholders.
3207 function &outputReplaceMatches( $matches ) {
3208 global $outputReplace;
3209 return $outputReplace[$matches[1]];
3213 * Return the total number of articles
3215 function wfNumberOfArticles() {
3216 global $wgNumberOfArticles;
3219 return $wgNumberOfArticles;
3223 * Get various statistics from the database
3226 function wfLoadSiteStats() {
3227 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3228 $fname = 'wfLoadSiteStats';
3230 if ( -1 != $wgNumberOfArticles ) return;
3231 $dbr =& wfGetDB( DB_SLAVE
);
3232 $s = $dbr->selectRow( 'site_stats',
3233 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3234 array( 'ss_row_id' => 1 ), $fname
3237 if ( $s === false ) {
3240 $wgTotalViews = $s->ss_total_views
;
3241 $wgTotalEdits = $s->ss_total_edits
;
3242 $wgNumberOfArticles = $s->ss_good_articles
;
3246 function wfEscapeHTMLTagsOnly( $in ) {
3248 array( '"', '>', '<' ),
3249 array( '"', '>', '<' ),