3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
13 * Update this version number when the ParserOutput format
14 * changes in an incompatible way, so the parser cache
15 * can automatically discard old data.
17 define( 'MW_PARSER_VERSION', '1.5.0' );
20 * Variable substitution O(N^2) attack
22 * Without countermeasures, it would be possible to attack the parser by saving
23 * a page filled with a large number of inclusions of large pages. The size of
24 * the generated page would be proportional to the square of the input size.
25 * Hence, we limit the number of inclusions of any given page, thus bringing any
26 * attack back to O(N).
29 define( 'MAX_INCLUDE_REPEAT', 100 );
30 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32 define( 'RLH_FOR_UPDATE', 1 );
34 # Allowed values for $mOutputType
35 define( 'OT_HTML', 1 );
36 define( 'OT_WIKI', 2 );
37 define( 'OT_MSG' , 3 );
39 # string parameter for extractTags which will cause it
40 # to strip HTML comments in addition to regular
41 # <XML>-style tags. This should not be anything we
42 # may want to use in wikisyntax
43 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45 # prefix for escaping, used in two functions at least
46 define( 'UNIQ_PREFIX', 'NaodW29');
48 # Constants needed for external link processing
49 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
50 define( 'HTTP_PROTOCOLS', 'http|https' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS
.'):'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS
.':)'. # Protocol
60 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
67 * Processes wiki markup
70 * There are three main entry points into the Parser class:
72 * produces HTML output
74 * produces altered wiki markup.
76 * performs brace substitution on MediaWiki messages
79 * objects: $wgLang, $wgLinkCache
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
88 * * only within ParserOptions
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
103 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mInterwikiLinkHolders, $mLinkHolders;
107 var $mOptions, $mTitle, $mOutputType,
108 $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
122 $this->mTemplates
= array();
123 $this->mTemplatePath
= array();
124 $this->mTagHooks
= array();
133 function clearState() {
134 $this->mOutput
= new ParserOutput
;
135 $this->mAutonumber
= 0;
136 $this->mLastSection
= '';
137 $this->mDTopen
= false;
138 $this->mVariables
= false;
139 $this->mIncludeCount
= array();
140 $this->mStripState
= array();
141 $this->mArgStack
= array();
142 $this->mInPre
= false;
143 $this->mInterwikiLinkHolders
= array();
144 $this->mLinkHolders
= array(
145 'namespaces' => array(),
147 'queries' => array(),
154 * First pass--just handle <nowiki> sections, pass the rest off
155 * to internalParse() which does all the real work.
158 * @param string $text Text we want to parse
159 * @param Title &$title A title object
160 * @param array $options
161 * @param boolean $linestart
162 * @param boolean $clearState
163 * @return ParserOutput a ParserOutput
165 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
166 global $wgUseTidy, $wgContLang;
167 $fname = 'Parser::parse';
168 wfProfileIn( $fname );
174 $this->mOptions
= $options;
175 $this->mTitle
=& $title;
176 $this->mOutputType
= OT_HTML
;
178 $this->mStripState
= NULL;
180 //$text = $this->strip( $text, $this->mStripState );
181 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
182 $x =& $this->mStripState
;
183 $text = $this->strip( $text, $x );
185 $text = $this->internalParse( $text );
187 $dashReplace = array(
188 '/ - /' => " – ", # N dash
189 '/(?<=[0-9])-(?=[0-9])/' => "–", # N dash between numbers
190 '/ -- /' => " — " # M dash
192 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
195 $text = $this->unstrip( $text, $this->mStripState
);
197 # Clean up special characters, only run once, next-to-last before doBlockLevels
199 # french spaces, last one Guillemet-left
200 # only if there is something before the space
201 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
202 # french spaces, Guillemet-right
203 '/(\\302\\253) /' => '\\1 ',
204 '/<hr *>/i' => '<hr />',
205 '/<br *>/i' => '<br />',
206 '/<center *>/i' => '<div class="center">',
207 '/<\\/center *>/i' => '</div>',
209 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
212 $text = $this->doBlockLevels( $text, $linestart );
214 $this->replaceLinkHolders( $text );
216 # the position of the convert() call should not be changed. it
217 # assumes that the links are all replaces and the only thing left
218 # is the <nowiki> mark.
219 $text = $wgContLang->convert($text);
220 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
222 $text = $this->unstripNoWiki( $text, $this->mStripState
);
224 $text = Sanitizer
::normalizeCharReferences( $text );
227 $text = Parser
::tidy($text);
230 $this->mOutput
->setText( $text );
231 wfProfileOut( $fname );
232 return $this->mOutput
;
236 * Get a random string
241 function getRandomString() {
242 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
246 * Replaces all occurrences of <$tag>content</$tag> in the text
247 * with a random marker and returns the new text. the output parameter
248 * $content will be an associative array filled with data on the form
249 * $unique_marker => content.
251 * If $content is already set, the additional entries will be appended
252 * If $tag is set to STRIP_COMMENTS, the function will extract
253 * <!-- HTML comments -->
258 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
259 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
266 while ( '' != $text ) {
267 if($tag==STRIP_COMMENTS
) {
268 $p = preg_split( '/<!--/', $text, 2 );
270 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
273 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
276 if($tag==STRIP_COMMENTS
) {
277 $q = preg_split( '/-->/i', $p[1], 2 );
279 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
281 $marker = $rnd . sprintf('%08X', $n++
);
282 $content[$marker] = $q[0];
283 $stripped .= $marker;
291 * Strips and renders nowiki, pre, math, hiero
292 * If $render is set, performs necessary rendering operations on plugins
293 * Returns the text, and fills an array with data needed in unstrip()
294 * If the $state is already a valid strip state, it adds to the state
296 * @param bool $stripcomments when set, HTML comments <!-- like this -->
297 * will be stripped in addition to other tags. This is important
298 * for section editing, where these comments cause confusion when
299 * counting the sections in the wikisource
303 function strip( $text, &$state, $stripcomments = false ) {
304 $render = ($this->mOutputType
== OT_HTML
);
305 $html_content = array();
306 $nowiki_content = array();
307 $math_content = array();
308 $pre_content = array();
309 $comment_content = array();
310 $ext_content = array();
311 $gallery_content = array();
313 # Replace any instances of the placeholders
314 $uniq_prefix = UNIQ_PREFIX
;
315 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
318 global $wgRawHtml, $wgWhitelistEdit;
319 if( $wgRawHtml && $wgWhitelistEdit ) {
320 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
321 foreach( $html_content as $marker => $content ) {
323 # Raw and unchecked for validity.
324 $html_content[$marker] = $content;
326 $html_content[$marker] = '<html>'.$content.'</html>';
332 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
333 foreach( $nowiki_content as $marker => $content ) {
335 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
337 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
342 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
343 foreach( $math_content as $marker => $content ){
345 if( $this->mOptions
->getUseTeX() ) {
346 $math_content[$marker] = renderMath( $content );
348 $math_content[$marker] = '<math>'.$content.'<math>';
351 $math_content[$marker] = '<math>'.$content.'</math>';
356 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
357 foreach( $pre_content as $marker => $content ){
359 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
361 $pre_content[$marker] = '<pre>'.$content.'</pre>';
366 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
367 foreach( $gallery_content as $marker => $content ) {
368 require_once( 'ImageGallery.php' );
370 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
372 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
378 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
379 foreach( $comment_content as $marker => $content ){
380 $comment_content[$marker] = '<!--'.$content.'-->';
385 foreach ( $this->mTagHooks
as $tag => $callback ) {
386 $ext_content[$tag] = array();
387 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
388 foreach( $ext_content[$tag] as $marker => $content ) {
390 $ext_content[$tag][$marker] = $callback( $content );
392 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
397 # Merge state with the pre-existing state, if there is one
399 $state['html'] = $state['html'] +
$html_content;
400 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
401 $state['math'] = $state['math'] +
$math_content;
402 $state['pre'] = $state['pre'] +
$pre_content;
403 $state['comment'] = $state['comment'] +
$comment_content;
404 $state['gallery'] = $state['gallery'] +
$gallery_content;
406 foreach( $ext_content as $tag => $array ) {
407 if ( array_key_exists( $tag, $state ) ) {
408 $state[$tag] = $state[$tag] +
$array;
413 'html' => $html_content,
414 'nowiki' => $nowiki_content,
415 'math' => $math_content,
416 'pre' => $pre_content,
417 'comment' => $comment_content,
418 'gallery' => $gallery_content,
425 * restores pre, math, and hiero removed by strip()
427 * always call unstripNoWiki() after this one
430 function unstrip( $text, &$state ) {
431 # Must expand in reverse order, otherwise nested tags will be corrupted
432 $contentDict = end( $state );
433 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
434 if( key($state) != 'nowiki' && key($state) != 'html') {
435 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
436 $text = str_replace( key( $contentDict ), $content, $text );
445 * always call this after unstrip() to preserve the order
449 function unstripNoWiki( $text, &$state ) {
450 # Must expand in reverse order, otherwise nested tags will be corrupted
451 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
452 $text = str_replace( key( $state['nowiki'] ), $content, $text );
457 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
458 $text = str_replace( key( $state['html'] ), $content, $text );
466 * Add an item to the strip state
467 * Returns the unique tag which must be inserted into the stripped text
468 * The tag will be replaced with the original text in unstrip()
472 function insertStripItem( $text, &$state ) {
473 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
482 $state['item'][$rnd] = $text;
487 * Interface with html tidy, used if $wgUseTidy = true.
488 * If tidy isn't able to correct the markup, the original will be
489 * returned in all its glory with a warning comment appended.
491 * Either the external tidy program or the in-process tidy extension
492 * will be used depending on availability. Override the default
493 * $wgTidyInternal setting to disable the internal if it's not working.
495 * @param string $text Hideous HTML input
496 * @return string Corrected HTML output
500 function tidy( $text ) {
501 global $wgTidyInternal;
502 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
503 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
504 '<head><title>test</title></head><body>'.$text.'</body></html>';
505 if( $wgTidyInternal ) {
506 $correctedtext = Parser
::internalTidy( $wrappedtext );
508 $correctedtext = Parser
::externalTidy( $wrappedtext );
510 if( is_null( $correctedtext ) ) {
511 wfDebug( "Tidy error detected!\n" );
512 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
514 return $correctedtext;
518 * Spawn an external HTML tidy process and get corrected markup back from it.
523 function externalTidy( $text ) {
524 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
525 $fname = 'Parser::externalTidy';
526 wfProfileIn( $fname );
531 $descriptorspec = array(
532 0 => array('pipe', 'r'),
533 1 => array('pipe', 'w'),
534 2 => array('file', '/dev/null', 'a')
537 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
538 if (is_resource($process)) {
539 fwrite($pipes[0], $text);
541 while (!feof($pipes[1])) {
542 $cleansource .= fgets($pipes[1], 1024);
545 proc_close($process);
548 wfProfileOut( $fname );
550 if( $cleansource == '' && $text != '') {
551 // Some kind of error happened, so we couldn't get the corrected text.
552 // Just give up; we'll use the source text and append a warning.
560 * Use the HTML tidy PECL extension to use the tidy library in-process,
561 * saving the overhead of spawning a new process. Currently written to
562 * the PHP 4.3.x version of the extension, may not work on PHP 5.
564 * 'pear install tidy' should be able to compile the extension module.
569 function internalTidy( $text ) {
571 $fname = 'Parser::internalTidy';
572 wfProfileIn( $fname );
574 tidy_load_config( $wgTidyConf );
575 tidy_set_encoding( 'utf8' );
576 tidy_parse_string( $text );
578 if( tidy_get_status() == 2 ) {
579 // 2 is magic number for fatal error
580 // http://www.php.net/manual/en/function.tidy-get-status.php
583 $cleansource = tidy_get_output();
585 wfProfileOut( $fname );
590 * parse the wiki syntax used to render tables
594 function doTableStuff ( $t ) {
595 $fname = 'Parser::doTableStuff';
596 wfProfileIn( $fname );
598 $t = explode ( "\n" , $t ) ;
599 $td = array () ; # Is currently a td tag open?
600 $ltd = array () ; # Was it TD or TH?
601 $tr = array () ; # Is currently a tr tag open?
602 $ltr = array () ; # tr attributes
603 $indent_level = 0; # indent level of the table
604 foreach ( $t AS $k => $x )
607 $fc = substr ( $x , 0 , 1 ) ;
608 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
609 $indent_level = strlen( $matches[1] );
610 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
611 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
612 array_push ( $td , false ) ;
613 array_push ( $ltd , '' ) ;
614 array_push ( $tr , false ) ;
615 array_push ( $ltr , '' ) ;
617 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
618 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
619 $z = "</table>" . substr ( $x , 2);
620 $l = array_pop ( $ltd ) ;
621 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
622 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
624 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
626 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
627 $x = substr ( $x , 1 ) ;
628 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
630 $l = array_pop ( $ltd ) ;
631 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
632 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
635 array_push ( $tr , false ) ;
636 array_push ( $td , false ) ;
637 array_push ( $ltd , '' ) ;
638 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
640 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
642 if ( '|+' == substr ( $x , 0 , 2 ) ) {
644 $x = substr ( $x , 1 ) ;
646 $after = substr ( $x , 1 ) ;
647 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
648 $after = explode ( '||' , $after ) ;
651 # Loop through each table cell
652 foreach ( $after AS $theline )
657 $tra = array_pop ( $ltr ) ;
658 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
659 array_push ( $tr , true ) ;
660 array_push ( $ltr , '' ) ;
663 $l = array_pop ( $ltd ) ;
664 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
665 if ( $fc == '|' ) $l = 'td' ;
666 else if ( $fc == '!' ) $l = 'th' ;
667 else if ( $fc == '+' ) $l = 'caption' ;
669 array_push ( $ltd , $l ) ;
672 $y = explode ( '|' , $theline , 2 ) ;
673 # Note that a '|' inside an invalid link should not
674 # be mistaken as delimiting cell parameters
675 if ( strpos( $y[0], '[[' ) !== false ) {
676 $y = array ($theline);
678 if ( count ( $y ) == 1 )
679 $y = "{$z}<{$l}>{$y[0]}" ;
680 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$y[1]}" ;
682 array_push ( $td , true ) ;
687 # Closing open td, tr && table
688 while ( count ( $td ) > 0 )
690 if ( array_pop ( $td ) ) $t[] = '</td>' ;
691 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
695 $t = implode ( "\n" , $t ) ;
696 wfProfileOut( $fname );
701 * Helper function for parse() that transforms wiki markup into
702 * HTML. Only called for $mOutputType == OT_HTML.
706 function internalParse( $text ) {
710 $fname = 'Parser::internalParse';
711 wfProfileIn( $fname );
713 $text = Sanitizer
::removeHTMLtags( $text );
714 $text = $this->replaceVariables( $text, $args );
716 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
718 $text = $this->doHeadings( $text );
719 if($this->mOptions
->getUseDynamicDates()) {
720 $df =& DateFormatter
::getInstance();
721 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
723 $text = $this->doAllQuotes( $text );
724 $text = $this->replaceInternalLinks( $text );
725 $text = $this->replaceExternalLinks( $text );
727 # replaceInternalLinks may sometimes leave behind
728 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
729 $text = str_replace("http-noparse://","http://",$text);
731 $text = $this->doMagicLinks( $text );
732 $text = $this->doTableStuff( $text );
733 $text = $this->formatHeadings( $text, $isMain );
735 wfProfileOut( $fname );
740 * Replace special strings like "ISBN xxx" and "RFC xxx" with
741 * magic external links.
745 function &doMagicLinks( &$text ) {
746 $text = $this->magicISBN( $text );
747 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
748 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
753 * Parse ^^ tokens and return html
757 function doExponent( $text ) {
758 $fname = 'Parser::doExponent';
759 wfProfileIn( $fname );
760 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
761 wfProfileOut( $fname );
766 * Parse headers and return html
770 function doHeadings( $text ) {
771 $fname = 'Parser::doHeadings';
772 wfProfileIn( $fname );
773 for ( $i = 6; $i >= 1; --$i ) {
774 $h = substr( '======', 0, $i );
775 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
776 "<h{$i}>\\1</h{$i}>\\2", $text );
778 wfProfileOut( $fname );
783 * Replace single quotes with HTML markup
785 * @return string the altered text
787 function doAllQuotes( $text ) {
788 $fname = 'Parser::doAllQuotes';
789 wfProfileIn( $fname );
791 $lines = explode( "\n", $text );
792 foreach ( $lines as $line ) {
793 $outtext .= $this->doQuotes ( $line ) . "\n";
795 $outtext = substr($outtext, 0,-1);
796 wfProfileOut( $fname );
801 * Helper function for doAllQuotes()
804 function doQuotes( $text ) {
805 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
806 if ( count( $arr ) == 1 )
810 # First, do some preliminary work. This may shift some apostrophes from
811 # being mark-up to being text. It also counts the number of occurrences
812 # of bold and italics mark-ups.
816 foreach ( $arr as $r )
818 if ( ( $i %
2 ) == 1 )
820 # If there are ever four apostrophes, assume the first is supposed to
821 # be text, and the remaining three constitute mark-up for bold text.
822 if ( strlen( $arr[$i] ) == 4 )
827 # If there are more than 5 apostrophes in a row, assume they're all
828 # text except for the last 5.
829 else if ( strlen( $arr[$i] ) > 5 )
831 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
834 # Count the number of occurrences of bold and italics mark-ups.
835 # We are not counting sequences of five apostrophes.
836 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
837 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
838 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
843 # If there is an odd number of both bold and italics, it is likely
844 # that one of the bold ones was meant to be an apostrophe followed
845 # by italics. Which one we cannot know for certain, but it is more
846 # likely to be one that has a single-letter word before it.
847 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
850 $firstsingleletterword = -1;
851 $firstmultiletterword = -1;
853 foreach ( $arr as $r )
855 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
857 $x1 = substr ($arr[$i-1], -1);
858 $x2 = substr ($arr[$i-1], -2, 1);
860 if ($firstspace == -1) $firstspace = $i;
861 } else if ($x2 == ' ') {
862 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
864 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
870 # If there is a single-letter word, use it!
871 if ($firstsingleletterword > -1)
873 $arr [ $firstsingleletterword ] = "''";
874 $arr [ $firstsingleletterword-1 ] .= "'";
876 # If not, but there's a multi-letter word, use that one.
877 else if ($firstmultiletterword > -1)
879 $arr [ $firstmultiletterword ] = "''";
880 $arr [ $firstmultiletterword-1 ] .= "'";
882 # ... otherwise use the first one that has neither.
883 # (notice that it is possible for all three to be -1 if, for example,
884 # there is only one pentuple-apostrophe in the line)
885 else if ($firstspace > -1)
887 $arr [ $firstspace ] = "''";
888 $arr [ $firstspace-1 ] .= "'";
892 # Now let's actually convert our apostrophic mush to HTML!
901 if ($state == 'both')
908 if (strlen ($r) == 2)
911 { $output .= '</i>'; $state = ''; }
912 else if ($state == 'bi')
913 { $output .= '</i>'; $state = 'b'; }
914 else if ($state == 'ib')
915 { $output .= '</b></i><b>'; $state = 'b'; }
916 else if ($state == 'both')
917 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
918 else # $state can be 'b' or ''
919 { $output .= '<i>'; $state .= 'i'; }
921 else if (strlen ($r) == 3)
924 { $output .= '</b>'; $state = ''; }
925 else if ($state == 'bi')
926 { $output .= '</i></b><i>'; $state = 'i'; }
927 else if ($state == 'ib')
928 { $output .= '</b>'; $state = 'i'; }
929 else if ($state == 'both')
930 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
931 else # $state can be 'i' or ''
932 { $output .= '<b>'; $state .= 'b'; }
934 else if (strlen ($r) == 5)
937 { $output .= '</b><i>'; $state = 'i'; }
938 else if ($state == 'i')
939 { $output .= '</i><b>'; $state = 'b'; }
940 else if ($state == 'bi')
941 { $output .= '</i></b>'; $state = ''; }
942 else if ($state == 'ib')
943 { $output .= '</b></i>'; $state = ''; }
944 else if ($state == 'both')
945 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
946 else # ($state == '')
947 { $buffer = ''; $state = 'both'; }
952 # Now close all remaining tags. Notice that the order is important.
953 if ($state == 'b' ||
$state == 'ib')
955 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
959 if ($state == 'both')
960 $output .= '<b><i>'.$buffer.'</i></b>';
966 * Replace external links
968 * Note: this is all very hackish and the order of execution matters a lot.
969 * Make sure to run maintenance/parserTests.php if you change this code.
973 function replaceExternalLinks( $text ) {
975 $fname = 'Parser::replaceExternalLinks';
976 wfProfileIn( $fname );
978 $sk =& $this->mOptions
->getSkin();
980 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
982 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
985 while ( $i<count( $bits ) ) {
987 $protocol = $bits[$i++
];
989 $trail = $bits[$i++
];
991 # The characters '<' and '>' (which were escaped by
992 # removeHTMLtags()) should not be included in
993 # URLs, per RFC 2396.
994 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
995 $text = substr($url, $m2[0][1]) . ' ' . $text;
996 $url = substr($url, 0, $m2[0][1]);
999 # If the link text is an image URL, replace it with an <img> tag
1000 # This happened by accident in the original parser, but some people used it extensively
1001 $img = $this->maybeMakeExternalImage( $text );
1002 if ( $img !== false ) {
1008 # Set linktype for CSS - if URL==text, link is essentially free
1009 $linktype = ($text == $url) ?
'free' : 'text';
1011 # No link text, e.g. [http://domain.tld/some.link]
1012 if ( $text == '' ) {
1013 # Autonumber if allowed
1014 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
1015 $text = '[' . ++
$this->mAutonumber
. ']';
1016 $linktype = 'autonumber';
1018 # Otherwise just use the URL
1019 $text = htmlspecialchars( $url );
1023 # Have link text, e.g. [http://domain.tld/some.link text]s
1025 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1028 $text = $wgContLang->markNoConversion($text);
1030 # Replace & from obsolete syntax with &.
1031 # All HTML entities will be escaped by makeExternalLink()
1032 # or maybeMakeExternalImage()
1033 $url = str_replace( '&', '&', $url );
1035 # Process the trail (i.e. everything after this link up until start of the next link),
1036 # replacing any non-bracketed links
1037 $trail = $this->replaceFreeExternalLinks( $trail );
1040 # Use the encoded URL
1041 # This means that users can paste URLs directly into the text
1042 # Funny characters like ö aren't valid in URLs anyway
1043 # This was changed in August 2004
1044 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1047 wfProfileOut( $fname );
1052 * Replace anything that looks like a URL with a link
1055 function replaceFreeExternalLinks( $text ) {
1057 $fname = 'Parser::replaceFreeExternalLinks';
1058 wfProfileIn( $fname );
1060 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1061 $s = array_shift( $bits );
1064 $sk =& $this->mOptions
->getSkin();
1066 while ( $i < count( $bits ) ){
1067 $protocol = $bits[$i++
];
1068 $remainder = $bits[$i++
];
1070 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1071 # Found some characters after the protocol that look promising
1072 $url = $protocol . $m[1];
1075 # The characters '<' and '>' (which were escaped by
1076 # removeHTMLtags()) should not be included in
1077 # URLs, per RFC 2396.
1078 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1079 $trail = substr($url, $m2[0][1]) . $trail;
1080 $url = substr($url, 0, $m2[0][1]);
1083 # Move trailing punctuation to $trail
1085 # If there is no left bracket, then consider right brackets fair game too
1086 if ( strpos( $url, '(' ) === false ) {
1090 $numSepChars = strspn( strrev( $url ), $sep );
1091 if ( $numSepChars ) {
1092 $trail = substr( $url, -$numSepChars ) . $trail;
1093 $url = substr( $url, 0, -$numSepChars );
1096 # Replace & from obsolete syntax with &.
1097 # All HTML entities will be escaped by makeExternalLink()
1098 # or maybeMakeExternalImage()
1099 $url = str_replace( '&', '&', $url );
1101 # Is this an external image?
1102 $text = $this->maybeMakeExternalImage( $url );
1103 if ( $text === false ) {
1104 # Not an image, make a link
1105 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1107 $s .= $text . $trail;
1109 $s .= $protocol . $remainder;
1117 * make an image if it's allowed
1120 function maybeMakeExternalImage( $url ) {
1121 $sk =& $this->mOptions
->getSkin();
1123 if ( $this->mOptions
->getAllowExternalImages() ) {
1124 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1126 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1133 * Process [[ ]] wikilinks
1137 function replaceInternalLinks( $s ) {
1138 global $wgContLang, $wgLinkCache;
1139 static $fname = 'Parser::replaceInternalLinks' ;
1141 wfProfileIn( $fname );
1143 wfProfileIn( $fname.'-setup' );
1145 # the % is needed to support urlencoded titles as well
1146 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1148 $sk =& $this->mOptions
->getSkin();
1150 #split the entire text string on occurences of [[
1151 $a = explode( '[[', ' ' . $s );
1152 #get the first element (all text up to first [[), and remove the space we added
1153 $s = array_shift( $a );
1154 $s = substr( $s, 1 );
1156 # Match a link having the form [[namespace:link|alternate]]trail
1158 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1159 # Match cases where there is no "]]", which might still be images
1160 static $e1_img = FALSE;
1161 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1162 # Match the end of a line for a word that's not followed by whitespace,
1163 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1164 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1166 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1168 if( is_null( $this->mTitle
) ) {
1169 wfDebugDieBacktrace( 'nooo' );
1171 $nottalk = !$this->mTitle
->isTalkPage();
1173 if ( $useLinkPrefixExtension ) {
1174 if ( preg_match( $e2, $s, $m ) ) {
1175 $first_prefix = $m[2];
1178 $first_prefix = false;
1184 $selflink = $this->mTitle
->getPrefixedText();
1185 wfProfileOut( $fname.'-setup' );
1187 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1188 $useSubpages = $this->areSubpagesAllowed();
1190 # Loop for each link
1191 for ($k = 0; isset( $a[$k] ); $k++
) {
1193 if ( $useLinkPrefixExtension ) {
1194 wfProfileIn( $fname.'-prefixhandling' );
1195 if ( preg_match( $e2, $s, $m ) ) {
1203 $prefix = $first_prefix;
1204 $first_prefix = false;
1206 wfProfileOut( $fname.'-prefixhandling' );
1209 $might_be_img = false;
1211 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1213 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1214 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1215 # the real problem is with the $e1 regex
1217 if (preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1218 $text .= ']'; # so that replaceExternalLinks($text) works later
1221 # fix up urlencoded title texts
1222 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1224 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1225 $might_be_img = true;
1227 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1229 } else { # Invalid form; output directly
1230 $s .= $prefix . '[[' . $line ;
1234 # Don't allow internal links to pages containing
1235 # PROTO: where PROTO is a valid URL protocol; these
1236 # should be external links.
1237 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1238 $s .= $prefix . '[[' . $line ;
1242 # Make subpage if necessary
1243 if( $useSubpages ) {
1244 $link = $this->maybeDoSubpageLink( $m[1], $text );
1249 $noforce = (substr($m[1], 0, 1) != ':');
1251 # Strip off leading ':'
1252 $link = substr($link, 1);
1255 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1257 $s .= $prefix . '[[' . $line;
1261 #check other language variants of the link
1262 #if the article does not exist
1263 if( $checkVariantLink
1264 && $nt->getArticleID() == 0 ) {
1265 $wgContLang->findVariantLink($link, $nt);
1268 $ns = $nt->getNamespace();
1269 $iw = $nt->getInterWiki();
1271 if ($might_be_img) { # if this is actually an invalid link
1272 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1274 while (isset ($a[$k+
1]) ) {
1275 #look at the next 'line' to see if we can close it there
1276 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1277 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1278 # the first ]] closes the inner link, the second the image
1280 $text .= '[[' . $m[1];
1283 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1284 #if there's exactly one ]] that's fine, we'll keep looking
1285 $text .= '[[' . $m[0];
1287 #if $next_line is invalid too, we need look no further
1288 $text .= '[[' . $next_line;
1293 # we couldn't find the end of this imageLink, so output it raw
1294 #but don't ignore what might be perfectly normal links in the text we've examined
1295 $text = $this->replaceInternalLinks($text);
1296 $s .= $prefix . '[[' . $link . '|' . $text;
1297 # note: no $trail, because without an end, there *is* no trail
1300 } else { #it's not an image, so output it raw
1301 $s .= $prefix . '[[' . $link . '|' . $text;
1302 # note: no $trail, because without an end, there *is* no trail
1307 $wasblank = ( '' == $text );
1308 if( $wasblank ) $text = $link;
1311 # Link not escaped by : , create the various objects
1315 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1316 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1317 $s = rtrim($s . "\n");
1318 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1322 if ( $ns == NS_IMAGE
) {
1323 wfProfileIn( "$fname-image" );
1324 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1325 # recursively parse links inside the image caption
1326 # actually, this will parse them in any other parameters, too,
1327 # but it might be hard to fix that, and it doesn't matter ATM
1328 $text = $this->replaceExternalLinks($text);
1329 $text = $this->replaceInternalLinks($text);
1331 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1332 $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
1333 $wgLinkCache->addImageLinkObj( $nt );
1335 wfProfileOut( "$fname-image" );
1338 wfProfileOut( "$fname-image" );
1342 if ( $ns == NS_CATEGORY
) {
1343 wfProfileIn( "$fname-category" );
1344 $t = $nt->getText();
1345 $s = rtrim($s . "\n"); # bug 87
1347 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1348 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1349 $wgLinkCache->resume();
1352 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1353 $sortkey = $this->mTitle
->getText();
1355 $sortkey = $this->mTitle
->getPrefixedText();
1360 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1361 $this->mOutput
->addCategoryLink( $t );
1364 * Strip the whitespace Category links produce, see bug 87
1365 * @todo We might want to use trim($tmp, "\n") here.
1367 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1369 wfProfileOut( "$fname-category" );
1374 if( ( $nt->getPrefixedText() === $selflink ) &&
1375 ( $nt->getFragment() === '' ) ) {
1376 # Self-links are handled specially; generally de-link and change to bold.
1377 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1381 # Special and Media are pseudo-namespaces; no pages actually exist in them
1382 if( $ns == NS_MEDIA
) {
1383 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1384 $wgLinkCache->addImageLinkObj( $nt );
1386 } elseif( $ns == NS_SPECIAL
) {
1387 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1390 if ( $nt->isAlwaysKnown() ) {
1391 $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
1394 * Add a link placeholder
1395 * Later, this will be replaced by a real link, after the existence or
1396 * non-existence of all the links is known
1398 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1401 wfProfileOut( $fname );
1406 * Make a link placeholder. The text returned can be later resolved to a real link with
1407 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1408 * parsing of interwiki links, and secondly to allow all extistence checks and
1409 * article length checks (for stub links) to be bundled into a single query.
1412 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1413 if ( ! is_object($nt) ) {
1415 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1417 # Separate the link trail from the rest of the link
1418 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1420 if ( $nt->isExternal() ) {
1421 $iwRecord = array( $nt->getPrefixedDBkey(), $prefix.$text.$inside );
1422 $nr = array_push($this->mInterwikiLinkHolders
, $iwRecord);
1423 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1425 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1426 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1427 $this->mLinkHolders
['queries'][] = $query;
1428 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1429 $this->mLinkHolders
['titles'][] =& $nt;
1431 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1438 * Return true if subpage links should be expanded on this page.
1441 function areSubpagesAllowed() {
1442 # Some namespaces don't allow subpages
1443 global $wgNamespacesWithSubpages;
1444 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1448 * Handle link to subpage if necessary
1449 * @param string $target the source of the link
1450 * @param string &$text the link text, modified as necessary
1451 * @return string the full name of the link
1454 function maybeDoSubpageLink($target, &$text) {
1457 # :Foobar -- override special treatment of prefix (images, language links)
1458 # /Foobar -- convert to CurrentPage/Foobar
1459 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1460 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1461 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1463 $fname = 'Parser::maybeDoSubpageLink';
1464 wfProfileIn( $fname );
1465 $ret = $target; # default return value is no change
1467 # Some namespaces don't allow subpages,
1468 # so only perform processing if subpages are allowed
1469 if( $this->areSubpagesAllowed() ) {
1470 # Look at the first character
1471 if( $target != '' && $target{0} == '/' ) {
1472 # / at end means we don't want the slash to be shown
1473 if( substr( $target, -1, 1 ) == '/' ) {
1474 $target = substr( $target, 1, -1 );
1477 $noslash = substr( $target, 1 );
1480 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1481 if( '' === $text ) {
1483 } # this might be changed for ugliness reasons
1485 # check for .. subpage backlinks
1487 $nodotdot = $target;
1488 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1490 $nodotdot = substr( $nodotdot, 3 );
1492 if($dotdotcount > 0) {
1493 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1494 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1495 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1496 # / at the end means don't show full path
1497 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1498 $nodotdot = substr( $nodotdot, 0, -1 );
1499 if( '' === $text ) {
1503 $nodotdot = trim( $nodotdot );
1504 if( $nodotdot != '' ) {
1505 $ret .= '/' . $nodotdot;
1512 wfProfileOut( $fname );
1517 * Used by doBlockLevels()
1520 /* private */ function closeParagraph() {
1522 if ( '' != $this->mLastSection
) {
1523 $result = '</' . $this->mLastSection
. ">\n";
1525 $this->mInPre
= false;
1526 $this->mLastSection
= '';
1529 # getCommon() returns the length of the longest common substring
1530 # of both arguments, starting at the beginning of both.
1532 /* private */ function getCommon( $st1, $st2 ) {
1533 $fl = strlen( $st1 );
1534 $shorter = strlen( $st2 );
1535 if ( $fl < $shorter ) { $shorter = $fl; }
1537 for ( $i = 0; $i < $shorter; ++
$i ) {
1538 if ( $st1{$i} != $st2{$i} ) { break; }
1542 # These next three functions open, continue, and close the list
1543 # element appropriate to the prefix character passed into them.
1545 /* private */ function openList( $char ) {
1546 $result = $this->closeParagraph();
1548 if ( '*' == $char ) { $result .= '<ul><li>'; }
1549 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1550 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1551 else if ( ';' == $char ) {
1552 $result .= '<dl><dt>';
1553 $this->mDTopen
= true;
1555 else { $result = '<!-- ERR 1 -->'; }
1560 /* private */ function nextItem( $char ) {
1561 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1562 else if ( ':' == $char ||
';' == $char ) {
1564 if ( $this->mDTopen
) { $close = '</dt>'; }
1565 if ( ';' == $char ) {
1566 $this->mDTopen
= true;
1567 return $close . '<dt>';
1569 $this->mDTopen
= false;
1570 return $close . '<dd>';
1573 return '<!-- ERR 2 -->';
1576 /* private */ function closeList( $char ) {
1577 if ( '*' == $char ) { $text = '</li></ul>'; }
1578 else if ( '#' == $char ) { $text = '</li></ol>'; }
1579 else if ( ':' == $char ) {
1580 if ( $this->mDTopen
) {
1581 $this->mDTopen
= false;
1582 $text = '</dt></dl>';
1584 $text = '</dd></dl>';
1587 else { return '<!-- ERR 3 -->'; }
1593 * Make lists from lines starting with ':', '*', '#', etc.
1596 * @return string the lists rendered as HTML
1598 function doBlockLevels( $text, $linestart ) {
1599 $fname = 'Parser::doBlockLevels';
1600 wfProfileIn( $fname );
1602 # Parsing through the text line by line. The main thing
1603 # happening here is handling of block-level elements p, pre,
1604 # and making lists from lines starting with * # : etc.
1606 $textLines = explode( "\n", $text );
1608 $lastPrefix = $output = '';
1609 $this->mDTopen
= $inBlockElem = false;
1611 $paragraphStack = false;
1613 if ( !$linestart ) {
1614 $output .= array_shift( $textLines );
1616 foreach ( $textLines as $oLine ) {
1617 $lastPrefixLength = strlen( $lastPrefix );
1618 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1619 $preOpenMatch = preg_match('/<pre/i', $oLine );
1620 if ( !$this->mInPre
) {
1621 # Multiple prefixes may abut each other for nested lists.
1622 $prefixLength = strspn( $oLine, '*#:;' );
1623 $pref = substr( $oLine, 0, $prefixLength );
1626 $pref2 = str_replace( ';', ':', $pref );
1627 $t = substr( $oLine, $prefixLength );
1628 $this->mInPre
= !empty($preOpenMatch);
1630 # Don't interpret any other prefixes in preformatted text
1632 $pref = $pref2 = '';
1637 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1638 # Same as the last item, so no need to deal with nesting or opening stuff
1639 $output .= $this->nextItem( substr( $pref, -1 ) );
1640 $paragraphStack = false;
1642 if ( substr( $pref, -1 ) == ';') {
1643 # The one nasty exception: definition lists work like this:
1644 # ; title : definition text
1645 # So we check for : in the remainder text to split up the
1646 # title and definition, without b0rking links.
1648 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1650 $output .= $term . $this->nextItem( ':' );
1653 } elseif( $prefixLength ||
$lastPrefixLength ) {
1654 # Either open or close a level...
1655 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1656 $paragraphStack = false;
1658 while( $commonPrefixLength < $lastPrefixLength ) {
1659 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1660 --$lastPrefixLength;
1662 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1663 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1665 while ( $prefixLength > $commonPrefixLength ) {
1666 $char = substr( $pref, $commonPrefixLength, 1 );
1667 $output .= $this->openList( $char );
1669 if ( ';' == $char ) {
1670 # FIXME: This is dupe of code above
1671 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1673 $output .= $term . $this->nextItem( ':' );
1676 ++
$commonPrefixLength;
1678 $lastPrefix = $pref2;
1680 if( 0 == $prefixLength ) {
1681 wfProfileIn( "$fname-paragraph" );
1682 # No prefix (not in list)--go to paragraph mode
1683 $uniq_prefix = UNIQ_PREFIX
;
1684 // XXX: use a stack for nestable elements like span, table and div
1685 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1686 $closematch = preg_match(
1687 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1688 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1689 if ( $openmatch or $closematch ) {
1690 $paragraphStack = false;
1691 $output .= $this->closeParagraph();
1692 if($preOpenMatch and !$preCloseMatch) {
1693 $this->mInPre
= true;
1695 if ( $closematch ) {
1696 $inBlockElem = false;
1698 $inBlockElem = true;
1700 } else if ( !$inBlockElem && !$this->mInPre
) {
1701 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1703 if ($this->mLastSection
!= 'pre') {
1704 $paragraphStack = false;
1705 $output .= $this->closeParagraph().'<pre>';
1706 $this->mLastSection
= 'pre';
1708 $t = substr( $t, 1 );
1711 if ( '' == trim($t) ) {
1712 if ( $paragraphStack ) {
1713 $output .= $paragraphStack.'<br />';
1714 $paragraphStack = false;
1715 $this->mLastSection
= 'p';
1717 if ($this->mLastSection
!= 'p' ) {
1718 $output .= $this->closeParagraph();
1719 $this->mLastSection
= '';
1720 $paragraphStack = '<p>';
1722 $paragraphStack = '</p><p>';
1726 if ( $paragraphStack ) {
1727 $output .= $paragraphStack;
1728 $paragraphStack = false;
1729 $this->mLastSection
= 'p';
1730 } else if ($this->mLastSection
!= 'p') {
1731 $output .= $this->closeParagraph().'<p>';
1732 $this->mLastSection
= 'p';
1737 wfProfileOut( "$fname-paragraph" );
1739 if ($paragraphStack === false) {
1743 while ( $prefixLength ) {
1744 $output .= $this->closeList( $pref2{$prefixLength-1} );
1747 if ( '' != $this->mLastSection
) {
1748 $output .= '</' . $this->mLastSection
. '>';
1749 $this->mLastSection
= '';
1752 wfProfileOut( $fname );
1757 * Split up a string on ':', ignoring any occurences inside
1758 * <a>..</a> or <span>...</span>
1759 * @param string $str the string to split
1760 * @param string &$before set to everything before the ':'
1761 * @param string &$after set to everything after the ':'
1762 * return string the position of the ':', or false if none found
1764 function findColonNoLinks($str, &$before, &$after) {
1765 # I wonder if we should make this count all tags, not just <a>
1766 # and <span>. That would prevent us from matching a ':' that
1767 # comes in the middle of italics other such formatting....
1769 $fname = 'Parser::findColonNoLinks';
1770 wfProfileIn( $fname );
1773 $colon = strpos($str, ':', $pos);
1775 if ($colon !== false) {
1776 $before = substr($str, 0, $colon);
1777 $after = substr($str, $colon +
1);
1779 # Skip any ':' within <a> or <span> pairs
1780 $a = substr_count($before, '<a');
1781 $s = substr_count($before, '<span');
1782 $ca = substr_count($before, '</a>');
1783 $cs = substr_count($before, '</span>');
1785 if ($a <= $ca and $s <= $cs) {
1786 # Tags are balanced before ':'; ok
1791 } while ($colon !== false);
1792 wfProfileOut( $fname );
1797 * Return value of a magic variable (like PAGENAME)
1801 function getVariableValue( $index ) {
1802 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1805 * Some of these require message or data lookups and can be
1806 * expensive to check many times.
1808 static $varCache = array();
1809 if( isset( $varCache[$index] ) ) return $varCache[$index];
1812 case MAG_CURRENTMONTH
:
1813 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1814 case MAG_CURRENTMONTHNAME
:
1815 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1816 case MAG_CURRENTMONTHNAMEGEN
:
1817 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1818 case MAG_CURRENTMONTHABBREV
:
1819 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1820 case MAG_CURRENTDAY
:
1821 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1823 return $this->mTitle
->getText();
1825 return $this->mTitle
->getPartialURL();
1826 case MAG_REVISIONID
:
1827 return $wgArticle->getRevIdFetched();
1829 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1830 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1831 case MAG_CURRENTDAYNAME
:
1832 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1833 case MAG_CURRENTYEAR
:
1834 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1835 case MAG_CURRENTTIME
:
1836 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1837 case MAG_CURRENTWEEK
:
1838 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1839 case MAG_CURRENTDOW
:
1840 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1841 case MAG_NUMBEROFARTICLES
:
1842 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1853 * initialise the magic variables (like CURRENTMONTHNAME)
1857 function initialiseVariables() {
1858 $fname = 'Parser::initialiseVariables';
1859 wfProfileIn( $fname );
1860 global $wgVariableIDs;
1861 $this->mVariables
= array();
1862 foreach ( $wgVariableIDs as $id ) {
1863 $mw =& MagicWord
::get( $id );
1864 $mw->addToArray( $this->mVariables
, $id );
1866 wfProfileOut( $fname );
1870 * Replace magic variables, templates, and template arguments
1871 * with the appropriate text. Templates are substituted recursively,
1872 * taking care to avoid infinite loops.
1874 * Note that the substitution depends on value of $mOutputType:
1875 * OT_WIKI: only {{subst:}} templates
1876 * OT_MSG: only magic variables
1877 * OT_HTML: all templates and magic variables
1879 * @param string $tex The text to transform
1880 * @param array $args Key-value pairs representing template parameters to substitute
1883 function replaceVariables( $text, $args = array() ) {
1885 # Prevent too big inclusions
1886 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1890 $fname = 'Parser::replaceVariables';
1891 wfProfileIn( $fname );
1893 $titleChars = Title
::legalChars();
1895 # This function is called recursively. To keep track of arguments we need a stack:
1896 array_push( $this->mArgStack
, $args );
1898 # Variable substitution
1899 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1901 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1902 # Argument substitution
1903 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1905 # Template substitution
1906 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1907 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1909 array_pop( $this->mArgStack
);
1911 wfProfileOut( $fname );
1916 * Replace magic variables
1919 function variableSubstitution( $matches ) {
1920 $fname = 'parser::variableSubstitution';
1921 $varname = $matches[1];
1922 wfProfileIn( $fname );
1923 if ( !$this->mVariables
) {
1924 $this->initialiseVariables();
1927 if ( $this->mOutputType
== OT_WIKI
) {
1928 # Do only magic variables prefixed by SUBST
1929 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1930 if (!$mwSubst->matchStartAndRemove( $varname ))
1932 # Note that if we don't substitute the variable below,
1933 # we don't remove the {{subst:}} magic word, in case
1934 # it is a template rather than a magic variable.
1936 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1937 $id = $this->mVariables
[$varname];
1938 $text = $this->getVariableValue( $id );
1939 $this->mOutput
->mContainsOldMagic
= true;
1941 $text = $matches[0];
1943 wfProfileOut( $fname );
1947 # Split template arguments
1948 function getTemplateArgs( $argsString ) {
1949 if ( $argsString === '' ) {
1953 $args = explode( '|', substr( $argsString, 1 ) );
1955 # If any of the arguments contains a '[[' but no ']]', it needs to be
1956 # merged with the next arg because the '|' character between belongs
1957 # to the link syntax and not the template parameter syntax.
1958 $argc = count($args);
1960 for ( $i = 0; $i < $argc-1; $i++
) {
1961 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1962 $args[$i] .= '|'.$args[$i+
1];
1963 array_splice($args, $i+
1, 1);
1973 * Return the text of a template, after recursively
1974 * replacing any variables or templates within the template.
1976 * @param array $matches The parts of the template
1977 * $matches[1]: the title, i.e. the part before the |
1978 * $matches[2]: the parameters (including a leading |), if any
1979 * @return string the text of the template
1982 function braceSubstitution( $matches ) {
1983 global $wgLinkCache, $wgContLang;
1984 $fname = 'Parser::braceSubstitution';
1985 wfProfileIn( $fname );
1993 # Need to know if the template comes at the start of a line,
1994 # to treat the beginning of the template like the beginning
1995 # of a line for tables and block-level elements.
1996 $linestart = $matches[1];
1998 # $part1 is the bit before the first |, and must contain only title characters
1999 # $args is a list of arguments, starting from index 0, not including $part1
2001 $part1 = $matches[2];
2002 # If the third subpattern matched anything, it will start with |
2004 $args = $this->getTemplateArgs($matches[3]);
2005 $argc = count( $args );
2007 # Don't parse {{{}}} because that's only for template arguments
2008 if ( $linestart === '{' ) {
2009 $text = $matches[0];
2016 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2017 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2018 # One of two possibilities is true:
2019 # 1) Found SUBST but not in the PST phase
2020 # 2) Didn't find SUBST and in the PST phase
2021 # In either case, return without further processing
2022 $text = $matches[0];
2028 # MSG, MSGNW and INT
2031 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2032 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2035 # Remove obsolete MSG:
2036 $mwMsg =& MagicWord
::get( MAG_MSG
);
2037 $mwMsg->matchStartAndRemove( $part1 );
2040 # Check if it is an internal message
2041 $mwInt =& MagicWord
::get( MAG_INT
);
2042 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2043 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2044 $text = $linestart . wfMsgReal( $part1, $args, true );
2052 # Check for NS: (namespace expansion)
2053 $mwNs = MagicWord
::get( MAG_NS
);
2054 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2055 if ( intval( $part1 ) ) {
2056 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2059 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2060 if ( !is_null( $index ) ) {
2061 $text = $linestart . $wgContLang->getNsText( $index );
2068 # LOCALURL and LOCALURLE
2070 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2071 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2073 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2074 $func = 'getLocalURL';
2075 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2076 $func = 'escapeLocalURL';
2081 if ( $func !== '' ) {
2082 $title = Title
::newFromText( $part1 );
2083 if ( !is_null( $title ) ) {
2085 $text = $linestart . $title->$func( $args[0] );
2087 $text = $linestart . $title->$func();
2095 if ( !$found && $argc == 1 ) {
2096 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2097 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2098 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2103 # Template table test
2105 # Did we encounter this template already? If yes, it is in the cache
2106 # and we need to check for loops.
2107 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2110 # Infinite loop test
2111 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2114 $text = $linestart .
2116 '<!-- WARNING: template loop detected -->';
2117 wfDebug( "$fname: template loop broken at '$part1'\n" );
2119 # set $text to cached message.
2120 $text = $linestart . $this->mTemplates
[$part1];
2124 # Load from database
2125 $itcamefromthedatabase = false;
2126 $lastPathLevel = $this->mTemplatePath
;
2129 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2130 if ($subpage !== '') {
2131 $ns = $this->mTitle
->getNamespace();
2133 $title = Title
::newFromText( $part1, $ns );
2134 if ( !is_null( $title ) && !$title->isExternal() ) {
2135 # Check for excessive inclusion
2136 $dbk = $title->getPrefixedDBkey();
2137 if ( $this->incrementIncludeCount( $dbk ) ) {
2138 # This should never be reached.
2139 $article = new Article( $title );
2140 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2141 if ( $articleContent !== false ) {
2143 $text = $linestart . $articleContent;
2144 $itcamefromthedatabase = true;
2148 # If the title is valid but undisplayable, make a link to it
2149 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2150 $text = $linestart . '[['.$title->getPrefixedText().']]';
2154 # Template cache array insertion
2156 $this->mTemplates
[$part1] = $text;
2161 # Recursive parsing, escaping and link table handling
2162 # Only for HTML output
2163 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2164 $text = wfEscapeWikiText( $text );
2165 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2166 # Clean up argument array
2167 $assocArgs = array();
2169 foreach( $args as $arg ) {
2170 $eqpos = strpos( $arg, '=' );
2171 if ( $eqpos === false ) {
2172 $assocArgs[$index++
] = $arg;
2174 $name = trim( substr( $arg, 0, $eqpos ) );
2175 $value = trim( substr( $arg, $eqpos+
1 ) );
2176 if ( $value === false ) {
2179 if ( $name !== false ) {
2180 $assocArgs[$name] = $value;
2185 # Add a new element to the templace recursion path
2186 $this->mTemplatePath
[$part1] = 1;
2188 if( $this->mOutputType
== OT_HTML
) {
2189 $text = $this->strip( $text, $this->mStripState
);
2190 $text = Sanitizer
::removeHTMLtags( $text );
2192 $text = $this->replaceVariables( $text, $assocArgs );
2194 # Resume the link cache and register the inclusion as a link
2195 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2196 $wgLinkCache->addLinkObj( $title );
2199 # If the template begins with a table or block-level
2200 # element, it should be treated as beginning a new line.
2201 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2202 $text = "\n" . $text;
2205 # Prune lower levels off the recursion check path
2206 $this->mTemplatePath
= $lastPathLevel;
2209 wfProfileOut( $fname );
2212 # replace ==section headers==
2213 # XXX this needs to go away once we have a better parser.
2214 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2215 if( !is_null( $title ) )
2216 $encodedname = base64_encode($title->getPrefixedDBkey());
2218 $encodedname = base64_encode("");
2219 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2220 PREG_SPLIT_DELIM_CAPTURE
);
2223 for( $i = 0; $i < count($m); $i +
= 2 ) {
2225 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2227 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2231 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2232 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2233 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2239 # Prune lower levels off the recursion check path
2240 $this->mTemplatePath
= $lastPathLevel;
2243 wfProfileOut( $fname );
2246 wfProfileOut( $fname );
2252 * Triple brace replacement -- used for template arguments
2255 function argSubstitution( $matches ) {
2256 $arg = trim( $matches[1] );
2257 $text = $matches[0];
2258 $inputArgs = end( $this->mArgStack
);
2260 if ( array_key_exists( $arg, $inputArgs ) ) {
2261 $text = $inputArgs[$arg];
2268 * Returns true if the function is allowed to include this entity
2271 function incrementIncludeCount( $dbk ) {
2272 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2273 $this->mIncludeCount
[$dbk] = 0;
2275 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2283 * This function accomplishes several tasks:
2284 * 1) Auto-number headings if that option is enabled
2285 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2286 * 3) Add a Table of contents on the top for users who have enabled the option
2287 * 4) Auto-anchor headings
2289 * It loops through all headlines, collects the necessary data, then splits up the
2290 * string and re-inserts the newly formatted headlines.
2292 * @param string $text
2293 * @param boolean $isMain
2296 function formatHeadings( $text, $isMain=true ) {
2297 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2299 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2301 $forceTocHere = false;
2302 if( !$this->mTitle
->userCanEdit() ) {
2305 $showEditLink = $this->mOptions
->getEditSection();
2308 # Inhibit editsection links if requested in the page
2309 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2310 if( $esw->matchAndRemove( $text ) ) {
2313 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2315 $mw =& MagicWord
::get( MAG_NOTOC
);
2316 if( $mw->matchAndRemove( $text ) ) {
2320 # Get all headlines for numbering them and adding funky stuff like [edit]
2321 # links - this is for later, but we need the number of headlines right now
2322 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2324 # if there are fewer than 4 headlines in the article, do not show TOC
2325 if( $numMatches < 4 ) {
2329 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2330 # override above conditions and always show TOC at that place
2332 $mw =& MagicWord
::get( MAG_TOC
);
2333 if($mw->match( $text ) ) {
2335 $forceTocHere = true;
2337 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2338 # override above conditions and always show TOC above first header
2339 $mw =& MagicWord
::get( MAG_FORCETOC
);
2340 if ($mw->matchAndRemove( $text ) ) {
2345 # Never ever show TOC if no headers
2346 if( $numMatches < 1 ) {
2350 # We need this to perform operations on the HTML
2351 $sk =& $this->mOptions
->getSkin();
2355 $sectionCount = 0; # headlineCount excluding template sections
2357 # Ugh .. the TOC should have neat indentation levels which can be
2358 # passed to the skin functions. These are determined here
2362 $sublevelCount = array();
2363 $levelCount = array();
2370 foreach( $matches[3] as $headline ) {
2372 $templatetitle = '';
2373 $templatesection = 0;
2376 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2378 $templatetitle = base64_decode($mat[1]);
2379 $templatesection = 1 +
(int)base64_decode($mat[2]);
2380 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2384 $prevlevel = $level;
2385 $prevtoclevel = $toclevel;
2387 $level = $matches[1][$headlineCount];
2389 if( $doNumberHeadings ||
$doShowToc ) {
2391 if ( $level > $prevlevel ) {
2392 # Increase TOC level
2394 $sublevelCount[$toclevel] = 0;
2395 $toc .= $sk->tocIndent();
2397 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2398 # Decrease TOC level, find level to jump to
2400 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2401 # Can only go down to level 1
2404 for ($i = $toclevel; $i > 0; $i--) {
2405 if ( $levelCount[$i] == $level ) {
2406 # Found last matching level
2410 elseif ( $levelCount[$i] < $level ) {
2411 # Found first matching level below current level
2418 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2421 # No change in level, end TOC line
2422 $toc .= $sk->tocLineEnd();
2425 $levelCount[$toclevel] = $level;
2427 # count number of headlines for each level
2428 @$sublevelCount[$toclevel]++
;
2430 for( $i = 1; $i <= $toclevel; $i++
) {
2431 if( !empty( $sublevelCount[$i] ) ) {
2435 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2441 # The canonized header is a version of the header text safe to use for links
2442 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2443 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2444 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2446 # Remove link placeholders by the link text.
2447 # <!--LINK number-->
2449 # link text with suffix
2450 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2451 "\$this->mLinkHolders['texts'][\$1]",
2452 $canonized_headline );
2453 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2454 "\$this->mInterwikiLinkHolders[\$1][1]",
2455 $canonized_headline );
2458 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2459 $tocline = trim( $canonized_headline );
2460 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2461 $replacearray = array(
2465 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2466 $refers[$headlineCount] = $canonized_headline;
2468 # count how many in assoc. array so we can track dupes in anchors
2469 @$refers[$canonized_headline]++
;
2470 $refcount[$headlineCount]=$refers[$canonized_headline];
2472 # Don't number the heading if it is the only one (looks silly)
2473 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2474 # the two are different if the line contains a link
2475 $headline=$numbering . ' ' . $headline;
2478 # Create the anchor for linking from the TOC to the section
2479 $anchor = $canonized_headline;
2480 if($refcount[$headlineCount] > 1 ) {
2481 $anchor .= '_' . $refcount[$headlineCount];
2483 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2484 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2486 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2487 if ( empty( $head[$headlineCount] ) ) {
2488 $head[$headlineCount] = '';
2491 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2493 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2496 # give headline the correct <h#> tag
2497 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2505 $toc .= $sk->tocUnindent( $toclevel - 1 );
2506 $toc = $sk->tocList( $toc );
2509 # split up and insert constructed headlines
2511 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2514 foreach( $blocks as $block ) {
2515 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2516 # This is the [edit] link that appears for the top block of text when
2517 # section editing is enabled
2519 # Disabled because it broke block formatting
2520 # For example, a bullet point in the top line
2521 # $full .= $sk->editSectionLink(0);
2524 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2525 # Top anchor now in skin
2529 if( !empty( $head[$i] ) ) {
2535 $mw =& MagicWord
::get( MAG_TOC
);
2536 return $mw->replace( $toc, $full );
2543 * Return an HTML link for the "ISBN 123456" text
2546 function magicISBN( $text ) {
2547 $fname = 'Parser::magicISBN';
2548 wfProfileIn( $fname );
2550 $a = split( 'ISBN ', ' '.$text );
2551 if ( count ( $a ) < 2 ) {
2552 wfProfileOut( $fname );
2555 $text = substr( array_shift( $a ), 1);
2556 $valid = '0123456789-Xx';
2558 foreach ( $a as $x ) {
2559 $isbn = $blank = '' ;
2560 while ( ' ' == $x{0} ) {
2562 $x = substr( $x, 1 );
2564 if ( $x == '' ) { # blank isbn
2565 $text .= "ISBN $blank";
2568 while ( strstr( $valid, $x{0} ) != false ) {
2570 $x = substr( $x, 1 );
2572 $num = str_replace( '-', '', $isbn );
2573 $num = str_replace( ' ', '', $num );
2574 $num = str_replace( 'x', 'X', $num );
2577 $text .= "ISBN $blank$x";
2579 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2580 $text .= '<a href="' .
2581 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2582 "\" class=\"internal\">ISBN $isbn</a>";
2586 wfProfileOut( $fname );
2591 * Return an HTML link for the "RFC 1234" text
2594 * @param string $text Text to be processed
2595 * @param string $keyword Magic keyword to use (default RFC)
2596 * @param string $urlmsg Interface message to use (default rfcurl)
2599 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2601 $valid = '0123456789';
2604 $a = split( $keyword, ' '.$text );
2605 if ( count ( $a ) < 2 ) {
2608 $text = substr( array_shift( $a ), 1);
2610 /* Check if keyword is preceed by [[.
2611 * This test is made here cause of the array_shift above
2612 * that prevent the test to be done in the foreach.
2614 if ( substr( $text, -2 ) == '[[' ) {
2618 foreach ( $a as $x ) {
2619 /* token might be empty if we have RFC RFC 1234 */
2627 /** remove and save whitespaces in $blank */
2628 while ( $x{0} == ' ' ) {
2630 $x = substr( $x, 1 );
2633 /** remove and save the rfc number in $id */
2634 while ( strstr( $valid, $x{0} ) != false ) {
2636 $x = substr( $x, 1 );
2640 /* call back stripped spaces*/
2641 $text .= $keyword.$blank.$x;
2642 } elseif( $internal ) {
2644 $text .= $keyword.$id.$x;
2646 /* build the external link*/
2647 $url = wfMsg( $urlmsg, $id);
2648 $sk =& $this->mOptions
->getSkin();
2649 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2650 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2653 /* Check if the next RFC keyword is preceed by [[ */
2654 $internal = ( substr($x,-2) == '[[' );
2660 * Transform wiki markup when saving a page by doing \r\n -> \n
2661 * conversion, substitting signatures, {{subst:}} templates, etc.
2663 * @param string $text the text to transform
2664 * @param Title &$title the Title object for the current article
2665 * @param User &$user the User object describing the current user
2666 * @param ParserOptions $options parsing options
2667 * @param bool $clearState whether to clear the parser state first
2668 * @return string the altered wiki markup
2671 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2672 $this->mOptions
= $options;
2673 $this->mTitle
=& $title;
2674 $this->mOutputType
= OT_WIKI
;
2676 if ( $clearState ) {
2677 $this->clearState();
2680 $stripState = false;
2684 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2685 $text = $this->strip( $text, $stripState, false );
2686 $text = $this->pstPass2( $text, $user );
2687 $text = $this->unstrip( $text, $stripState );
2688 $text = $this->unstripNoWiki( $text, $stripState );
2693 * Pre-save transform helper function
2696 function pstPass2( $text, &$user ) {
2697 global $wgContLang, $wgLocaltimezone;
2699 # Variable replacement
2700 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2701 $text = $this->replaceVariables( $text );
2705 $n = $user->getName();
2706 $k = $user->getOption( 'nickname' );
2707 if ( '' == $k ) { $k = $n; }
2708 if ( isset( $wgLocaltimezone ) ) {
2709 $oldtz = getenv( 'TZ' );
2710 putenv( 'TZ='.$wgLocaltimezone );
2713 /* Note: This is the timestamp saved as hardcoded wikitext to
2714 * the database, we use $wgContLang here in order to give
2715 * everyone the same signiture and use the default one rather
2716 * than the one selected in each users preferences.
2718 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2719 ' (' . date( 'T' ) . ')';
2720 if ( isset( $wgLocaltimezone ) ) {
2721 putenv( 'TZ='.$oldtz );
2724 if( $user->getOption( 'fancysig' ) ) {
2727 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2729 $text = preg_replace( '/~~~~~/', $d, $text );
2730 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2731 $text = preg_replace( '/~~~/', $sigText, $text );
2733 # Context links: [[|name]] and [[name (context)|]]
2735 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2736 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2737 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2738 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2740 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2741 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2742 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2743 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2745 $t = $this->mTitle
->getText();
2746 if ( preg_match( $conpat, $t, $m ) ) {
2749 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2750 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2751 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2753 if ( '' == $context ) {
2754 $text = preg_replace( $p2, '[[\\1]]', $text );
2756 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2759 # Trim trailing whitespace
2760 # MAG_END (__END__) tag allows for trailing
2761 # whitespace to be deliberately included
2762 $text = rtrim( $text );
2763 $mw =& MagicWord
::get( MAG_END
);
2764 $mw->matchAndRemove( $text );
2770 * Set up some variables which are usually set up in parse()
2771 * so that an external function can call some class members with confidence
2774 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2775 $this->mTitle
=& $title;
2776 $this->mOptions
= $options;
2777 $this->mOutputType
= $outputType;
2778 if ( $clearState ) {
2779 $this->clearState();
2784 * Transform a MediaWiki message by replacing magic variables.
2786 * @param string $text the text to transform
2787 * @param ParserOptions $options options
2788 * @return string the text with variables substituted
2791 function transformMsg( $text, $options ) {
2793 static $executing = false;
2795 # Guard against infinite recursion
2801 $this->mTitle
= $wgTitle;
2802 $this->mOptions
= $options;
2803 $this->mOutputType
= OT_MSG
;
2804 $this->clearState();
2805 $text = $this->replaceVariables( $text );
2812 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2813 * Callback will be called with the text within
2814 * Transform and return the text within
2817 function setHook( $tag, $callback ) {
2818 $oldVal = @$this->mTagHooks
[$tag];
2819 $this->mTagHooks
[$tag] = $callback;
2824 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2825 * Placeholders created in Skin::makeLinkObj()
2826 * Returns an array of links found, indexed by PDBK:
2830 * $options is a bit field, RLH_FOR_UPDATE to select for update
2832 function replaceLinkHolders( &$text, $options = 0 ) {
2833 global $wgUser, $wgLinkCache;
2834 global $wgOutputReplace;
2836 $fname = 'Parser::replaceLinkHolders';
2837 wfProfileIn( $fname );
2841 $sk = $this->mOptions
->getSkin();
2843 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
2844 wfProfileIn( $fname.'-check' );
2845 $dbr =& wfGetDB( DB_SLAVE
);
2846 $page = $dbr->tableName( 'page' );
2847 $threshold = $wgUser->getOption('stubthreshold');
2850 asort( $this->mLinkHolders
['namespaces'] );
2854 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
2856 $title = $this->mLinkHolders
['titles'][$key];
2858 # Skip invalid entries.
2859 # Result will be ugly, but prevents crash.
2860 if ( is_null( $title ) ) {
2863 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2865 # Check if it's in the link cache already
2866 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2867 $colours[$pdbk] = 1;
2868 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2869 $colours[$pdbk] = 0;
2871 # Not in the link cache, add it to the query
2872 if ( !isset( $current ) ) {
2874 $query = "SELECT page_id, page_namespace, page_title";
2875 if ( $threshold > 0 ) {
2876 $query .= ', page_len, page_is_redirect';
2878 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2879 } elseif ( $current != $val ) {
2881 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2886 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
2891 if ( $options & RLH_FOR_UPDATE
) {
2892 $query .= ' FOR UPDATE';
2895 $res = $dbr->query( $query, $fname );
2897 # Fetch data and form into an associative array
2898 # non-existent = broken
2901 while ( $s = $dbr->fetchObject($res) ) {
2902 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2903 $pdbk = $title->getPrefixedDBkey();
2904 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
2906 if ( $threshold > 0 ) {
2907 $size = $s->page_len
;
2908 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
2909 $colours[$pdbk] = 1;
2911 $colours[$pdbk] = 2;
2914 $colours[$pdbk] = 1;
2918 wfProfileOut( $fname.'-check' );
2920 # Construct search and replace arrays
2921 wfProfileIn( $fname.'-construct' );
2922 $wgOutputReplace = array();
2923 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
2924 $pdbk = $pdbks[$key];
2925 $searchkey = "<!--LINK $key-->";
2926 $title = $this->mLinkHolders
['titles'][$key];
2927 if ( empty( $colours[$pdbk] ) ) {
2928 $wgLinkCache->addBadLink( $pdbk );
2929 $colours[$pdbk] = 0;
2930 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2931 $this->mLinkHolders
['texts'][$key],
2932 $this->mLinkHolders
['queries'][$key] );
2933 } elseif ( $colours[$pdbk] == 1 ) {
2934 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2935 $this->mLinkHolders
['texts'][$key],
2936 $this->mLinkHolders
['queries'][$key] );
2937 } elseif ( $colours[$pdbk] == 2 ) {
2938 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2939 $this->mLinkHolders
['texts'][$key],
2940 $this->mLinkHolders
['queries'][$key] );
2943 wfProfileOut( $fname.'-construct' );
2946 wfProfileIn( $fname.'-replace' );
2948 $text = preg_replace_callback(
2949 '/(<!--LINK .*?-->)/',
2950 "wfOutputReplaceMatches",
2953 wfProfileOut( $fname.'-replace' );
2956 # Now process interwiki link holders
2957 # This is quite a bit simpler than internal links
2958 if ( !empty( $this->mInterwikiLinkHolders
) ) {
2959 wfProfileIn( $fname.'-interwiki' );
2960 # Make interwiki link HTML
2961 $wgOutputReplace = array();
2962 foreach( $this->mInterwikiLinkHolders
as $i => $lh ) {
2963 $s = $sk->makeLink( $lh[0], $lh[1] );
2964 $wgOutputReplace[] = $s;
2967 $text = preg_replace_callback(
2968 '/<!--IWLINK (.*?)-->/',
2969 "wfOutputReplaceMatches",
2971 wfProfileOut( $fname.'-interwiki' );
2974 wfProfileOut( $fname );
2979 * Renders an image gallery from a text with one line per image.
2980 * text labels may be given by using |-style alternative text. E.g.
2981 * Image:one.jpg|The number "1"
2982 * Image:tree.jpg|A tree
2983 * given as text will return the HTML of a gallery with two images,
2984 * labeled 'The number "1"' and
2989 function renderImageGallery( $text ) {
2991 global $wgUser, $wgParser, $wgTitle;
2992 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2994 global $wgLinkCache;
2995 $ig = new ImageGallery();
2996 $ig->setShowBytes( false );
2997 $ig->setShowFilename( false );
2998 $lines = explode( "\n", $text );
3000 foreach ( $lines as $line ) {
3001 # match lines like these:
3002 # Image:someimage.jpg|This is some image
3003 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3005 if ( count( $matches ) == 0 ) {
3008 $nt = Title
::newFromURL( $matches[1] );
3009 if( is_null( $nt ) ) {
3010 # Bogus title. Ignore these so we don't bomb out later.
3013 if ( isset( $matches[3] ) ) {
3014 $label = $matches[3];
3019 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
3020 $html = $html->mText
;
3022 $ig->add( new Image( $nt ), $html );
3023 $wgLinkCache->addImageLinkObj( $nt );
3025 return $ig->toHTML();
3029 * Parse image options text and use it to make an image
3031 function makeImage( &$nt, $options ) {
3032 global $wgContLang, $wgUseImageResize;
3033 global $wgUser, $wgThumbLimits;
3037 # Check if the options text is of the form "options|alt text"
3039 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3040 # * left no resizing, just left align. label is used for alt= only
3041 # * right same, but right aligned
3042 # * none same, but not aligned
3043 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3044 # * center center the image
3045 # * framed Keep original image size, no magnify-button.
3047 $part = explode( '|', $options);
3049 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3050 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3051 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3052 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3053 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3054 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3055 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3058 $width = $height = $framed = $thumb = false;
3059 $manual_thumb = "" ;
3061 foreach( $part as $key => $val ) {
3062 $val_parts = explode ( "=" , $val , 2 ) ;
3063 $left_part = array_shift ( $val_parts ) ;
3064 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3066 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3067 # use manually specified thumbnail
3069 $manual_thumb = array_shift ( $val_parts ) ;
3070 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3071 # remember to set an alignment, don't render immediately
3073 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3074 # remember to set an alignment, don't render immediately
3076 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3077 # remember to set an alignment, don't render immediately
3079 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3080 # remember to set an alignment, don't render immediately
3082 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3083 # $match is the image width in pixels
3084 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3085 $width = intval( $m[1] );
3086 $height = intval( $m[2] );
3088 $width = intval($match);
3090 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3096 # Strip bad stuff out of the alt text
3098 $this->replaceLinkHolders( $alt );
3099 $alt = Sanitizer
::stripAllTags( $alt );
3101 # Linker does the rest
3102 $sk =& $this->mOptions
->getSkin();
3103 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3109 * @package MediaWiki
3113 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3114 var $mCacheTime; # Used in ParserCache
3115 var $mVersion; # Compatibility check
3116 var $mTitleText; # title text of the chosen language variant
3118 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3119 $containsOldMagic = false, $titletext = '' )
3121 $this->mText
= $text;
3122 $this->mLanguageLinks
= $languageLinks;
3123 $this->mCategoryLinks
= $categoryLinks;
3124 $this->mContainsOldMagic
= $containsOldMagic;
3125 $this->mCacheTime
= '';
3126 $this->mVersion
= MW_PARSER_VERSION
;
3127 $this->mTitleText
= $titletext;
3130 function getText() { return $this->mText
; }
3131 function getLanguageLinks() { return $this->mLanguageLinks
; }
3132 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3133 function getCacheTime() { return $this->mCacheTime
; }
3134 function getTitleText() { return $this->mTitleText
; }
3135 function containsOldMagic() { return $this->mContainsOldMagic
; }
3136 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3137 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3138 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3139 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3140 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3141 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3143 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3145 function merge( $other ) {
3146 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3147 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3148 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3152 * Return true if this cached output object predates the global or
3153 * per-article cache invalidation timestamps, or if it comes from
3154 * an incompatible older version.
3156 * @param string $touched the affected article's last touched timestamp
3160 function expired( $touched ) {
3161 global $wgCacheEpoch;
3162 return $this->getCacheTime() <= $touched ||
3163 $this->getCacheTime() <= $wgCacheEpoch ||
3164 !isset( $this->mVersion
) ||
3165 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3170 * Set options of the Parser
3172 * @package MediaWiki
3176 # All variables are private
3177 var $mUseTeX; # Use texvc to expand <math> tags
3178 var $mUseDynamicDates; # Use DateFormatter to format dates
3179 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3180 var $mAllowExternalImages; # Allow external images inline
3181 var $mSkin; # Reference to the preferred skin
3182 var $mDateFormat; # Date format index
3183 var $mEditSection; # Create "edit section" links
3184 var $mNumberHeadings; # Automatically number headings
3186 function getUseTeX() { return $this->mUseTeX
; }
3187 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3188 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3189 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3190 function getSkin() { return $this->mSkin
; }
3191 function getDateFormat() { return $this->mDateFormat
; }
3192 function getEditSection() { return $this->mEditSection
; }
3193 function getNumberHeadings() { return $this->mNumberHeadings
; }
3195 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3196 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3197 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3198 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3199 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3200 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3201 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3203 function setSkin( &$x ) { $this->mSkin
=& $x; }
3206 * Get parser options
3209 function newFromUser( &$user ) {
3210 $popts = new ParserOptions
;
3211 $popts->initialiseFromUser( $user );
3215 /** Get user options */
3216 function initialiseFromUser( &$userInput ) {
3217 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3218 $fname = 'ParserOptions::initialiseFromUser';
3219 wfProfileIn( $fname );
3220 if ( !$userInput ) {
3222 $user->setLoaded( true );
3224 $user =& $userInput;
3227 $this->mUseTeX
= $wgUseTeX;
3228 $this->mUseDynamicDates
= $wgUseDynamicDates;
3229 $this->mInterwikiMagic
= $wgInterwikiMagic;
3230 $this->mAllowExternalImages
= $wgAllowExternalImages;
3231 wfProfileIn( $fname.'-skin' );
3232 $this->mSkin
=& $user->getSkin();
3233 wfProfileOut( $fname.'-skin' );
3234 $this->mDateFormat
= $user->getOption( 'date' );
3235 $this->mEditSection
= $user->getOption( 'editsection' );
3236 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3237 wfProfileOut( $fname );
3242 * Callback function used by Parser::replaceLinkHolders()
3243 * to substitute link placeholders.
3245 function &wfOutputReplaceMatches( $matches ) {
3246 global $wgOutputReplace;
3247 return $wgOutputReplace[$matches[1]];
3251 * Return the total number of articles
3253 function wfNumberOfArticles() {
3254 global $wgNumberOfArticles;
3257 return $wgNumberOfArticles;
3261 * Get various statistics from the database
3264 function wfLoadSiteStats() {
3265 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3266 $fname = 'wfLoadSiteStats';
3268 if ( -1 != $wgNumberOfArticles ) return;
3269 $dbr =& wfGetDB( DB_SLAVE
);
3270 $s = $dbr->selectRow( 'site_stats',
3271 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3272 array( 'ss_row_id' => 1 ), $fname
3275 if ( $s === false ) {
3278 $wgTotalViews = $s->ss_total_views
;
3279 $wgTotalEdits = $s->ss_total_edits
;
3280 $wgNumberOfArticles = $s->ss_good_articles
;
3286 * Basicly replacing " > and < with HTML entities ( ", >, <)
3288 * @param string $in Text that might contain HTML tags
3289 * @return string Escaped string
3291 function wfEscapeHTMLTagsOnly( $in ) {
3293 array( '"', '>', '<' ),
3294 array( '"', '>', '<' ),