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 ) {
974 $fname = 'Parser::replaceExternalLinks';
975 wfProfileIn( $fname );
977 $sk =& $this->mOptions
->getSkin();
979 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
981 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
984 while ( $i<count( $bits ) ) {
986 $protocol = $bits[$i++
];
988 $trail = $bits[$i++
];
990 # The characters '<' and '>' (which were escaped by
991 # removeHTMLtags()) should not be included in
992 # URLs, per RFC 2396.
993 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
994 $text = substr($url, $m2[0][1]) . ' ' . $text;
995 $url = substr($url, 0, $m2[0][1]);
998 # If the link text is an image URL, replace it with an <img> tag
999 # This happened by accident in the original parser, but some people used it extensively
1000 $img = $this->maybeMakeExternalImage( $text );
1001 if ( $img !== false ) {
1007 # Set linktype for CSS - if URL==text, link is essentially free
1008 $linktype = ($text == $url) ?
'free' : 'text';
1010 # No link text, e.g. [http://domain.tld/some.link]
1011 if ( $text == '' ) {
1012 # Autonumber if allowed
1013 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
1014 $text = '[' . ++
$this->mAutonumber
. ']';
1015 $linktype = 'autonumber';
1017 # Otherwise just use the URL
1018 $text = htmlspecialchars( $url );
1022 # Have link text, e.g. [http://domain.tld/some.link text]s
1024 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1027 $text = $wgContLang->markNoConversion($text);
1029 # Replace & from obsolete syntax with &.
1030 # All HTML entities will be escaped by makeExternalLink()
1031 # or maybeMakeExternalImage()
1032 $url = str_replace( '&', '&', $url );
1034 # Process the trail (i.e. everything after this link up until start of the next link),
1035 # replacing any non-bracketed links
1036 $trail = $this->replaceFreeExternalLinks( $trail );
1039 # Use the encoded URL
1040 # This means that users can paste URLs directly into the text
1041 # Funny characters like ö aren't valid in URLs anyway
1042 # This was changed in August 2004
1043 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1046 wfProfileOut( $fname );
1051 * Replace anything that looks like a URL with a link
1054 function replaceFreeExternalLinks( $text ) {
1056 $fname = 'Parser::replaceFreeExternalLinks';
1057 wfProfileIn( $fname );
1059 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1060 $s = array_shift( $bits );
1063 $sk =& $this->mOptions
->getSkin();
1065 while ( $i < count( $bits ) ){
1066 $protocol = $bits[$i++
];
1067 $remainder = $bits[$i++
];
1069 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1070 # Found some characters after the protocol that look promising
1071 $url = $protocol . $m[1];
1074 # The characters '<' and '>' (which were escaped by
1075 # removeHTMLtags()) should not be included in
1076 # URLs, per RFC 2396.
1077 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1078 $trail = substr($url, $m2[0][1]) . $trail;
1079 $url = substr($url, 0, $m2[0][1]);
1082 # Move trailing punctuation to $trail
1084 # If there is no left bracket, then consider right brackets fair game too
1085 if ( strpos( $url, '(' ) === false ) {
1089 $numSepChars = strspn( strrev( $url ), $sep );
1090 if ( $numSepChars ) {
1091 $trail = substr( $url, -$numSepChars ) . $trail;
1092 $url = substr( $url, 0, -$numSepChars );
1095 # Replace & from obsolete syntax with &.
1096 # All HTML entities will be escaped by makeExternalLink()
1097 # or maybeMakeExternalImage()
1098 $url = str_replace( '&', '&', $url );
1100 # Is this an external image?
1101 $text = $this->maybeMakeExternalImage( $url );
1102 if ( $text === false ) {
1103 # Not an image, make a link
1104 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1106 $s .= $text . $trail;
1108 $s .= $protocol . $remainder;
1116 * make an image if it's allowed
1119 function maybeMakeExternalImage( $url ) {
1120 $sk =& $this->mOptions
->getSkin();
1122 if ( $this->mOptions
->getAllowExternalImages() ) {
1123 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1125 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1132 * Process [[ ]] wikilinks
1136 function replaceInternalLinks( $s ) {
1137 global $wgContLang, $wgLinkCache;
1138 static $fname = 'Parser::replaceInternalLinks' ;
1140 wfProfileIn( $fname );
1142 wfProfileIn( $fname.'-setup' );
1144 # the % is needed to support urlencoded titles as well
1145 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1147 $sk =& $this->mOptions
->getSkin();
1149 #split the entire text string on occurences of [[
1150 $a = explode( '[[', ' ' . $s );
1151 #get the first element (all text up to first [[), and remove the space we added
1152 $s = array_shift( $a );
1153 $s = substr( $s, 1 );
1155 # Match a link having the form [[namespace:link|alternate]]trail
1157 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1158 # Match cases where there is no "]]", which might still be images
1159 static $e1_img = FALSE;
1160 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1161 # Match the end of a line for a word that's not followed by whitespace,
1162 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1163 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1165 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1167 if( is_null( $this->mTitle
) ) {
1168 wfDebugDieBacktrace( 'nooo' );
1170 $nottalk = !$this->mTitle
->isTalkPage();
1172 if ( $useLinkPrefixExtension ) {
1173 if ( preg_match( $e2, $s, $m ) ) {
1174 $first_prefix = $m[2];
1177 $first_prefix = false;
1183 $selflink = $this->mTitle
->getPrefixedText();
1184 wfProfileOut( $fname.'-setup' );
1186 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1187 $useSubpages = $this->areSubpagesAllowed();
1189 # Loop for each link
1190 for ($k = 0; isset( $a[$k] ); $k++
) {
1192 if ( $useLinkPrefixExtension ) {
1193 wfProfileIn( $fname.'-prefixhandling' );
1194 if ( preg_match( $e2, $s, $m ) ) {
1202 $prefix = $first_prefix;
1203 $first_prefix = false;
1205 wfProfileOut( $fname.'-prefixhandling' );
1208 $might_be_img = false;
1210 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1212 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1213 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1214 # the real problem is with the $e1 regex
1216 if (preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1217 $text .= ']'; # so that replaceExternalLinks($text) works later
1220 # fix up urlencoded title texts
1221 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1223 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1224 $might_be_img = true;
1226 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1228 } else { # Invalid form; output directly
1229 $s .= $prefix . '[[' . $line ;
1233 # Don't allow internal links to pages containing
1234 # PROTO: where PROTO is a valid URL protocol; these
1235 # should be external links.
1236 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1237 $s .= $prefix . '[[' . $line ;
1241 # Make subpage if necessary
1242 if( $useSubpages ) {
1243 $link = $this->maybeDoSubpageLink( $m[1], $text );
1248 $noforce = (substr($m[1], 0, 1) != ':');
1250 # Strip off leading ':'
1251 $link = substr($link, 1);
1254 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1256 $s .= $prefix . '[[' . $line;
1260 #check other language variants of the link
1261 #if the article does not exist
1262 if( $checkVariantLink
1263 && $nt->getArticleID() == 0 ) {
1264 $wgContLang->findVariantLink($link, $nt);
1267 $ns = $nt->getNamespace();
1268 $iw = $nt->getInterWiki();
1270 if ($might_be_img) { # if this is actually an invalid link
1271 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1273 while (isset ($a[$k+
1]) ) {
1274 #look at the next 'line' to see if we can close it there
1275 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1276 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1277 # the first ]] closes the inner link, the second the image
1279 $text .= '[[' . $m[1];
1282 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1283 #if there's exactly one ]] that's fine, we'll keep looking
1284 $text .= '[[' . $m[0];
1286 #if $next_line is invalid too, we need look no further
1287 $text .= '[[' . $next_line;
1292 # we couldn't find the end of this imageLink, so output it raw
1293 #but don't ignore what might be perfectly normal links in the text we've examined
1294 $text = $this->replaceInternalLinks($text);
1295 $s .= $prefix . '[[' . $link . '|' . $text;
1296 # note: no $trail, because without an end, there *is* no trail
1299 } else { #it's not an image, so output it raw
1300 $s .= $prefix . '[[' . $link . '|' . $text;
1301 # note: no $trail, because without an end, there *is* no trail
1306 $wasblank = ( '' == $text );
1307 if( $wasblank ) $text = $link;
1310 # Link not escaped by : , create the various objects
1314 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1315 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1316 $s = rtrim($s . "\n");
1317 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1321 if ( $ns == NS_IMAGE
) {
1322 wfProfileIn( "$fname-image" );
1323 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1324 # recursively parse links inside the image caption
1325 # actually, this will parse them in any other parameters, too,
1326 # but it might be hard to fix that, and it doesn't matter ATM
1327 $text = $this->replaceExternalLinks($text);
1328 $text = $this->replaceInternalLinks($text);
1330 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1331 $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
1332 $wgLinkCache->addImageLinkObj( $nt );
1334 wfProfileOut( "$fname-image" );
1337 wfProfileOut( "$fname-image" );
1341 if ( $ns == NS_CATEGORY
) {
1342 wfProfileIn( "$fname-category" );
1343 $t = $nt->getText();
1344 $s = rtrim($s . "\n"); # bug 87
1346 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1347 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1348 $wgLinkCache->resume();
1351 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1352 $sortkey = $this->mTitle
->getText();
1354 $sortkey = $this->mTitle
->getPrefixedText();
1359 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1360 $this->mOutput
->addCategoryLink( $t );
1363 * Strip the whitespace Category links produce, see bug 87
1364 * @todo We might want to use trim($tmp, "\n") here.
1366 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1368 wfProfileOut( "$fname-category" );
1373 if( ( $nt->getPrefixedText() === $selflink ) &&
1374 ( $nt->getFragment() === '' ) ) {
1375 # Self-links are handled specially; generally de-link and change to bold.
1376 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1380 # Special and Media are pseudo-namespaces; no pages actually exist in them
1381 if( $ns == NS_MEDIA
) {
1382 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1383 $wgLinkCache->addImageLinkObj( $nt );
1385 } elseif( $ns == NS_SPECIAL
) {
1386 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1389 if ( $nt->isAlwaysKnown() ) {
1390 $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
1393 * Add a link placeholder
1394 * Later, this will be replaced by a real link, after the existence or
1395 * non-existence of all the links is known
1397 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1400 wfProfileOut( $fname );
1405 * Make a link placeholder. The text returned can be later resolved to a real link with
1406 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1407 * parsing of interwiki links, and secondly to allow all extistence checks and
1408 * article length checks (for stub links) to be bundled into a single query.
1411 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1412 if ( ! is_object($nt) ) {
1414 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1416 # Separate the link trail from the rest of the link
1417 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1419 if ( $nt->isExternal() ) {
1420 $iwRecord = array( $nt->getPrefixedDBkey(), $prefix.$text.$inside );
1421 $nr = array_push($this->mInterwikiLinkHolders
, $iwRecord);
1422 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1424 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1425 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1426 $this->mLinkHolders
['queries'][] = $query;
1427 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1428 $this->mLinkHolders
['titles'][] =& $nt;
1430 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1437 * Return true if subpage links should be expanded on this page.
1440 function areSubpagesAllowed() {
1441 # Some namespaces don't allow subpages
1442 global $wgNamespacesWithSubpages;
1443 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1447 * Handle link to subpage if necessary
1448 * @param string $target the source of the link
1449 * @param string &$text the link text, modified as necessary
1450 * @return string the full name of the link
1453 function maybeDoSubpageLink($target, &$text) {
1456 # :Foobar -- override special treatment of prefix (images, language links)
1457 # /Foobar -- convert to CurrentPage/Foobar
1458 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1459 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1460 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1462 $fname = 'Parser::maybeDoSubpageLink';
1463 wfProfileIn( $fname );
1464 $ret = $target; # default return value is no change
1466 # Some namespaces don't allow subpages,
1467 # so only perform processing if subpages are allowed
1468 if( $this->areSubpagesAllowed() ) {
1469 # Look at the first character
1470 if( $target != '' && $target{0} == '/' ) {
1471 # / at end means we don't want the slash to be shown
1472 if( substr( $target, -1, 1 ) == '/' ) {
1473 $target = substr( $target, 1, -1 );
1476 $noslash = substr( $target, 1 );
1479 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1480 if( '' === $text ) {
1482 } # this might be changed for ugliness reasons
1484 # check for .. subpage backlinks
1486 $nodotdot = $target;
1487 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1489 $nodotdot = substr( $nodotdot, 3 );
1491 if($dotdotcount > 0) {
1492 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1493 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1494 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1495 # / at the end means don't show full path
1496 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1497 $nodotdot = substr( $nodotdot, 0, -1 );
1498 if( '' === $text ) {
1502 $nodotdot = trim( $nodotdot );
1503 if( $nodotdot != '' ) {
1504 $ret .= '/' . $nodotdot;
1511 wfProfileOut( $fname );
1516 * Used by doBlockLevels()
1519 /* private */ function closeParagraph() {
1521 if ( '' != $this->mLastSection
) {
1522 $result = '</' . $this->mLastSection
. ">\n";
1524 $this->mInPre
= false;
1525 $this->mLastSection
= '';
1528 # getCommon() returns the length of the longest common substring
1529 # of both arguments, starting at the beginning of both.
1531 /* private */ function getCommon( $st1, $st2 ) {
1532 $fl = strlen( $st1 );
1533 $shorter = strlen( $st2 );
1534 if ( $fl < $shorter ) { $shorter = $fl; }
1536 for ( $i = 0; $i < $shorter; ++
$i ) {
1537 if ( $st1{$i} != $st2{$i} ) { break; }
1541 # These next three functions open, continue, and close the list
1542 # element appropriate to the prefix character passed into them.
1544 /* private */ function openList( $char ) {
1545 $result = $this->closeParagraph();
1547 if ( '*' == $char ) { $result .= '<ul><li>'; }
1548 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1549 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1550 else if ( ';' == $char ) {
1551 $result .= '<dl><dt>';
1552 $this->mDTopen
= true;
1554 else { $result = '<!-- ERR 1 -->'; }
1559 /* private */ function nextItem( $char ) {
1560 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1561 else if ( ':' == $char ||
';' == $char ) {
1563 if ( $this->mDTopen
) { $close = '</dt>'; }
1564 if ( ';' == $char ) {
1565 $this->mDTopen
= true;
1566 return $close . '<dt>';
1568 $this->mDTopen
= false;
1569 return $close . '<dd>';
1572 return '<!-- ERR 2 -->';
1575 /* private */ function closeList( $char ) {
1576 if ( '*' == $char ) { $text = '</li></ul>'; }
1577 else if ( '#' == $char ) { $text = '</li></ol>'; }
1578 else if ( ':' == $char ) {
1579 if ( $this->mDTopen
) {
1580 $this->mDTopen
= false;
1581 $text = '</dt></dl>';
1583 $text = '</dd></dl>';
1586 else { return '<!-- ERR 3 -->'; }
1592 * Make lists from lines starting with ':', '*', '#', etc.
1595 * @return string the lists rendered as HTML
1597 function doBlockLevels( $text, $linestart ) {
1598 $fname = 'Parser::doBlockLevels';
1599 wfProfileIn( $fname );
1601 # Parsing through the text line by line. The main thing
1602 # happening here is handling of block-level elements p, pre,
1603 # and making lists from lines starting with * # : etc.
1605 $textLines = explode( "\n", $text );
1607 $lastPrefix = $output = '';
1608 $this->mDTopen
= $inBlockElem = false;
1610 $paragraphStack = false;
1612 if ( !$linestart ) {
1613 $output .= array_shift( $textLines );
1615 foreach ( $textLines as $oLine ) {
1616 $lastPrefixLength = strlen( $lastPrefix );
1617 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1618 $preOpenMatch = preg_match('/<pre/i', $oLine );
1619 if ( !$this->mInPre
) {
1620 # Multiple prefixes may abut each other for nested lists.
1621 $prefixLength = strspn( $oLine, '*#:;' );
1622 $pref = substr( $oLine, 0, $prefixLength );
1625 $pref2 = str_replace( ';', ':', $pref );
1626 $t = substr( $oLine, $prefixLength );
1627 $this->mInPre
= !empty($preOpenMatch);
1629 # Don't interpret any other prefixes in preformatted text
1631 $pref = $pref2 = '';
1636 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1637 # Same as the last item, so no need to deal with nesting or opening stuff
1638 $output .= $this->nextItem( substr( $pref, -1 ) );
1639 $paragraphStack = false;
1641 if ( substr( $pref, -1 ) == ';') {
1642 # The one nasty exception: definition lists work like this:
1643 # ; title : definition text
1644 # So we check for : in the remainder text to split up the
1645 # title and definition, without b0rking links.
1647 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1649 $output .= $term . $this->nextItem( ':' );
1652 } elseif( $prefixLength ||
$lastPrefixLength ) {
1653 # Either open or close a level...
1654 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1655 $paragraphStack = false;
1657 while( $commonPrefixLength < $lastPrefixLength ) {
1658 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1659 --$lastPrefixLength;
1661 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1662 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1664 while ( $prefixLength > $commonPrefixLength ) {
1665 $char = substr( $pref, $commonPrefixLength, 1 );
1666 $output .= $this->openList( $char );
1668 if ( ';' == $char ) {
1669 # FIXME: This is dupe of code above
1670 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1672 $output .= $term . $this->nextItem( ':' );
1675 ++
$commonPrefixLength;
1677 $lastPrefix = $pref2;
1679 if( 0 == $prefixLength ) {
1680 wfProfileIn( "$fname-paragraph" );
1681 # No prefix (not in list)--go to paragraph mode
1682 $uniq_prefix = UNIQ_PREFIX
;
1683 // XXX: use a stack for nestable elements like span, table and div
1684 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1685 $closematch = preg_match(
1686 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1687 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1688 if ( $openmatch or $closematch ) {
1689 $paragraphStack = false;
1690 $output .= $this->closeParagraph();
1691 if($preOpenMatch and !$preCloseMatch) {
1692 $this->mInPre
= true;
1694 if ( $closematch ) {
1695 $inBlockElem = false;
1697 $inBlockElem = true;
1699 } else if ( !$inBlockElem && !$this->mInPre
) {
1700 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1702 if ($this->mLastSection
!= 'pre') {
1703 $paragraphStack = false;
1704 $output .= $this->closeParagraph().'<pre>';
1705 $this->mLastSection
= 'pre';
1707 $t = substr( $t, 1 );
1710 if ( '' == trim($t) ) {
1711 if ( $paragraphStack ) {
1712 $output .= $paragraphStack.'<br />';
1713 $paragraphStack = false;
1714 $this->mLastSection
= 'p';
1716 if ($this->mLastSection
!= 'p' ) {
1717 $output .= $this->closeParagraph();
1718 $this->mLastSection
= '';
1719 $paragraphStack = '<p>';
1721 $paragraphStack = '</p><p>';
1725 if ( $paragraphStack ) {
1726 $output .= $paragraphStack;
1727 $paragraphStack = false;
1728 $this->mLastSection
= 'p';
1729 } else if ($this->mLastSection
!= 'p') {
1730 $output .= $this->closeParagraph().'<p>';
1731 $this->mLastSection
= 'p';
1736 wfProfileOut( "$fname-paragraph" );
1738 if ($paragraphStack === false) {
1742 while ( $prefixLength ) {
1743 $output .= $this->closeList( $pref2{$prefixLength-1} );
1746 if ( '' != $this->mLastSection
) {
1747 $output .= '</' . $this->mLastSection
. '>';
1748 $this->mLastSection
= '';
1751 wfProfileOut( $fname );
1756 * Split up a string on ':', ignoring any occurences inside
1757 * <a>..</a> or <span>...</span>
1758 * @param string $str the string to split
1759 * @param string &$before set to everything before the ':'
1760 * @param string &$after set to everything after the ':'
1761 * return string the position of the ':', or false if none found
1763 function findColonNoLinks($str, &$before, &$after) {
1764 # I wonder if we should make this count all tags, not just <a>
1765 # and <span>. That would prevent us from matching a ':' that
1766 # comes in the middle of italics other such formatting....
1768 $fname = 'Parser::findColonNoLinks';
1769 wfProfileIn( $fname );
1772 $colon = strpos($str, ':', $pos);
1774 if ($colon !== false) {
1775 $before = substr($str, 0, $colon);
1776 $after = substr($str, $colon +
1);
1778 # Skip any ':' within <a> or <span> pairs
1779 $a = substr_count($before, '<a');
1780 $s = substr_count($before, '<span');
1781 $ca = substr_count($before, '</a>');
1782 $cs = substr_count($before, '</span>');
1784 if ($a <= $ca and $s <= $cs) {
1785 # Tags are balanced before ':'; ok
1790 } while ($colon !== false);
1791 wfProfileOut( $fname );
1796 * Return value of a magic variable (like PAGENAME)
1800 function getVariableValue( $index ) {
1801 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1804 * Some of these require message or data lookups and can be
1805 * expensive to check many times.
1807 static $varCache = array();
1808 if( isset( $varCache[$index] ) ) return $varCache[$index];
1811 case MAG_CURRENTMONTH
:
1812 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1813 case MAG_CURRENTMONTHNAME
:
1814 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1815 case MAG_CURRENTMONTHNAMEGEN
:
1816 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1817 case MAG_CURRENTMONTHABBREV
:
1818 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1819 case MAG_CURRENTDAY
:
1820 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1822 return $this->mTitle
->getText();
1824 return $this->mTitle
->getPartialURL();
1825 case MAG_REVISIONID
:
1826 return $wgArticle->getRevIdFetched();
1828 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1829 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1830 case MAG_CURRENTDAYNAME
:
1831 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1832 case MAG_CURRENTYEAR
:
1833 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1834 case MAG_CURRENTTIME
:
1835 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1836 case MAG_CURRENTWEEK
:
1837 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1838 case MAG_CURRENTDOW
:
1839 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1840 case MAG_NUMBEROFARTICLES
:
1841 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1852 * initialise the magic variables (like CURRENTMONTHNAME)
1856 function initialiseVariables() {
1857 $fname = 'Parser::initialiseVariables';
1858 wfProfileIn( $fname );
1859 global $wgVariableIDs;
1860 $this->mVariables
= array();
1861 foreach ( $wgVariableIDs as $id ) {
1862 $mw =& MagicWord
::get( $id );
1863 $mw->addToArray( $this->mVariables
, $id );
1865 wfProfileOut( $fname );
1869 * Replace magic variables, templates, and template arguments
1870 * with the appropriate text. Templates are substituted recursively,
1871 * taking care to avoid infinite loops.
1873 * Note that the substitution depends on value of $mOutputType:
1874 * OT_WIKI: only {{subst:}} templates
1875 * OT_MSG: only magic variables
1876 * OT_HTML: all templates and magic variables
1878 * @param string $tex The text to transform
1879 * @param array $args Key-value pairs representing template parameters to substitute
1882 function replaceVariables( $text, $args = array() ) {
1884 # Prevent too big inclusions
1885 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1889 $fname = 'Parser::replaceVariables';
1890 wfProfileIn( $fname );
1892 $titleChars = Title
::legalChars();
1894 # This function is called recursively. To keep track of arguments we need a stack:
1895 array_push( $this->mArgStack
, $args );
1897 # Variable substitution
1898 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1900 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1901 # Argument substitution
1902 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1904 # Template substitution
1905 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1906 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1908 array_pop( $this->mArgStack
);
1910 wfProfileOut( $fname );
1915 * Replace magic variables
1918 function variableSubstitution( $matches ) {
1919 $fname = 'parser::variableSubstitution';
1920 $varname = $matches[1];
1921 wfProfileIn( $fname );
1922 if ( !$this->mVariables
) {
1923 $this->initialiseVariables();
1926 if ( $this->mOutputType
== OT_WIKI
) {
1927 # Do only magic variables prefixed by SUBST
1928 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1929 if (!$mwSubst->matchStartAndRemove( $varname ))
1931 # Note that if we don't substitute the variable below,
1932 # we don't remove the {{subst:}} magic word, in case
1933 # it is a template rather than a magic variable.
1935 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1936 $id = $this->mVariables
[$varname];
1937 $text = $this->getVariableValue( $id );
1938 $this->mOutput
->mContainsOldMagic
= true;
1940 $text = $matches[0];
1942 wfProfileOut( $fname );
1946 # Split template arguments
1947 function getTemplateArgs( $argsString ) {
1948 if ( $argsString === '' ) {
1952 $args = explode( '|', substr( $argsString, 1 ) );
1954 # If any of the arguments contains a '[[' but no ']]', it needs to be
1955 # merged with the next arg because the '|' character between belongs
1956 # to the link syntax and not the template parameter syntax.
1957 $argc = count($args);
1959 for ( $i = 0; $i < $argc-1; $i++
) {
1960 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1961 $args[$i] .= '|'.$args[$i+
1];
1962 array_splice($args, $i+
1, 1);
1972 * Return the text of a template, after recursively
1973 * replacing any variables or templates within the template.
1975 * @param array $matches The parts of the template
1976 * $matches[1]: the title, i.e. the part before the |
1977 * $matches[2]: the parameters (including a leading |), if any
1978 * @return string the text of the template
1981 function braceSubstitution( $matches ) {
1982 global $wgLinkCache, $wgContLang;
1983 $fname = 'Parser::braceSubstitution';
1984 wfProfileIn( $fname );
1992 # Need to know if the template comes at the start of a line,
1993 # to treat the beginning of the template like the beginning
1994 # of a line for tables and block-level elements.
1995 $linestart = $matches[1];
1997 # $part1 is the bit before the first |, and must contain only title characters
1998 # $args is a list of arguments, starting from index 0, not including $part1
2000 $part1 = $matches[2];
2001 # If the third subpattern matched anything, it will start with |
2003 $args = $this->getTemplateArgs($matches[3]);
2004 $argc = count( $args );
2006 # Don't parse {{{}}} because that's only for template arguments
2007 if ( $linestart === '{' ) {
2008 $text = $matches[0];
2015 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2016 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2017 # One of two possibilities is true:
2018 # 1) Found SUBST but not in the PST phase
2019 # 2) Didn't find SUBST and in the PST phase
2020 # In either case, return without further processing
2021 $text = $matches[0];
2027 # MSG, MSGNW and INT
2030 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2031 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2034 # Remove obsolete MSG:
2035 $mwMsg =& MagicWord
::get( MAG_MSG
);
2036 $mwMsg->matchStartAndRemove( $part1 );
2039 # Check if it is an internal message
2040 $mwInt =& MagicWord
::get( MAG_INT
);
2041 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2042 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2043 $text = $linestart . wfMsgReal( $part1, $args, true );
2051 # Check for NS: (namespace expansion)
2052 $mwNs = MagicWord
::get( MAG_NS
);
2053 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2054 if ( intval( $part1 ) ) {
2055 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2058 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2059 if ( !is_null( $index ) ) {
2060 $text = $linestart . $wgContLang->getNsText( $index );
2067 # LOCALURL and LOCALURLE
2069 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
2070 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
2072 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2073 $func = 'getLocalURL';
2074 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2075 $func = 'escapeLocalURL';
2080 if ( $func !== '' ) {
2081 $title = Title
::newFromText( $part1 );
2082 if ( !is_null( $title ) ) {
2084 $text = $linestart . $title->$func( $args[0] );
2086 $text = $linestart . $title->$func();
2094 if ( !$found && $argc == 1 ) {
2095 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2096 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2097 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2102 # Template table test
2104 # Did we encounter this template already? If yes, it is in the cache
2105 # and we need to check for loops.
2106 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2109 # Infinite loop test
2110 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2113 $text = $linestart .
2115 '<!-- WARNING: template loop detected -->';
2116 wfDebug( "$fname: template loop broken at '$part1'\n" );
2118 # set $text to cached message.
2119 $text = $linestart . $this->mTemplates
[$part1];
2123 # Load from database
2124 $itcamefromthedatabase = false;
2125 $lastPathLevel = $this->mTemplatePath
;
2128 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2129 if ($subpage !== '') {
2130 $ns = $this->mTitle
->getNamespace();
2132 $title = Title
::newFromText( $part1, $ns );
2133 if ( !is_null( $title ) && !$title->isExternal() ) {
2134 # Check for excessive inclusion
2135 $dbk = $title->getPrefixedDBkey();
2136 if ( $this->incrementIncludeCount( $dbk ) ) {
2137 # This should never be reached.
2138 $article = new Article( $title );
2139 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2140 if ( $articleContent !== false ) {
2142 $text = $linestart . $articleContent;
2143 $itcamefromthedatabase = true;
2147 # If the title is valid but undisplayable, make a link to it
2148 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2149 $text = $linestart . '[['.$title->getPrefixedText().']]';
2153 # Template cache array insertion
2155 $this->mTemplates
[$part1] = $text;
2160 # Recursive parsing, escaping and link table handling
2161 # Only for HTML output
2162 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2163 $text = wfEscapeWikiText( $text );
2164 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2165 # Clean up argument array
2166 $assocArgs = array();
2168 foreach( $args as $arg ) {
2169 $eqpos = strpos( $arg, '=' );
2170 if ( $eqpos === false ) {
2171 $assocArgs[$index++
] = $arg;
2173 $name = trim( substr( $arg, 0, $eqpos ) );
2174 $value = trim( substr( $arg, $eqpos+
1 ) );
2175 if ( $value === false ) {
2178 if ( $name !== false ) {
2179 $assocArgs[$name] = $value;
2184 # Add a new element to the templace recursion path
2185 $this->mTemplatePath
[$part1] = 1;
2187 if( $this->mOutputType
== OT_HTML
) {
2188 $text = $this->strip( $text, $this->mStripState
);
2189 $text = Sanitizer
::removeHTMLtags( $text );
2191 $text = $this->replaceVariables( $text, $assocArgs );
2193 # Resume the link cache and register the inclusion as a link
2194 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2195 $wgLinkCache->addLinkObj( $title );
2198 # If the template begins with a table or block-level
2199 # element, it should be treated as beginning a new line.
2200 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2201 $text = "\n" . $text;
2204 # Prune lower levels off the recursion check path
2205 $this->mTemplatePath
= $lastPathLevel;
2208 wfProfileOut( $fname );
2211 # replace ==section headers==
2212 # XXX this needs to go away once we have a better parser.
2213 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2214 if( !is_null( $title ) )
2215 $encodedname = base64_encode($title->getPrefixedDBkey());
2217 $encodedname = base64_encode("");
2218 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2219 PREG_SPLIT_DELIM_CAPTURE
);
2222 for( $i = 0; $i < count($m); $i +
= 2 ) {
2224 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2226 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2230 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2231 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2232 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2238 # Prune lower levels off the recursion check path
2239 $this->mTemplatePath
= $lastPathLevel;
2242 wfProfileOut( $fname );
2245 wfProfileOut( $fname );
2251 * Triple brace replacement -- used for template arguments
2254 function argSubstitution( $matches ) {
2255 $arg = trim( $matches[1] );
2256 $text = $matches[0];
2257 $inputArgs = end( $this->mArgStack
);
2259 if ( array_key_exists( $arg, $inputArgs ) ) {
2260 $text = $inputArgs[$arg];
2267 * Returns true if the function is allowed to include this entity
2270 function incrementIncludeCount( $dbk ) {
2271 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2272 $this->mIncludeCount
[$dbk] = 0;
2274 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2282 * This function accomplishes several tasks:
2283 * 1) Auto-number headings if that option is enabled
2284 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2285 * 3) Add a Table of contents on the top for users who have enabled the option
2286 * 4) Auto-anchor headings
2288 * It loops through all headlines, collects the necessary data, then splits up the
2289 * string and re-inserts the newly formatted headlines.
2291 * @param string $text
2292 * @param boolean $isMain
2295 function formatHeadings( $text, $isMain=true ) {
2296 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2298 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2300 $forceTocHere = false;
2301 if( !$this->mTitle
->userCanEdit() ) {
2304 $showEditLink = $this->mOptions
->getEditSection();
2307 # Inhibit editsection links if requested in the page
2308 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2309 if( $esw->matchAndRemove( $text ) ) {
2312 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2314 $mw =& MagicWord
::get( MAG_NOTOC
);
2315 if( $mw->matchAndRemove( $text ) ) {
2319 # Get all headlines for numbering them and adding funky stuff like [edit]
2320 # links - this is for later, but we need the number of headlines right now
2321 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2323 # if there are fewer than 4 headlines in the article, do not show TOC
2324 if( $numMatches < 4 ) {
2328 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2329 # override above conditions and always show TOC at that place
2331 $mw =& MagicWord
::get( MAG_TOC
);
2332 if($mw->match( $text ) ) {
2334 $forceTocHere = true;
2336 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2337 # override above conditions and always show TOC above first header
2338 $mw =& MagicWord
::get( MAG_FORCETOC
);
2339 if ($mw->matchAndRemove( $text ) ) {
2344 # Never ever show TOC if no headers
2345 if( $numMatches < 1 ) {
2349 # We need this to perform operations on the HTML
2350 $sk =& $this->mOptions
->getSkin();
2354 $sectionCount = 0; # headlineCount excluding template sections
2356 # Ugh .. the TOC should have neat indentation levels which can be
2357 # passed to the skin functions. These are determined here
2361 $sublevelCount = array();
2362 $levelCount = array();
2369 foreach( $matches[3] as $headline ) {
2371 $templatetitle = '';
2372 $templatesection = 0;
2375 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2377 $templatetitle = base64_decode($mat[1]);
2378 $templatesection = 1 +
(int)base64_decode($mat[2]);
2379 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2383 $prevlevel = $level;
2384 $prevtoclevel = $toclevel;
2386 $level = $matches[1][$headlineCount];
2388 if( $doNumberHeadings ||
$doShowToc ) {
2390 if ( $level > $prevlevel ) {
2391 # Increase TOC level
2393 $sublevelCount[$toclevel] = 0;
2394 $toc .= $sk->tocIndent();
2396 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2397 # Decrease TOC level, find level to jump to
2399 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2400 # Can only go down to level 1
2403 for ($i = $toclevel; $i > 0; $i--) {
2404 if ( $levelCount[$i] == $level ) {
2405 # Found last matching level
2409 elseif ( $levelCount[$i] < $level ) {
2410 # Found first matching level below current level
2417 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2420 # No change in level, end TOC line
2421 $toc .= $sk->tocLineEnd();
2424 $levelCount[$toclevel] = $level;
2426 # count number of headlines for each level
2427 @$sublevelCount[$toclevel]++
;
2429 for( $i = 1; $i <= $toclevel; $i++
) {
2430 if( !empty( $sublevelCount[$i] ) ) {
2434 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2440 # The canonized header is a version of the header text safe to use for links
2441 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2442 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2443 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2445 # Remove link placeholders by the link text.
2446 # <!--LINK number-->
2448 # link text with suffix
2449 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2450 "\$this->mLinkHolders['texts'][\$1]",
2451 $canonized_headline );
2452 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2453 "\$this->mInterwikiLinkHolders[\$1][1]",
2454 $canonized_headline );
2457 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2458 $tocline = trim( $canonized_headline );
2459 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2460 $replacearray = array(
2464 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2465 $refers[$headlineCount] = $canonized_headline;
2467 # count how many in assoc. array so we can track dupes in anchors
2468 @$refers[$canonized_headline]++
;
2469 $refcount[$headlineCount]=$refers[$canonized_headline];
2471 # Don't number the heading if it is the only one (looks silly)
2472 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2473 # the two are different if the line contains a link
2474 $headline=$numbering . ' ' . $headline;
2477 # Create the anchor for linking from the TOC to the section
2478 $anchor = $canonized_headline;
2479 if($refcount[$headlineCount] > 1 ) {
2480 $anchor .= '_' . $refcount[$headlineCount];
2482 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2483 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2485 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2486 if ( empty( $head[$headlineCount] ) ) {
2487 $head[$headlineCount] = '';
2490 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2492 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2495 # give headline the correct <h#> tag
2496 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2504 $toc .= $sk->tocUnindent( $toclevel - 1 );
2505 $toc = $sk->tocList( $toc );
2508 # split up and insert constructed headlines
2510 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2513 foreach( $blocks as $block ) {
2514 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2515 # This is the [edit] link that appears for the top block of text when
2516 # section editing is enabled
2518 # Disabled because it broke block formatting
2519 # For example, a bullet point in the top line
2520 # $full .= $sk->editSectionLink(0);
2523 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2524 # Top anchor now in skin
2528 if( !empty( $head[$i] ) ) {
2534 $mw =& MagicWord
::get( MAG_TOC
);
2535 return $mw->replace( $toc, $full );
2542 * Return an HTML link for the "ISBN 123456" text
2545 function magicISBN( $text ) {
2546 $fname = 'Parser::magicISBN';
2547 wfProfileIn( $fname );
2549 $a = split( 'ISBN ', ' '.$text );
2550 if ( count ( $a ) < 2 ) {
2551 wfProfileOut( $fname );
2554 $text = substr( array_shift( $a ), 1);
2555 $valid = '0123456789-Xx';
2557 foreach ( $a as $x ) {
2558 $isbn = $blank = '' ;
2559 while ( ' ' == $x{0} ) {
2561 $x = substr( $x, 1 );
2563 if ( $x == '' ) { # blank isbn
2564 $text .= "ISBN $blank";
2567 while ( strstr( $valid, $x{0} ) != false ) {
2569 $x = substr( $x, 1 );
2571 $num = str_replace( '-', '', $isbn );
2572 $num = str_replace( ' ', '', $num );
2573 $num = str_replace( 'x', 'X', $num );
2576 $text .= "ISBN $blank$x";
2578 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2579 $text .= '<a href="' .
2580 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2581 "\" class=\"internal\">ISBN $isbn</a>";
2585 wfProfileOut( $fname );
2590 * Return an HTML link for the "RFC 1234" text
2593 * @param string $text Text to be processed
2594 * @param string $keyword Magic keyword to use (default RFC)
2595 * @param string $urlmsg Interface message to use (default rfcurl)
2598 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2600 $valid = '0123456789';
2603 $a = split( $keyword, ' '.$text );
2604 if ( count ( $a ) < 2 ) {
2607 $text = substr( array_shift( $a ), 1);
2609 /* Check if keyword is preceed by [[.
2610 * This test is made here cause of the array_shift above
2611 * that prevent the test to be done in the foreach.
2613 if ( substr( $text, -2 ) == '[[' ) {
2617 foreach ( $a as $x ) {
2618 /* token might be empty if we have RFC RFC 1234 */
2626 /** remove and save whitespaces in $blank */
2627 while ( $x{0} == ' ' ) {
2629 $x = substr( $x, 1 );
2632 /** remove and save the rfc number in $id */
2633 while ( strstr( $valid, $x{0} ) != false ) {
2635 $x = substr( $x, 1 );
2639 /* call back stripped spaces*/
2640 $text .= $keyword.$blank.$x;
2641 } elseif( $internal ) {
2643 $text .= $keyword.$id.$x;
2645 /* build the external link*/
2646 $url = wfMsg( $urlmsg, $id);
2647 $sk =& $this->mOptions
->getSkin();
2648 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2649 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2652 /* Check if the next RFC keyword is preceed by [[ */
2653 $internal = ( substr($x,-2) == '[[' );
2659 * Transform wiki markup when saving a page by doing \r\n -> \n
2660 * conversion, substitting signatures, {{subst:}} templates, etc.
2662 * @param string $text the text to transform
2663 * @param Title &$title the Title object for the current article
2664 * @param User &$user the User object describing the current user
2665 * @param ParserOptions $options parsing options
2666 * @param bool $clearState whether to clear the parser state first
2667 * @return string the altered wiki markup
2670 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2671 $this->mOptions
= $options;
2672 $this->mTitle
=& $title;
2673 $this->mOutputType
= OT_WIKI
;
2675 if ( $clearState ) {
2676 $this->clearState();
2679 $stripState = false;
2683 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2684 $text = $this->strip( $text, $stripState, false );
2685 $text = $this->pstPass2( $text, $user );
2686 $text = $this->unstrip( $text, $stripState );
2687 $text = $this->unstripNoWiki( $text, $stripState );
2692 * Pre-save transform helper function
2695 function pstPass2( $text, &$user ) {
2696 global $wgContLang, $wgLocaltimezone;
2698 # Variable replacement
2699 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2700 $text = $this->replaceVariables( $text );
2704 $n = $user->getName();
2705 $k = $user->getOption( 'nickname' );
2706 if ( '' == $k ) { $k = $n; }
2707 if ( isset( $wgLocaltimezone ) ) {
2708 $oldtz = getenv( 'TZ' );
2709 putenv( 'TZ='.$wgLocaltimezone );
2712 /* Note: This is the timestamp saved as hardcoded wikitext to
2713 * the database, we use $wgContLang here in order to give
2714 * everyone the same signiture and use the default one rather
2715 * than the one selected in each users preferences.
2717 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2718 ' (' . date( 'T' ) . ')';
2719 if ( isset( $wgLocaltimezone ) ) {
2720 putenv( 'TZ='.$oldtz );
2723 if( $user->getOption( 'fancysig' ) ) {
2726 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2728 $text = preg_replace( '/~~~~~/', $d, $text );
2729 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2730 $text = preg_replace( '/~~~/', $sigText, $text );
2732 # Context links: [[|name]] and [[name (context)|]]
2734 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2735 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2736 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2737 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2739 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2740 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2741 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2742 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2744 $t = $this->mTitle
->getText();
2745 if ( preg_match( $conpat, $t, $m ) ) {
2748 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2749 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2750 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2752 if ( '' == $context ) {
2753 $text = preg_replace( $p2, '[[\\1]]', $text );
2755 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2758 # Trim trailing whitespace
2759 # MAG_END (__END__) tag allows for trailing
2760 # whitespace to be deliberately included
2761 $text = rtrim( $text );
2762 $mw =& MagicWord
::get( MAG_END
);
2763 $mw->matchAndRemove( $text );
2769 * Set up some variables which are usually set up in parse()
2770 * so that an external function can call some class members with confidence
2773 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2774 $this->mTitle
=& $title;
2775 $this->mOptions
= $options;
2776 $this->mOutputType
= $outputType;
2777 if ( $clearState ) {
2778 $this->clearState();
2783 * Transform a MediaWiki message by replacing magic variables.
2785 * @param string $text the text to transform
2786 * @param ParserOptions $options options
2787 * @return string the text with variables substituted
2790 function transformMsg( $text, $options ) {
2792 static $executing = false;
2794 # Guard against infinite recursion
2800 $this->mTitle
= $wgTitle;
2801 $this->mOptions
= $options;
2802 $this->mOutputType
= OT_MSG
;
2803 $this->clearState();
2804 $text = $this->replaceVariables( $text );
2811 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2812 * Callback will be called with the text within
2813 * Transform and return the text within
2816 function setHook( $tag, $callback ) {
2817 $oldVal = @$this->mTagHooks
[$tag];
2818 $this->mTagHooks
[$tag] = $callback;
2823 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2824 * Placeholders created in Skin::makeLinkObj()
2825 * Returns an array of links found, indexed by PDBK:
2829 * $options is a bit field, RLH_FOR_UPDATE to select for update
2831 function replaceLinkHolders( &$text, $options = 0 ) {
2832 global $wgUser, $wgLinkCache;
2833 global $wgOutputReplace;
2835 $fname = 'Parser::replaceLinkHolders';
2836 wfProfileIn( $fname );
2840 $sk = $this->mOptions
->getSkin();
2842 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
2843 wfProfileIn( $fname.'-check' );
2844 $dbr =& wfGetDB( DB_SLAVE
);
2845 $page = $dbr->tableName( 'page' );
2846 $threshold = $wgUser->getOption('stubthreshold');
2849 asort( $this->mLinkHolders
['namespaces'] );
2853 foreach ( $this->mLinkHolders
['namespaces'] as $key => $val ) {
2855 $title = $this->mLinkHolders
['titles'][$key];
2857 # Skip invalid entries.
2858 # Result will be ugly, but prevents crash.
2859 if ( is_null( $title ) ) {
2862 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2864 # Check if it's in the link cache already
2865 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2866 $colours[$pdbk] = 1;
2867 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2868 $colours[$pdbk] = 0;
2870 # Not in the link cache, add it to the query
2871 if ( !isset( $current ) ) {
2873 $query = "SELECT page_id, page_namespace, page_title";
2874 if ( $threshold > 0 ) {
2875 $query .= ', page_len, page_is_redirect';
2877 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2878 } elseif ( $current != $val ) {
2880 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2885 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
2890 if ( $options & RLH_FOR_UPDATE
) {
2891 $query .= ' FOR UPDATE';
2894 $res = $dbr->query( $query, $fname );
2896 # Fetch data and form into an associative array
2897 # non-existent = broken
2900 while ( $s = $dbr->fetchObject($res) ) {
2901 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2902 $pdbk = $title->getPrefixedDBkey();
2903 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
2905 if ( $threshold > 0 ) {
2906 $size = $s->page_len
;
2907 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
2908 $colours[$pdbk] = 1;
2910 $colours[$pdbk] = 2;
2913 $colours[$pdbk] = 1;
2917 wfProfileOut( $fname.'-check' );
2919 # Construct search and replace arrays
2920 wfProfileIn( $fname.'-construct' );
2921 $wgOutputReplace = array();
2922 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
2923 $pdbk = $pdbks[$key];
2924 $searchkey = "<!--LINK $key-->";
2925 $title = $this->mLinkHolders
['titles'][$key];
2926 if ( empty( $colours[$pdbk] ) ) {
2927 $wgLinkCache->addBadLink( $pdbk );
2928 $colours[$pdbk] = 0;
2929 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2930 $this->mLinkHolders
['texts'][$key],
2931 $this->mLinkHolders
['queries'][$key] );
2932 } elseif ( $colours[$pdbk] == 1 ) {
2933 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2934 $this->mLinkHolders
['texts'][$key],
2935 $this->mLinkHolders
['queries'][$key] );
2936 } elseif ( $colours[$pdbk] == 2 ) {
2937 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2938 $this->mLinkHolders
['texts'][$key],
2939 $this->mLinkHolders
['queries'][$key] );
2942 wfProfileOut( $fname.'-construct' );
2945 wfProfileIn( $fname.'-replace' );
2947 $text = preg_replace_callback(
2948 '/(<!--LINK .*?-->)/',
2949 "wfOutputReplaceMatches",
2952 wfProfileOut( $fname.'-replace' );
2955 # Now process interwiki link holders
2956 # This is quite a bit simpler than internal links
2957 if ( !empty( $this->mInterwikiLinkHolders
) ) {
2958 wfProfileIn( $fname.'-interwiki' );
2959 # Make interwiki link HTML
2960 $wgOutputReplace = array();
2961 foreach( $this->mInterwikiLinkHolders
as $i => $lh ) {
2962 $s = $sk->makeLink( $lh[0], $lh[1] );
2963 $wgOutputReplace[] = $s;
2966 $text = preg_replace_callback(
2967 '/<!--IWLINK (.*?)-->/',
2968 "wfOutputReplaceMatches",
2970 wfProfileOut( $fname.'-interwiki' );
2973 wfProfileOut( $fname );
2978 * Renders an image gallery from a text with one line per image.
2979 * text labels may be given by using |-style alternative text. E.g.
2980 * Image:one.jpg|The number "1"
2981 * Image:tree.jpg|A tree
2982 * given as text will return the HTML of a gallery with two images,
2983 * labeled 'The number "1"' and
2988 function renderImageGallery( $text ) {
2990 global $wgUser, $wgParser, $wgTitle;
2991 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2993 global $wgLinkCache;
2994 $ig = new ImageGallery();
2995 $ig->setShowBytes( false );
2996 $ig->setShowFilename( false );
2997 $lines = explode( "\n", $text );
2999 foreach ( $lines as $line ) {
3000 # match lines like these:
3001 # Image:someimage.jpg|This is some image
3002 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3004 if ( count( $matches ) == 0 ) {
3007 $nt = Title
::newFromURL( $matches[1] );
3008 if( is_null( $nt ) ) {
3009 # Bogus title. Ignore these so we don't bomb out later.
3012 if ( isset( $matches[3] ) ) {
3013 $label = $matches[3];
3018 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
3019 $html = $html->mText
;
3021 $ig->add( new Image( $nt ), $html );
3022 $wgLinkCache->addImageLinkObj( $nt );
3024 return $ig->toHTML();
3028 * Parse image options text and use it to make an image
3030 function makeImage( &$nt, $options ) {
3031 global $wgContLang, $wgUseImageResize;
3032 global $wgUser, $wgThumbLimits;
3036 # Check if the options text is of the form "options|alt text"
3038 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3039 # * left no resizing, just left align. label is used for alt= only
3040 # * right same, but right aligned
3041 # * none same, but not aligned
3042 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3043 # * center center the image
3044 # * framed Keep original image size, no magnify-button.
3046 $part = explode( '|', $options);
3048 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3049 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3050 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3051 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3052 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3053 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3054 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3057 $width = $height = $framed = $thumb = false;
3058 $manual_thumb = "" ;
3060 foreach( $part as $key => $val ) {
3061 $val_parts = explode ( "=" , $val , 2 ) ;
3062 $left_part = array_shift ( $val_parts ) ;
3063 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3065 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3066 # use manually specified thumbnail
3068 $manual_thumb = array_shift ( $val_parts ) ;
3069 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3070 # remember to set an alignment, don't render immediately
3072 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3073 # remember to set an alignment, don't render immediately
3075 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3076 # remember to set an alignment, don't render immediately
3078 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3079 # remember to set an alignment, don't render immediately
3081 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3082 # $match is the image width in pixels
3083 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3084 $width = intval( $m[1] );
3085 $height = intval( $m[2] );
3087 $width = intval($match);
3089 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3095 # Strip bad stuff out of the alt text
3097 $this->replaceLinkHolders( $alt );
3098 $alt = Sanitizer
::stripAllTags( $alt );
3100 # Linker does the rest
3101 $sk =& $this->mOptions
->getSkin();
3102 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3108 * @package MediaWiki
3112 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3113 var $mCacheTime; # Used in ParserCache
3114 var $mVersion; # Compatibility check
3115 var $mTitleText; # title text of the chosen language variant
3117 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3118 $containsOldMagic = false, $titletext = '' )
3120 $this->mText
= $text;
3121 $this->mLanguageLinks
= $languageLinks;
3122 $this->mCategoryLinks
= $categoryLinks;
3123 $this->mContainsOldMagic
= $containsOldMagic;
3124 $this->mCacheTime
= '';
3125 $this->mVersion
= MW_PARSER_VERSION
;
3126 $this->mTitleText
= $titletext;
3129 function getText() { return $this->mText
; }
3130 function getLanguageLinks() { return $this->mLanguageLinks
; }
3131 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
3132 function getCacheTime() { return $this->mCacheTime
; }
3133 function getTitleText() { return $this->mTitleText
; }
3134 function containsOldMagic() { return $this->mContainsOldMagic
; }
3135 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3136 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3137 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
3138 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3139 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3140 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3142 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
3144 function merge( $other ) {
3145 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
3146 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
3147 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
3151 * Return true if this cached output object predates the global or
3152 * per-article cache invalidation timestamps, or if it comes from
3153 * an incompatible older version.
3155 * @param string $touched the affected article's last touched timestamp
3159 function expired( $touched ) {
3160 global $wgCacheEpoch;
3161 return $this->getCacheTime() <= $touched ||
3162 $this->getCacheTime() <= $wgCacheEpoch ||
3163 !isset( $this->mVersion
) ||
3164 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3169 * Set options of the Parser
3171 * @package MediaWiki
3175 # All variables are private
3176 var $mUseTeX; # Use texvc to expand <math> tags
3177 var $mUseDynamicDates; # Use DateFormatter to format dates
3178 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3179 var $mAllowExternalImages; # Allow external images inline
3180 var $mSkin; # Reference to the preferred skin
3181 var $mDateFormat; # Date format index
3182 var $mEditSection; # Create "edit section" links
3183 var $mNumberHeadings; # Automatically number headings
3185 function getUseTeX() { return $this->mUseTeX
; }
3186 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3187 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3188 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3189 function getSkin() { return $this->mSkin
; }
3190 function getDateFormat() { return $this->mDateFormat
; }
3191 function getEditSection() { return $this->mEditSection
; }
3192 function getNumberHeadings() { return $this->mNumberHeadings
; }
3194 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3195 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3196 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3197 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3198 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3199 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3200 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3202 function setSkin( &$x ) { $this->mSkin
=& $x; }
3205 * Get parser options
3208 function newFromUser( &$user ) {
3209 $popts = new ParserOptions
;
3210 $popts->initialiseFromUser( $user );
3214 /** Get user options */
3215 function initialiseFromUser( &$userInput ) {
3216 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3217 $fname = 'ParserOptions::initialiseFromUser';
3218 wfProfileIn( $fname );
3219 if ( !$userInput ) {
3221 $user->setLoaded( true );
3223 $user =& $userInput;
3226 $this->mUseTeX
= $wgUseTeX;
3227 $this->mUseDynamicDates
= $wgUseDynamicDates;
3228 $this->mInterwikiMagic
= $wgInterwikiMagic;
3229 $this->mAllowExternalImages
= $wgAllowExternalImages;
3230 wfProfileIn( $fname.'-skin' );
3231 $this->mSkin
=& $user->getSkin();
3232 wfProfileOut( $fname.'-skin' );
3233 $this->mDateFormat
= $user->getOption( 'date' );
3234 $this->mEditSection
= $user->getOption( 'editsection' );
3235 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3236 wfProfileOut( $fname );
3241 * Callback function used by Parser::replaceLinkHolders()
3242 * to substitute link placeholders.
3244 function &wfOutputReplaceMatches( $matches ) {
3245 global $wgOutputReplace;
3246 return $wgOutputReplace[$matches[1]];
3250 * Return the total number of articles
3252 function wfNumberOfArticles() {
3253 global $wgNumberOfArticles;
3256 return $wgNumberOfArticles;
3260 * Get various statistics from the database
3263 function wfLoadSiteStats() {
3264 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3265 $fname = 'wfLoadSiteStats';
3267 if ( -1 != $wgNumberOfArticles ) return;
3268 $dbr =& wfGetDB( DB_SLAVE
);
3269 $s = $dbr->selectRow( 'site_stats',
3270 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3271 array( 'ss_row_id' => 1 ), $fname
3274 if ( $s === false ) {
3277 $wgTotalViews = $s->ss_total_views
;
3278 $wgTotalEdits = $s->ss_total_edits
;
3279 $wgNumberOfArticles = $s->ss_good_articles
;
3285 * Basicly replacing " > and < with HTML entities ( ", >, <)
3287 * @param string $in Text that might contain HTML tags
3288 * @return string Escaped string
3290 function wfEscapeHTMLTagsOnly( $in ) {
3292 array( '"', '>', '<' ),
3293 array( '"', '>', '<' ),