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, $wgDateFormatter, $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;
106 var $mOptions, $mTitle, $mOutputType,
107 $mTemplates, // cache of already loaded templates, avoids
108 // multiple SQL queries for the same string
109 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
110 // in this path. Used for loop detection.
120 $this->mTemplates
= array();
121 $this->mTemplatePath
= array();
122 $this->mTagHooks
= array();
131 function clearState() {
132 $this->mOutput
= new ParserOutput
;
133 $this->mAutonumber
= 0;
134 $this->mLastSection
= '';
135 $this->mDTopen
= false;
136 $this->mVariables
= false;
137 $this->mIncludeCount
= array();
138 $this->mStripState
= array();
139 $this->mArgStack
= array();
140 $this->mInPre
= false;
144 * First pass--just handle <nowiki> sections, pass the rest off
145 * to internalParse() which does all the real work.
148 * @param string $text Text we want to parse
149 * @param Title &$title A title object
150 * @param array $options
151 * @param boolean $linestart
152 * @param boolean $clearState
153 * @return ParserOutput a ParserOutput
155 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
156 global $wgUseTidy, $wgContLang;
157 $fname = 'Parser::parse';
158 wfProfileIn( $fname );
164 $this->mOptions
= $options;
165 $this->mTitle
=& $title;
166 $this->mOutputType
= OT_HTML
;
169 global $fnord; $fnord = 1;
170 //$text = $this->strip( $text, $this->mStripState );
171 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
172 $x =& $this->mStripState
;
173 $text = $this->strip( $text, $x );
175 $text = $this->internalParse( $text, $linestart );
177 $dashReplace = array(
178 '/ - /' => " – ", # N dash
179 '/(?<=[0-9])-(?=[0-9])/' => "–", # N dash between numbers
180 '/ -- /' => " — " # M dash
182 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
185 $text = $this->unstrip( $text, $this->mStripState
);
186 # Clean up special characters, only run once, next-to-last before doBlockLevels
190 # french spaces, last one Guillemet-left
191 # only if there is something before the space
192 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
193 # french spaces, Guillemet-right
194 '/(\\302\\253) /' => '\\1 ',
195 '/<hr *>/i' => '<hr />',
196 '/<br *>/i' => '<br />',
197 '/<center *>/i' => '<div class="center">',
198 '/<\\/center *>/i' => '</div>',
200 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
201 $text = Sanitizer
::normalizeCharReferences( $text );
204 # french spaces, last one Guillemet-left
205 '/ (\\?|:|;|!|\\302\\273)/' => ' \\1',
206 # french spaces, Guillemet-right
207 '/(\\302\\253) /' => '\\1 ',
208 '/<center *>/i' => '<div class="center">',
209 '/<\\/center *>/i' => '</div>'
211 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
214 $text = $this->doBlockLevels( $text, $linestart );
216 $this->replaceLinkHolders( $text );
217 $text = $wgContLang->convert($text);
218 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
219 $text = $this->unstripNoWiki( $text, $this->mStripState
);
221 $text = Parser
::tidy($text);
224 $this->mOutput
->setText( $text );
225 wfProfileOut( $fname );
226 return $this->mOutput
;
230 * Get a random string
235 function getRandomString() {
236 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
240 * Replaces all occurrences of <$tag>content</$tag> in the text
241 * with a random marker and returns the new text. the output parameter
242 * $content will be an associative array filled with data on the form
243 * $unique_marker => content.
245 * If $content is already set, the additional entries will be appended
246 * If $tag is set to STRIP_COMMENTS, the function will extract
247 * <!-- HTML comments -->
252 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
253 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
260 while ( '' != $text ) {
261 if($tag==STRIP_COMMENTS
) {
262 $p = preg_split( '/<!--/', $text, 2 );
264 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
267 if ( ( count( $p ) < 2 ) ||
( '' == $p[1] ) ) {
270 if($tag==STRIP_COMMENTS
) {
271 $q = preg_split( '/-->/i', $p[1], 2 );
273 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
275 $marker = $rnd . sprintf('%08X', $n++
);
276 $content[$marker] = $q[0];
277 $stripped .= $marker;
285 * Strips and renders nowiki, pre, math, hiero
286 * If $render is set, performs necessary rendering operations on plugins
287 * Returns the text, and fills an array with data needed in unstrip()
288 * If the $state is already a valid strip state, it adds to the state
290 * @param bool $stripcomments when set, HTML comments <!-- like this -->
291 * will be stripped in addition to other tags. This is important
292 * for section editing, where these comments cause confusion when
293 * counting the sections in the wikisource
297 function strip( $text, &$state, $stripcomments = false ) {
298 $render = ($this->mOutputType
== OT_HTML
);
299 $html_content = array();
300 $nowiki_content = array();
301 $math_content = array();
302 $pre_content = array();
303 $comment_content = array();
304 $ext_content = array();
305 $gallery_content = array();
307 # Replace any instances of the placeholders
308 $uniq_prefix = UNIQ_PREFIX
;
309 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
312 global $wgRawHtml, $wgWhitelistEdit;
313 if( $wgRawHtml && $wgWhitelistEdit ) {
314 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
315 foreach( $html_content as $marker => $content ) {
317 # Raw and unchecked for validity.
318 $html_content[$marker] = $content;
320 $html_content[$marker] = '<html>'.$content.'</html>';
326 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
327 foreach( $nowiki_content as $marker => $content ) {
329 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
331 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
336 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
337 foreach( $math_content as $marker => $content ){
339 if( $this->mOptions
->getUseTeX() ) {
340 $math_content[$marker] = renderMath( $content );
342 $math_content[$marker] = '<math>'.$content.'<math>';
345 $math_content[$marker] = '<math>'.$content.'</math>';
350 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
351 foreach( $pre_content as $marker => $content ){
353 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
355 $pre_content[$marker] = '<pre>'.$content.'</pre>';
360 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
361 foreach( $gallery_content as $marker => $content ) {
362 require_once( 'ImageGallery.php' );
364 $gallery_content[$marker] = Parser
::renderImageGallery( $content );
366 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
372 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
373 foreach( $comment_content as $marker => $content ){
374 $comment_content[$marker] = '<!--'.$content.'-->';
379 foreach ( $this->mTagHooks
as $tag => $callback ) {
380 $ext_contents[$tag] = array();
381 $text = Parser
::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
382 foreach( $ext_content[$tag] as $marker => $content ) {
384 $ext_content[$tag][$marker] = $callback( $content );
386 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
391 # Merge state with the pre-existing state, if there is one
393 $state['html'] = $state['html'] +
$html_content;
394 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
395 $state['math'] = $state['math'] +
$math_content;
396 $state['pre'] = $state['pre'] +
$pre_content;
397 $state['comment'] = $state['comment'] +
$comment_content;
398 $state['gallery'] = $state['gallery'] +
$gallery_content;
400 foreach( $ext_content as $tag => $array ) {
401 if ( array_key_exists( $tag, $state ) ) {
402 $state[$tag] = $state[$tag] +
$array;
407 'html' => $html_content,
408 'nowiki' => $nowiki_content,
409 'math' => $math_content,
410 'pre' => $pre_content,
411 'comment' => $comment_content,
412 'gallery' => $gallery_content,
419 * restores pre, math, and hiero removed by strip()
421 * always call unstripNoWiki() after this one
424 function unstrip( $text, &$state ) {
425 # Must expand in reverse order, otherwise nested tags will be corrupted
426 $contentDict = end( $state );
427 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
428 if( key($state) != 'nowiki' && key($state) != 'html') {
429 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
430 $text = str_replace( key( $contentDict ), $content, $text );
439 * always call this after unstrip() to preserve the order
443 function unstripNoWiki( $text, &$state ) {
444 # Must expand in reverse order, otherwise nested tags will be corrupted
445 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
446 $text = str_replace( key( $state['nowiki'] ), $content, $text );
451 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
452 $text = str_replace( key( $state['html'] ), $content, $text );
460 * Add an item to the strip state
461 * Returns the unique tag which must be inserted into the stripped text
462 * The tag will be replaced with the original text in unstrip()
466 function insertStripItem( $text, &$state ) {
467 $rnd = UNIQ_PREFIX
. '-item' . Parser
::getRandomString();
476 $state['item'][$rnd] = $text;
481 * interface with html tidy, used if $wgUseTidy = true
486 function tidy ( $text ) {
487 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
488 $fname = 'Parser::tidy';
489 wfProfileIn( $fname );
494 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
495 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
496 '<head><title>test</title></head><body>'.$text.'</body></html>';
497 $descriptorspec = array(
498 0 => array('pipe', 'r'),
499 1 => array('pipe', 'w'),
500 2 => array('file', '/dev/null', 'a')
502 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
503 if (is_resource($process)) {
504 fwrite($pipes[0], $wrappedtext);
506 while (!feof($pipes[1])) {
507 $cleansource .= fgets($pipes[1], 1024);
510 $return_value = proc_close($process);
513 wfProfileOut( $fname );
515 if( $cleansource == '' && $text != '') {
516 wfDebug( "Tidy error detected!\n" );
517 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
524 * parse the wiki syntax used to render tables
528 function doTableStuff ( $t ) {
529 $fname = 'Parser::doTableStuff';
530 wfProfileIn( $fname );
532 $t = explode ( "\n" , $t ) ;
533 $td = array () ; # Is currently a td tag open?
534 $ltd = array () ; # Was it TD or TH?
535 $tr = array () ; # Is currently a tr tag open?
536 $ltr = array () ; # tr attributes
537 $indent_level = 0; # indent level of the table
538 foreach ( $t AS $k => $x )
541 $fc = substr ( $x , 0 , 1 ) ;
542 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
543 $indent_level = strlen( $matches[1] );
544 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
545 '<table' . Sanitizer
::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
546 array_push ( $td , false ) ;
547 array_push ( $ltd , '' ) ;
548 array_push ( $tr , false ) ;
549 array_push ( $ltr , '' ) ;
551 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
552 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
553 $z = "</table>" . substr ( $x , 2);
554 $l = array_pop ( $ltd ) ;
555 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
556 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
558 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
560 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
561 $x = substr ( $x , 1 ) ;
562 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
564 $l = array_pop ( $ltd ) ;
565 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
566 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
569 array_push ( $tr , false ) ;
570 array_push ( $td , false ) ;
571 array_push ( $ltd , '' ) ;
572 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $x, 'tr' ) ) ;
574 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
576 if ( '|+' == substr ( $x , 0 , 2 ) ) {
578 $x = substr ( $x , 1 ) ;
580 $after = substr ( $x , 1 ) ;
581 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
582 $after = explode ( '||' , $after ) ;
585 # Loop through each table cell
586 foreach ( $after AS $theline )
591 $tra = array_pop ( $ltr ) ;
592 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
593 array_push ( $tr , true ) ;
594 array_push ( $ltr , '' ) ;
597 $l = array_pop ( $ltd ) ;
598 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
599 if ( $fc == '|' ) $l = 'td' ;
600 else if ( $fc == '!' ) $l = 'th' ;
601 else if ( $fc == '+' ) $l = 'caption' ;
603 array_push ( $ltd , $l ) ;
606 $y = explode ( '|' , $theline , 2 ) ;
607 # Note that a '|' inside an invalid link should not
608 # be mistaken as delimiting cell parameters
609 if ( strpos( $y[0], '[[' ) !== false ) {
610 $y = array ($theline);
612 if ( count ( $y ) == 1 )
613 $y = "{$z}<{$l}>{$y[0]}" ;
614 else $y = $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($y[0], $l).">{$y[1]}" ;
616 array_push ( $td , true ) ;
621 # Closing open td, tr && table
622 while ( count ( $td ) > 0 )
624 if ( array_pop ( $td ) ) $t[] = '</td>' ;
625 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
629 $t = implode ( "\n" , $t ) ;
630 # $t = Sanitizer::removeHTMLtags( $t );
631 wfProfileOut( $fname );
636 * Helper function for parse() that transforms wiki markup into
637 * HTML. Only called for $mOutputType == OT_HTML.
641 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
644 $fname = 'Parser::internalParse';
645 wfProfileIn( $fname );
647 $text = Sanitizer
::removeHTMLtags( $text );
648 $text = $this->replaceVariables( $text, $args );
650 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
652 $text = $this->doHeadings( $text );
653 if($this->mOptions
->getUseDynamicDates()) {
654 global $wgDateFormatter;
655 $text = $wgDateFormatter->reformat( $this->mOptions
->getDateFormat(), $text );
657 $text = $this->doAllQuotes( $text );
658 $text = $this->replaceInternalLinks( $text );
659 $text = $this->replaceExternalLinks( $text );
661 # replaceInternalLinks may sometimes leave behind
662 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
663 $text = str_replace("http-noparse://","http://",$text);
665 $text = $this->doMagicLinks( $text );
666 $text = $this->doTableStuff( $text );
667 $text = $this->formatHeadings( $text, $isMain );
669 wfProfileOut( $fname );
674 * Replace special strings like "ISBN xxx" and "RFC xxx" with
675 * magic external links.
679 function &doMagicLinks( &$text ) {
680 $text = $this->magicISBN( $text );
681 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
682 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
687 * Parse ^^ tokens and return html
691 function doExponent( $text ) {
692 $fname = 'Parser::doExponent';
693 wfProfileIn( $fname );
694 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
695 wfProfileOut( $fname );
700 * Parse headers and return html
704 function doHeadings( $text ) {
705 $fname = 'Parser::doHeadings';
706 wfProfileIn( $fname );
707 for ( $i = 6; $i >= 1; --$i ) {
708 $h = substr( '======', 0, $i );
709 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
710 "<h{$i}>\\1</h{$i}>\\2", $text );
712 wfProfileOut( $fname );
717 * Replace single quotes with HTML markup
719 * @return string the altered text
721 function doAllQuotes( $text ) {
722 $fname = 'Parser::doAllQuotes';
723 wfProfileIn( $fname );
725 $lines = explode( "\n", $text );
726 foreach ( $lines as $line ) {
727 $outtext .= $this->doQuotes ( $line ) . "\n";
729 $outtext = substr($outtext, 0,-1);
730 wfProfileOut( $fname );
735 * Helper function for doAllQuotes()
738 function doQuotes( $text ) {
739 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
740 if ( count( $arr ) == 1 )
744 # First, do some preliminary work. This may shift some apostrophes from
745 # being mark-up to being text. It also counts the number of occurrences
746 # of bold and italics mark-ups.
750 foreach ( $arr as $r )
752 if ( ( $i %
2 ) == 1 )
754 # If there are ever four apostrophes, assume the first is supposed to
755 # be text, and the remaining three constitute mark-up for bold text.
756 if ( strlen( $arr[$i] ) == 4 )
761 # If there are more than 5 apostrophes in a row, assume they're all
762 # text except for the last 5.
763 else if ( strlen( $arr[$i] ) > 5 )
765 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
768 # Count the number of occurrences of bold and italics mark-ups.
769 # We are not counting sequences of five apostrophes.
770 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
771 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
772 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
777 # If there is an odd number of both bold and italics, it is likely
778 # that one of the bold ones was meant to be an apostrophe followed
779 # by italics. Which one we cannot know for certain, but it is more
780 # likely to be one that has a single-letter word before it.
781 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
784 $firstsingleletterword = -1;
785 $firstmultiletterword = -1;
787 foreach ( $arr as $r )
789 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
791 $x1 = substr ($arr[$i-1], -1);
792 $x2 = substr ($arr[$i-1], -2, 1);
794 if ($firstspace == -1) $firstspace = $i;
795 } else if ($x2 == ' ') {
796 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
798 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
804 # If there is a single-letter word, use it!
805 if ($firstsingleletterword > -1)
807 $arr [ $firstsingleletterword ] = "''";
808 $arr [ $firstsingleletterword-1 ] .= "'";
810 # If not, but there's a multi-letter word, use that one.
811 else if ($firstmultiletterword > -1)
813 $arr [ $firstmultiletterword ] = "''";
814 $arr [ $firstmultiletterword-1 ] .= "'";
816 # ... otherwise use the first one that has neither.
817 # (notice that it is possible for all three to be -1 if, for example,
818 # there is only one pentuple-apostrophe in the line)
819 else if ($firstspace > -1)
821 $arr [ $firstspace ] = "''";
822 $arr [ $firstspace-1 ] .= "'";
826 # Now let's actually convert our apostrophic mush to HTML!
835 if ($state == 'both')
842 if (strlen ($r) == 2)
845 { $output .= '</i>'; $state = ''; }
846 else if ($state == 'bi')
847 { $output .= '</i>'; $state = 'b'; }
848 else if ($state == 'ib')
849 { $output .= '</b></i><b>'; $state = 'b'; }
850 else if ($state == 'both')
851 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
852 else # $state can be 'b' or ''
853 { $output .= '<i>'; $state .= 'i'; }
855 else if (strlen ($r) == 3)
858 { $output .= '</b>'; $state = ''; }
859 else if ($state == 'bi')
860 { $output .= '</i></b><i>'; $state = 'i'; }
861 else if ($state == 'ib')
862 { $output .= '</b>'; $state = 'i'; }
863 else if ($state == 'both')
864 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
865 else # $state can be 'i' or ''
866 { $output .= '<b>'; $state .= 'b'; }
868 else if (strlen ($r) == 5)
871 { $output .= '</b><i>'; $state = 'i'; }
872 else if ($state == 'i')
873 { $output .= '</i><b>'; $state = 'b'; }
874 else if ($state == 'bi')
875 { $output .= '</i></b>'; $state = ''; }
876 else if ($state == 'ib')
877 { $output .= '</b></i>'; $state = ''; }
878 else if ($state == 'both')
879 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
880 else # ($state == '')
881 { $buffer = ''; $state = 'both'; }
886 # Now close all remaining tags. Notice that the order is important.
887 if ($state == 'b' ||
$state == 'ib')
889 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
893 if ($state == 'both')
894 $output .= '<b><i>'.$buffer.'</i></b>';
900 * Replace external links
902 * Note: this is all very hackish and the order of execution matters a lot.
903 * Make sure to run maintenance/parserTests.php if you change this code.
907 function replaceExternalLinks( $text ) {
908 $fname = 'Parser::replaceExternalLinks';
909 wfProfileIn( $fname );
911 $sk =& $this->mOptions
->getSkin();
913 $linktrail = $wgContLang->linkTrail();
915 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
917 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
920 while ( $i<count( $bits ) ) {
922 $protocol = $bits[$i++
];
924 $trail = $bits[$i++
];
926 # The characters '<' and '>' (which were escaped by
927 # removeHTMLtags()) should not be included in
928 # URLs, per RFC 2396.
929 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
930 $text = substr($url, $m2[0][1]) . ' ' . $text;
931 $url = substr($url, 0, $m2[0][1]);
934 # If the link text is an image URL, replace it with an <img> tag
935 # This happened by accident in the original parser, but some people used it extensively
936 $img = $this->maybeMakeImageLink( $text );
937 if ( $img !== false ) {
943 # Set linktype for CSS - if URL==text, link is essentially free
944 $linktype = ($text == $url) ?
'free' : 'text';
946 # No link text, e.g. [http://domain.tld/some.link]
948 # Autonumber if allowed
949 if ( strpos( HTTP_PROTOCOLS
, $protocol ) !== false ) {
950 $text = '[' . ++
$this->mAutonumber
. ']';
951 $linktype = 'autonumber';
953 # Otherwise just use the URL
954 $text = htmlspecialchars( $url );
958 # Have link text, e.g. [http://domain.tld/some.link text]s
960 if ( preg_match( $linktrail, $trail, $m2 ) ) {
966 # Replace & from obsolete syntax with &.
967 # All HTML entities will be escaped by makeExternalLink()
968 # or maybeMakeImageLink()
969 $url = str_replace( '&', '&', $url );
971 # Process the trail (i.e. everything after this link up until start of the next link),
972 # replacing any non-bracketed links
973 $trail = $this->replaceFreeExternalLinks( $trail );
975 # Use the encoded URL
976 # This means that users can paste URLs directly into the text
977 # Funny characters like ö aren't valid in URLs anyway
978 # This was changed in August 2004
979 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
982 wfProfileOut( $fname );
987 * Replace anything that looks like a URL with a link
990 function replaceFreeExternalLinks( $text ) {
991 $fname = 'Parser::replaceFreeExternalLinks';
992 wfProfileIn( $fname );
994 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS
.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
995 $s = array_shift( $bits );
998 $sk =& $this->mOptions
->getSkin();
1000 while ( $i < count( $bits ) ){
1001 $protocol = $bits[$i++
];
1002 $remainder = $bits[$i++
];
1004 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1005 # Found some characters after the protocol that look promising
1006 $url = $protocol . $m[1];
1009 # The characters '<' and '>' (which were escaped by
1010 # removeHTMLtags()) should not be included in
1011 # URLs, per RFC 2396.
1012 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1013 $trail = substr($url, $m2[0][1]) . $trail;
1014 $url = substr($url, 0, $m2[0][1]);
1017 # Move trailing punctuation to $trail
1019 # If there is no left bracket, then consider right brackets fair game too
1020 if ( strpos( $url, '(' ) === false ) {
1024 $numSepChars = strspn( strrev( $url ), $sep );
1025 if ( $numSepChars ) {
1026 $trail = substr( $url, -$numSepChars ) . $trail;
1027 $url = substr( $url, 0, -$numSepChars );
1030 # Replace & from obsolete syntax with &.
1031 # All HTML entities will be escaped by makeExternalLink()
1032 # or maybeMakeImageLink()
1033 $url = str_replace( '&', '&', $url );
1035 # Is this an external image?
1036 $text = $this->maybeMakeImageLink( $url );
1037 if ( $text === false ) {
1038 # Not an image, make a link
1039 $text = $sk->makeExternalLink( $url, $url, true, 'free' );
1041 $s .= $text . $trail;
1043 $s .= $protocol . $remainder;
1051 * make an image if it's allowed
1054 function maybeMakeImageLink( $url ) {
1055 $sk =& $this->mOptions
->getSkin();
1057 if ( $this->mOptions
->getAllowExternalImages() ) {
1058 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1060 $text = $sk->makeImage( htmlspecialchars( $url ) );
1067 * Process [[ ]] wikilinks
1071 function replaceInternalLinks( $s ) {
1072 global $wgLang, $wgContLang, $wgLinkCache;
1073 global $wgDisableLangConversion;
1074 static $fname = 'Parser::replaceInternalLinks' ;
1076 wfProfileIn( $fname );
1078 wfProfileIn( $fname.'-setup' );
1080 # the % is needed to support urlencoded titles as well
1081 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1083 $sk =& $this->mOptions
->getSkin();
1084 global $wgUseOldExistenceCheck;
1085 # "Post-parse link colour check" works only on wiki text since it's now
1086 # in Parser. Enable it, then disable it when we're done.
1087 $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
1089 $redirect = MagicWord
::get ( MAG_REDIRECT
) ;
1091 #split the entire text string on occurences of [[
1092 $a = explode( '[[', ' ' . $s );
1093 #get the first element (all text up to first [[), and remove the space we added
1094 $s = array_shift( $a );
1095 $s = substr( $s, 1 );
1097 # Match a link having the form [[namespace:link|alternate]]trail
1099 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1100 # Match cases where there is no "]]", which might still be images
1101 static $e1_img = FALSE;
1102 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1103 # Match the end of a line for a word that's not followed by whitespace,
1104 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1105 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1107 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1109 if( is_null( $this->mTitle
) ) {
1110 wfDebugDieBacktrace( 'nooo' );
1112 $nottalk = !$this->mTitle
->isTalkPage();
1114 if ( $useLinkPrefixExtension ) {
1115 if ( preg_match( $e2, $s, $m ) ) {
1116 $first_prefix = $m[2];
1119 $first_prefix = false;
1125 $selflink = $this->mTitle
->getPrefixedText();
1126 wfProfileOut( $fname.'-setup' );
1128 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1129 $useSubpages = $this->areSubpagesAllowed();
1131 # Loop for each link
1132 for ($k = 0; isset( $a[$k] ); $k++
) {
1134 if ( $useLinkPrefixExtension ) {
1135 wfProfileIn( $fname.'-prefixhandling' );
1136 if ( preg_match( $e2, $s, $m ) ) {
1144 $prefix = $first_prefix;
1145 $first_prefix = false;
1147 wfProfileOut( $fname.'-prefixhandling' );
1150 $might_be_img = false;
1152 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1154 # fix up urlencoded title texts
1155 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1157 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1158 $might_be_img = true;
1160 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1162 } else { # Invalid form; output directly
1163 $s .= $prefix . '[[' . $line ;
1167 # Don't allow internal links to pages containing
1168 # PROTO: where PROTO is a valid URL protocol; these
1169 # should be external links.
1170 if (preg_match('/^(\b(?:'.URL_PROTOCOLS
.'):)/', $m[1])) {
1171 $s .= $prefix . '[[' . $line ;
1175 # Make subpage if necessary
1176 if( $useSubpages ) {
1177 $link = $this->maybeDoSubpageLink( $m[1], $text );
1182 $noforce = (substr($m[1], 0, 1) != ':');
1184 # Strip off leading ':'
1185 $link = substr($link, 1);
1188 $nt =& Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1190 $s .= $prefix . '[[' . $line;
1194 #check other language variants of the link
1195 #if the article does not exist
1196 if( $checkVariantLink
1197 && $nt->getArticleID() == 0 ) {
1198 $wgContLang->findVariantLink($link, $nt);
1201 $ns = $nt->getNamespace();
1202 $iw = $nt->getInterWiki();
1204 if ($might_be_img) { # if this is actually an invalid link
1205 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1207 while (isset ($a[$k+
1]) ) {
1208 #look at the next 'line' to see if we can close it there
1209 $next_line = array_shift(array_splice( $a, $k +
1, 1) );
1210 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1211 # the first ]] closes the inner link, the second the image
1213 $text .= '[[' . $m[1];
1216 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1217 #if there's exactly one ]] that's fine, we'll keep looking
1218 $text .= '[[' . $m[0];
1220 #if $next_line is invalid too, we need look no further
1221 $text .= '[[' . $next_line;
1226 # we couldn't find the end of this imageLink, so output it raw
1227 #but don't ignore what might be perfectly normal links in the text we've examined
1228 $text = $this->replaceInternalLinks($text);
1229 $s .= $prefix . '[[' . $link . '|' . $text;
1230 # note: no $trail, because without an end, there *is* no trail
1233 } else { #it's not an image, so output it raw
1234 $s .= $prefix . '[[' . $link . '|' . $text;
1235 # note: no $trail, because without an end, there *is* no trail
1240 $wasblank = ( '' == $text );
1241 if( $wasblank ) $text = $link;
1244 # Link not escaped by : , create the various objects
1248 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1249 array_push( $this->mOutput
->mLanguageLinks
, $nt->getFullText() );
1250 $tmp = $prefix . $trail ;
1251 $s .= (trim($tmp) == '')?
'': $tmp;
1255 if ( $ns == NS_IMAGE
) {
1256 wfProfileIn( "$fname-image" );
1257 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1258 # recursively parse links inside the image caption
1259 # actually, this will parse them in any other parameters, too,
1260 # but it might be hard to fix that, and it doesn't matter ATM
1261 $text = $this->replaceExternalLinks($text);
1262 $text = $this->replaceInternalLinks($text);
1264 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1265 $s .= $prefix . str_replace('http://', 'http-noparse://', $sk->makeImageLinkObj( $nt, $text ) ) . $trail;
1266 $wgLinkCache->addImageLinkObj( $nt );
1268 wfProfileOut( "$fname-image" );
1271 wfProfileOut( "$fname-image" );
1275 if ( $ns == NS_CATEGORY
) {
1276 wfProfileIn( "$fname-category" );
1277 $t = $nt->getText();
1279 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1280 $pPLC=$sk->postParseLinkColour();
1281 $sk->postParseLinkColour( false );
1282 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1283 $sk->postParseLinkColour( $pPLC );
1284 $wgLinkCache->resume();
1287 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1288 $sortkey = $this->mTitle
->getText();
1290 $sortkey = $this->mTitle
->getPrefixedText();
1295 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1296 $this->mOutput
->addCategoryLink( $t );
1299 * Strip the whitespace Category links produce, see bug 87
1300 * @todo We might want to use trim($tmp, "\n") here.
1302 $tmp = $prefix . $trail;
1303 $s .= trim($tmp) == '' ?
'': $tmp;
1305 wfProfileOut( "$fname-category" );
1310 if( ( $nt->getPrefixedText() === $selflink ) &&
1311 ( $nt->getFragment() === '' ) ) {
1312 # Self-links are handled specially; generally de-link and change to bold.
1313 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1317 # Special and Media are pseudo-namespaces; no pages actually exist in them
1318 if( $ns == NS_MEDIA
) {
1319 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1320 $wgLinkCache->addImageLinkObj( $nt );
1322 } elseif( $ns == NS_SPECIAL
) {
1323 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1326 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1328 $sk->postParseLinkColour( $saveParseColour );
1329 wfProfileOut( $fname );
1334 * Return true if subpage links should be expanded on this page.
1337 function areSubpagesAllowed() {
1338 # Some namespaces don't allow subpages
1339 global $wgNamespacesWithSubpages;
1340 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1344 * Handle link to subpage if necessary
1345 * @param string $target the source of the link
1346 * @param string &$text the link text, modified as necessary
1347 * @return string the full name of the link
1350 function maybeDoSubpageLink($target, &$text) {
1353 # :Foobar -- override special treatment of prefix (images, language links)
1354 # /Foobar -- convert to CurrentPage/Foobar
1355 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1356 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1357 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1359 $fname = 'Parser::maybeDoSubpageLink';
1360 wfProfileIn( $fname );
1361 $ret = $target; # default return value is no change
1363 # Some namespaces don't allow subpages,
1364 # so only perform processing if subpages are allowed
1365 if( $this->areSubpagesAllowed() ) {
1366 # Look at the first character
1367 if( $target != '' && $target{0} == '/' ) {
1368 # / at end means we don't want the slash to be shown
1369 if( substr( $target, -1, 1 ) == '/' ) {
1370 $target = substr( $target, 1, -1 );
1373 $noslash = substr( $target, 1 );
1376 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1377 if( '' === $text ) {
1379 } # this might be changed for ugliness reasons
1381 # check for .. subpage backlinks
1383 $nodotdot = $target;
1384 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1386 $nodotdot = substr( $nodotdot, 3 );
1388 if($dotdotcount > 0) {
1389 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1390 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1391 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1392 # / at the end means don't show full path
1393 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1394 $nodotdot = substr( $nodotdot, 0, -1 );
1395 if( '' === $text ) {
1399 $nodotdot = trim( $nodotdot );
1400 if( $nodotdot != '' ) {
1401 $ret .= '/' . $nodotdot;
1408 wfProfileOut( $fname );
1413 * Used by doBlockLevels()
1416 /* private */ function closeParagraph() {
1418 if ( '' != $this->mLastSection
) {
1419 $result = '</' . $this->mLastSection
. ">\n";
1421 $this->mInPre
= false;
1422 $this->mLastSection
= '';
1425 # getCommon() returns the length of the longest common substring
1426 # of both arguments, starting at the beginning of both.
1428 /* private */ function getCommon( $st1, $st2 ) {
1429 $fl = strlen( $st1 );
1430 $shorter = strlen( $st2 );
1431 if ( $fl < $shorter ) { $shorter = $fl; }
1433 for ( $i = 0; $i < $shorter; ++
$i ) {
1434 if ( $st1{$i} != $st2{$i} ) { break; }
1438 # These next three functions open, continue, and close the list
1439 # element appropriate to the prefix character passed into them.
1441 /* private */ function openList( $char ) {
1442 $result = $this->closeParagraph();
1444 if ( '*' == $char ) { $result .= '<ul><li>'; }
1445 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1446 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1447 else if ( ';' == $char ) {
1448 $result .= '<dl><dt>';
1449 $this->mDTopen
= true;
1451 else { $result = '<!-- ERR 1 -->'; }
1456 /* private */ function nextItem( $char ) {
1457 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1458 else if ( ':' == $char ||
';' == $char ) {
1460 if ( $this->mDTopen
) { $close = '</dt>'; }
1461 if ( ';' == $char ) {
1462 $this->mDTopen
= true;
1463 return $close . '<dt>';
1465 $this->mDTopen
= false;
1466 return $close . '<dd>';
1469 return '<!-- ERR 2 -->';
1472 /* private */ function closeList( $char ) {
1473 if ( '*' == $char ) { $text = '</li></ul>'; }
1474 else if ( '#' == $char ) { $text = '</li></ol>'; }
1475 else if ( ':' == $char ) {
1476 if ( $this->mDTopen
) {
1477 $this->mDTopen
= false;
1478 $text = '</dt></dl>';
1480 $text = '</dd></dl>';
1483 else { return '<!-- ERR 3 -->'; }
1489 * Make lists from lines starting with ':', '*', '#', etc.
1492 * @return string the lists rendered as HTML
1494 function doBlockLevels( $text, $linestart ) {
1495 $fname = 'Parser::doBlockLevels';
1496 wfProfileIn( $fname );
1498 # Parsing through the text line by line. The main thing
1499 # happening here is handling of block-level elements p, pre,
1500 # and making lists from lines starting with * # : etc.
1502 $textLines = explode( "\n", $text );
1504 $lastPrefix = $output = $lastLine = '';
1505 $this->mDTopen
= $inBlockElem = false;
1507 $paragraphStack = false;
1509 if ( !$linestart ) {
1510 $output .= array_shift( $textLines );
1512 foreach ( $textLines as $oLine ) {
1513 $lastPrefixLength = strlen( $lastPrefix );
1514 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1515 $preOpenMatch = preg_match('/<pre/i', $oLine );
1516 if ( !$this->mInPre
) {
1517 # Multiple prefixes may abut each other for nested lists.
1518 $prefixLength = strspn( $oLine, '*#:;' );
1519 $pref = substr( $oLine, 0, $prefixLength );
1522 $pref2 = str_replace( ';', ':', $pref );
1523 $t = substr( $oLine, $prefixLength );
1524 $this->mInPre
= !empty($preOpenMatch);
1526 # Don't interpret any other prefixes in preformatted text
1528 $pref = $pref2 = '';
1533 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1534 # Same as the last item, so no need to deal with nesting or opening stuff
1535 $output .= $this->nextItem( substr( $pref, -1 ) );
1536 $paragraphStack = false;
1538 if ( substr( $pref, -1 ) == ';') {
1539 # The one nasty exception: definition lists work like this:
1540 # ; title : definition text
1541 # So we check for : in the remainder text to split up the
1542 # title and definition, without b0rking links.
1543 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1545 $output .= $term . $this->nextItem( ':' );
1548 } elseif( $prefixLength ||
$lastPrefixLength ) {
1549 # Either open or close a level...
1550 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1551 $paragraphStack = false;
1553 while( $commonPrefixLength < $lastPrefixLength ) {
1554 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1555 --$lastPrefixLength;
1557 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1558 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1560 while ( $prefixLength > $commonPrefixLength ) {
1561 $char = substr( $pref, $commonPrefixLength, 1 );
1562 $output .= $this->openList( $char );
1564 if ( ';' == $char ) {
1565 # FIXME: This is dupe of code above
1566 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1568 $output .= $term . $this->nextItem( ':' );
1571 ++
$commonPrefixLength;
1573 $lastPrefix = $pref2;
1575 if( 0 == $prefixLength ) {
1576 wfProfileIn( "$fname-paragraph" );
1577 # No prefix (not in list)--go to paragraph mode
1578 $uniq_prefix = UNIQ_PREFIX
;
1579 // XXX: use a stack for nestable elements like span, table and div
1580 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1581 $closematch = preg_match(
1582 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1583 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1584 if ( $openmatch or $closematch ) {
1585 $paragraphStack = false;
1586 $output .= $this->closeParagraph();
1587 if($preOpenMatch and !$preCloseMatch) {
1588 $this->mInPre
= true;
1590 if ( $closematch ) {
1591 $inBlockElem = false;
1593 $inBlockElem = true;
1595 } else if ( !$inBlockElem && !$this->mInPre
) {
1596 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1598 if ($this->mLastSection
!= 'pre') {
1599 $paragraphStack = false;
1600 $output .= $this->closeParagraph().'<pre>';
1601 $this->mLastSection
= 'pre';
1603 $t = substr( $t, 1 );
1606 if ( '' == trim($t) ) {
1607 if ( $paragraphStack ) {
1608 $output .= $paragraphStack.'<br />';
1609 $paragraphStack = false;
1610 $this->mLastSection
= 'p';
1612 if ($this->mLastSection
!= 'p' ) {
1613 $output .= $this->closeParagraph();
1614 $this->mLastSection
= '';
1615 $paragraphStack = '<p>';
1617 $paragraphStack = '</p><p>';
1621 if ( $paragraphStack ) {
1622 $output .= $paragraphStack;
1623 $paragraphStack = false;
1624 $this->mLastSection
= 'p';
1625 } else if ($this->mLastSection
!= 'p') {
1626 $output .= $this->closeParagraph().'<p>';
1627 $this->mLastSection
= 'p';
1632 wfProfileOut( "$fname-paragraph" );
1634 if ($paragraphStack === false) {
1638 while ( $prefixLength ) {
1639 $output .= $this->closeList( $pref2{$prefixLength-1} );
1642 if ( '' != $this->mLastSection
) {
1643 $output .= '</' . $this->mLastSection
. '>';
1644 $this->mLastSection
= '';
1647 wfProfileOut( $fname );
1652 * Split up a string on ':', ignoring any occurences inside
1653 * <a>..</a> or <span>...</span>
1654 * @param string $str the string to split
1655 * @param string &$before set to everything before the ':'
1656 * @param string &$after set to everything after the ':'
1657 * return string the position of the ':', or false if none found
1659 function findColonNoLinks($str, &$before, &$after) {
1660 # I wonder if we should make this count all tags, not just <a>
1661 # and <span>. That would prevent us from matching a ':' that
1662 # comes in the middle of italics other such formatting....
1664 $fname = 'Parser::findColonNoLinks';
1665 wfProfileIn( $fname );
1668 $colon = strpos($str, ':', $pos);
1670 if ($colon !== false) {
1671 $before = substr($str, 0, $colon);
1672 $after = substr($str, $colon +
1);
1674 # Skip any ':' within <a> or <span> pairs
1675 $a = substr_count($before, '<a');
1676 $s = substr_count($before, '<span');
1677 $ca = substr_count($before, '</a>');
1678 $cs = substr_count($before, '</span>');
1680 if ($a <= $ca and $s <= $cs) {
1681 # Tags are balanced before ':'; ok
1686 } while ($colon !== false);
1687 wfProfileOut( $fname );
1692 * Return value of a magic variable (like PAGENAME)
1696 function getVariableValue( $index ) {
1697 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1700 * Some of these require message or data lookups and can be
1701 * expensive to check many times.
1703 static $varCache = array();
1704 if( isset( $varCache[$index] ) ) return $varCache[$index];
1707 case MAG_CURRENTMONTH
:
1708 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1709 case MAG_CURRENTMONTHNAME
:
1710 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1711 case MAG_CURRENTMONTHNAMEGEN
:
1712 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1713 case MAG_CURRENTMONTHABBREV
:
1714 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1715 case MAG_CURRENTDAY
:
1716 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1718 return $this->mTitle
->getText();
1720 return $this->mTitle
->getPartialURL();
1721 case MAG_REVISIONID
:
1722 return $wgArticle->getRevIdFetched();
1724 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1725 return $wgContLang->getNsText($this->mTitle
->getNamespace()); # Patch by Dori
1726 case MAG_CURRENTDAYNAME
:
1727 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+
1 );
1728 case MAG_CURRENTYEAR
:
1729 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1730 case MAG_CURRENTTIME
:
1731 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1732 case MAG_CURRENTWEEK
:
1733 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1734 case MAG_CURRENTDOW
:
1735 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1736 case MAG_NUMBEROFARTICLES
:
1737 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1748 * initialise the magic variables (like CURRENTMONTHNAME)
1752 function initialiseVariables() {
1753 $fname = 'Parser::initialiseVariables';
1754 wfProfileIn( $fname );
1755 global $wgVariableIDs;
1756 $this->mVariables
= array();
1757 foreach ( $wgVariableIDs as $id ) {
1758 $mw =& MagicWord
::get( $id );
1759 $mw->addToArray( $this->mVariables
, $id );
1761 wfProfileOut( $fname );
1765 * Replace magic variables, templates, and template arguments
1766 * with the appropriate text. Templates are substituted recursively,
1767 * taking care to avoid infinite loops.
1769 * Note that the substitution depends on value of $mOutputType:
1770 * OT_WIKI: only {{subst:}} templates
1771 * OT_MSG: only magic variables
1772 * OT_HTML: all templates and magic variables
1774 * @param string $tex The text to transform
1775 * @param array $args Key-value pairs representing template parameters to substitute
1778 function replaceVariables( $text, $args = array() ) {
1779 global $wgLang, $wgScript, $wgArticlePath;
1781 # Prevent too big inclusions
1782 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
1786 $fname = 'Parser::replaceVariables';
1787 wfProfileIn( $fname );
1789 $titleChars = Title
::legalChars();
1791 # This function is called recursively. To keep track of arguments we need a stack:
1792 array_push( $this->mArgStack
, $args );
1794 # Variable substitution
1795 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1797 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
1798 # Argument substitution
1799 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1801 # Template substitution
1802 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1803 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1805 array_pop( $this->mArgStack
);
1807 wfProfileOut( $fname );
1812 * Replace magic variables
1815 function variableSubstitution( $matches ) {
1816 $fname = 'parser::variableSubstitution';
1817 $varname = $matches[1];
1818 wfProfileIn( $fname );
1819 if ( !$this->mVariables
) {
1820 $this->initialiseVariables();
1823 if ( $this->mOutputType
== OT_WIKI
) {
1824 # Do only magic variables prefixed by SUBST
1825 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1826 if (!$mwSubst->matchStartAndRemove( $varname ))
1828 # Note that if we don't substitute the variable below,
1829 # we don't remove the {{subst:}} magic word, in case
1830 # it is a template rather than a magic variable.
1832 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
1833 $id = $this->mVariables
[$varname];
1834 $text = $this->getVariableValue( $id );
1835 $this->mOutput
->mContainsOldMagic
= true;
1837 $text = $matches[0];
1839 wfProfileOut( $fname );
1843 # Split template arguments
1844 function getTemplateArgs( $argsString ) {
1845 if ( $argsString === '' ) {
1849 $args = explode( '|', substr( $argsString, 1 ) );
1851 # If any of the arguments contains a '[[' but no ']]', it needs to be
1852 # merged with the next arg because the '|' character between belongs
1853 # to the link syntax and not the template parameter syntax.
1854 $argc = count($args);
1856 for ( $i = 0; $i < $argc-1; $i++
) {
1857 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1858 $args[$i] .= '|'.$args[$i+
1];
1859 array_splice($args, $i+
1, 1);
1869 * Return the text of a template, after recursively
1870 * replacing any variables or templates within the template.
1872 * @param array $matches The parts of the template
1873 * $matches[1]: the title, i.e. the part before the |
1874 * $matches[2]: the parameters (including a leading |), if any
1875 * @return string the text of the template
1878 function braceSubstitution( $matches ) {
1879 global $wgLinkCache, $wgContLang;
1880 $fname = 'Parser::braceSubstitution';
1881 wfProfileIn( $fname );
1889 # Need to know if the template comes at the start of a line,
1890 # to treat the beginning of the template like the beginning
1891 # of a line for tables and block-level elements.
1892 $linestart = $matches[1];
1894 # $part1 is the bit before the first |, and must contain only title characters
1895 # $args is a list of arguments, starting from index 0, not including $part1
1897 $part1 = $matches[2];
1898 # If the third subpattern matched anything, it will start with |
1900 $args = $this->getTemplateArgs($matches[3]);
1901 $argc = count( $args );
1903 # Don't parse {{{}}} because that's only for template arguments
1904 if ( $linestart === '{' ) {
1905 $text = $matches[0];
1912 $mwSubst =& MagicWord
::get( MAG_SUBST
);
1913 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
1914 # One of two possibilities is true:
1915 # 1) Found SUBST but not in the PST phase
1916 # 2) Didn't find SUBST and in the PST phase
1917 # In either case, return without further processing
1918 $text = $matches[0];
1924 # MSG, MSGNW and INT
1927 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
1928 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1931 # Remove obsolete MSG:
1932 $mwMsg =& MagicWord
::get( MAG_MSG
);
1933 $mwMsg->matchStartAndRemove( $part1 );
1936 # Check if it is an internal message
1937 $mwInt =& MagicWord
::get( MAG_INT
);
1938 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1939 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1940 $text = $linestart . wfMsgReal( $part1, $args, true );
1948 # Check for NS: (namespace expansion)
1949 $mwNs = MagicWord
::get( MAG_NS
);
1950 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1951 if ( intval( $part1 ) ) {
1952 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1955 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1956 if ( !is_null( $index ) ) {
1957 $text = $linestart . $wgContLang->getNsText( $index );
1964 # LOCALURL and LOCALURLE
1966 $mwLocal = MagicWord
::get( MAG_LOCALURL
);
1967 $mwLocalE = MagicWord
::get( MAG_LOCALURLE
);
1969 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1970 $func = 'getLocalURL';
1971 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1972 $func = 'escapeLocalURL';
1977 if ( $func !== '' ) {
1978 $title = Title
::newFromText( $part1 );
1979 if ( !is_null( $title ) ) {
1981 $text = $linestart . $title->$func( $args[0] );
1983 $text = $linestart . $title->$func();
1991 if ( !$found && $argc == 1 ) {
1992 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
1993 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1994 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
1999 # Template table test
2001 # Did we encounter this template already? If yes, it is in the cache
2002 # and we need to check for loops.
2003 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2006 # Infinite loop test
2007 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2010 $text = $linestart .
2012 '<!-- WARNING: template loop detected -->';
2013 wfDebug( "$fname: template loop broken at '$part1'\n" );
2015 # set $text to cached message.
2016 $text = $linestart . $this->mTemplates
[$part1];
2020 # Load from database
2021 $itcamefromthedatabase = false;
2022 $lastPathLevel = $this->mTemplatePath
;
2025 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2026 if ($subpage !== '') {
2027 $ns = $this->mTitle
->getNamespace();
2029 $title = Title
::newFromText( $part1, $ns );
2030 if ( !is_null( $title ) && !$title->isExternal() ) {
2031 # Check for excessive inclusion
2032 $dbk = $title->getPrefixedDBkey();
2033 if ( $this->incrementIncludeCount( $dbk ) ) {
2034 # This should never be reached.
2035 $article = new Article( $title );
2036 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2037 if ( $articleContent !== false ) {
2039 $text = $linestart . $articleContent;
2040 $itcamefromthedatabase = true;
2044 # If the title is valid but undisplayable, make a link to it
2045 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2046 $text = $linestart . '[['.$title->getPrefixedText().']]';
2050 # Template cache array insertion
2052 $this->mTemplates
[$part1] = $text;
2057 # Recursive parsing, escaping and link table handling
2058 # Only for HTML output
2059 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2060 $text = wfEscapeWikiText( $text );
2061 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2062 # Clean up argument array
2063 $assocArgs = array();
2065 foreach( $args as $arg ) {
2066 $eqpos = strpos( $arg, '=' );
2067 if ( $eqpos === false ) {
2068 $assocArgs[$index++
] = $arg;
2070 $name = trim( substr( $arg, 0, $eqpos ) );
2071 $value = trim( substr( $arg, $eqpos+
1 ) );
2072 if ( $value === false ) {
2075 if ( $name !== false ) {
2076 $assocArgs[$name] = $value;
2081 # Add a new element to the templace recursion path
2082 $this->mTemplatePath
[$part1] = 1;
2084 $text = $this->strip( $text, $this->mStripState
);
2085 $text = Sanitizer
::removeHTMLtags( $text );
2086 $text = $this->replaceVariables( $text, $assocArgs );
2088 # Resume the link cache and register the inclusion as a link
2089 if ( $this->mOutputType
== OT_HTML
&& !is_null( $title ) ) {
2090 $wgLinkCache->addLinkObj( $title );
2093 # If the template begins with a table or block-level
2094 # element, it should be treated as beginning a new line.
2095 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2096 $text = "\n" . $text;
2099 # Prune lower levels off the recursion check path
2100 $this->mTemplatePath
= $lastPathLevel;
2103 wfProfileOut( $fname );
2106 # replace ==section headers==
2107 # XXX this needs to go away once we have a better parser.
2108 if ( $this->mOutputType
!= OT_WIKI
&& $itcamefromthedatabase ) {
2109 if( !is_null( $title ) )
2110 $encodedname = base64_encode($title->getPrefixedDBkey());
2112 $encodedname = base64_encode("");
2113 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2114 PREG_SPLIT_DELIM_CAPTURE
);
2117 for( $i = 0; $i < count($m); $i +
= 2 ) {
2119 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2121 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2125 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2126 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2127 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2133 # Prune lower levels off the recursion check path
2134 $this->mTemplatePath
= $lastPathLevel;
2137 wfProfileOut( $fname );
2140 wfProfileOut( $fname );
2146 * Triple brace replacement -- used for template arguments
2149 function argSubstitution( $matches ) {
2150 $arg = trim( $matches[1] );
2151 $text = $matches[0];
2152 $inputArgs = end( $this->mArgStack
);
2154 if ( array_key_exists( $arg, $inputArgs ) ) {
2155 $text = $inputArgs[$arg];
2162 * Returns true if the function is allowed to include this entity
2165 function incrementIncludeCount( $dbk ) {
2166 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2167 $this->mIncludeCount
[$dbk] = 0;
2169 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2177 * This function accomplishes several tasks:
2178 * 1) Auto-number headings if that option is enabled
2179 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2180 * 3) Add a Table of contents on the top for users who have enabled the option
2181 * 4) Auto-anchor headings
2183 * It loops through all headlines, collects the necessary data, then splits up the
2184 * string and re-inserts the newly formatted headlines.
2186 * @param string $text
2187 * @param boolean $isMain
2190 function formatHeadings( $text, $isMain=true ) {
2191 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2193 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2195 $forceTocHere = false;
2196 if( !$this->mTitle
->userCanEdit() ) {
2199 $showEditLink = $this->mOptions
->getEditSection();
2202 # Inhibit editsection links if requested in the page
2203 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2204 if( $esw->matchAndRemove( $text ) ) {
2207 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2209 $mw =& MagicWord
::get( MAG_NOTOC
);
2210 if( $mw->matchAndRemove( $text ) ) {
2214 # Get all headlines for numbering them and adding funky stuff like [edit]
2215 # links - this is for later, but we need the number of headlines right now
2216 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2218 # if there are fewer than 4 headlines in the article, do not show TOC
2219 if( $numMatches < 4 ) {
2223 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2224 # override above conditions and always show TOC at that place
2226 $mw =& MagicWord
::get( MAG_TOC
);
2227 if($mw->match( $text ) ) {
2229 $forceTocHere = true;
2231 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2232 # override above conditions and always show TOC above first header
2233 $mw =& MagicWord
::get( MAG_FORCETOC
);
2234 if ($mw->matchAndRemove( $text ) ) {
2239 # Never ever show TOC if no headers
2240 if( $numMatches < 1 ) {
2244 # We need this to perform operations on the HTML
2245 $sk =& $this->mOptions
->getSkin();
2249 $sectionCount = 0; # headlineCount excluding template sections
2251 # Ugh .. the TOC should have neat indentation levels which can be
2252 # passed to the skin functions. These are determined here
2256 $sublevelCount = array();
2257 $levelCount = array();
2264 foreach( $matches[3] as $headline ) {
2266 $templatetitle = '';
2267 $templatesection = 0;
2270 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2272 $templatetitle = base64_decode($mat[1]);
2273 $templatesection = 1 +
(int)base64_decode($mat[2]);
2274 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2278 $prevlevel = $level;
2279 $prevtoclevel = $toclevel;
2281 $level = $matches[1][$headlineCount];
2283 if( $doNumberHeadings ||
$doShowToc ) {
2285 if ( $level > $prevlevel ) {
2286 # Increase TOC level
2288 $sublevelCount[$toclevel] = 0;
2289 $toc .= $sk->tocIndent();
2291 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2292 # Decrease TOC level, find level to jump to
2294 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2295 # Can only go down to level 1
2298 for ($i = $toclevel; $i > 0; $i--) {
2299 if ( $levelCount[$i] == $level ) {
2300 # Found last matching level
2304 elseif ( $levelCount[$i] < $level ) {
2305 # Found first matching level below current level
2312 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2315 # No change in level, end TOC line
2316 $toc .= $sk->tocLineEnd();
2319 $levelCount[$toclevel] = $level;
2321 # count number of headlines for each level
2322 @$sublevelCount[$toclevel]++
;
2324 for( $i = 1; $i <= $toclevel; $i++
) {
2325 if( !empty( $sublevelCount[$i] ) ) {
2329 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2335 # The canonized header is a version of the header text safe to use for links
2336 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2337 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2338 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2340 # Remove link placeholders by the link text.
2341 # <!--LINK number-->
2343 # link text with suffix
2344 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2345 "\$wgLinkHolders['texts'][\$1]",
2346 $canonized_headline );
2347 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2348 "\$wgInterwikiLinkHolders[\$1]",
2349 $canonized_headline );
2352 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2353 $tocline = trim( $canonized_headline );
2354 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT
, $wgInputEncoding ) );
2355 $replacearray = array(
2359 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2360 $refer[$headlineCount] = $canonized_headline;
2362 # count how many in assoc. array so we can track dupes in anchors
2363 @$refers[$canonized_headline]++
;
2364 $refcount[$headlineCount]=$refers[$canonized_headline];
2366 # Don't number the heading if it is the only one (looks silly)
2367 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2368 # the two are different if the line contains a link
2369 $headline=$numbering . ' ' . $headline;
2372 # Create the anchor for linking from the TOC to the section
2373 $anchor = $canonized_headline;
2374 if($refcount[$headlineCount] > 1 ) {
2375 $anchor .= '_' . $refcount[$headlineCount];
2377 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2378 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2380 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2381 if ( empty( $head[$headlineCount] ) ) {
2382 $head[$headlineCount] = '';
2385 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2387 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
2390 # give headline the correct <h#> tag
2391 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2399 $toclines = $headlineCount;
2400 $toc .= $sk->tocUnindent( $toclevel - 1 );
2401 $toc = $sk->tocList( $toc );
2404 # split up and insert constructed headlines
2406 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2409 foreach( $blocks as $block ) {
2410 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2411 # This is the [edit] link that appears for the top block of text when
2412 # section editing is enabled
2414 # Disabled because it broke block formatting
2415 # For example, a bullet point in the top line
2416 # $full .= $sk->editSectionLink(0);
2419 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2420 # Top anchor now in skin
2424 if( !empty( $head[$i] ) ) {
2430 $mw =& MagicWord
::get( MAG_TOC
);
2431 return $mw->replace( $toc, $full );
2438 * Return an HTML link for the "ISBN 123456" text
2441 function magicISBN( $text ) {
2443 $fname = 'Parser::magicISBN';
2444 wfProfileIn( $fname );
2446 $a = split( 'ISBN ', ' '.$text );
2447 if ( count ( $a ) < 2 ) {
2448 wfProfileOut( $fname );
2451 $text = substr( array_shift( $a ), 1);
2452 $valid = '0123456789-Xx';
2454 foreach ( $a as $x ) {
2455 $isbn = $blank = '' ;
2456 while ( ' ' == $x{0} ) {
2458 $x = substr( $x, 1 );
2460 if ( $x == '' ) { # blank isbn
2461 $text .= "ISBN $blank";
2464 while ( strstr( $valid, $x{0} ) != false ) {
2466 $x = substr( $x, 1 );
2468 $num = str_replace( '-', '', $isbn );
2469 $num = str_replace( ' ', '', $num );
2470 $num = str_replace( 'x', 'X', $num );
2473 $text .= "ISBN $blank$x";
2475 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
2476 $text .= '<a href="' .
2477 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2478 "\" class=\"internal\">ISBN $isbn</a>";
2482 wfProfileOut( $fname );
2487 * Return an HTML link for the "RFC 1234" text
2490 * @param string $text Text to be processed
2491 * @param string $keyword Magic keyword to use (default RFC)
2492 * @param string $urlmsg Interface message to use (default rfcurl)
2495 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2498 $valid = '0123456789';
2501 $a = split( $keyword, ' '.$text );
2502 if ( count ( $a ) < 2 ) {
2505 $text = substr( array_shift( $a ), 1);
2507 /* Check if keyword is preceed by [[.
2508 * This test is made here cause of the array_shift above
2509 * that prevent the test to be done in the foreach.
2511 if ( substr( $text, -2 ) == '[[' ) {
2515 foreach ( $a as $x ) {
2516 /* token might be empty if we have RFC RFC 1234 */
2524 /** remove and save whitespaces in $blank */
2525 while ( $x{0} == ' ' ) {
2527 $x = substr( $x, 1 );
2530 /** remove and save the rfc number in $id */
2531 while ( strstr( $valid, $x{0} ) != false ) {
2533 $x = substr( $x, 1 );
2537 /* call back stripped spaces*/
2538 $text .= $keyword.$blank.$x;
2539 } elseif( $internal ) {
2541 $text .= $keyword.$id.$x;
2543 /* build the external link*/
2544 $url = wfMsg( $urlmsg, $id);
2545 $sk =& $this->mOptions
->getSkin();
2546 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2547 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2550 /* Check if the next RFC keyword is preceed by [[ */
2551 $internal = ( substr($x,-2) == '[[' );
2557 * Transform wiki markup when saving a page by doing \r\n -> \n
2558 * conversion, substitting signatures, {{subst:}} templates, etc.
2560 * @param string $text the text to transform
2561 * @param Title &$title the Title object for the current article
2562 * @param User &$user the User object describing the current user
2563 * @param ParserOptions $options parsing options
2564 * @param bool $clearState whether to clear the parser state first
2565 * @return string the altered wiki markup
2568 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2569 $this->mOptions
= $options;
2570 $this->mTitle
=& $title;
2571 $this->mOutputType
= OT_WIKI
;
2573 if ( $clearState ) {
2574 $this->clearState();
2577 $stripState = false;
2581 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2582 $text = $this->strip( $text, $stripState, false );
2583 $text = $this->pstPass2( $text, $user );
2584 $text = $this->unstrip( $text, $stripState );
2585 $text = $this->unstripNoWiki( $text, $stripState );
2590 * Pre-save transform helper function
2593 function pstPass2( $text, &$user ) {
2594 global $wgLang, $wgContLang, $wgLocaltimezone;
2596 # Variable replacement
2597 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2598 $text = $this->replaceVariables( $text );
2602 $n = $user->getName();
2603 $k = $user->getOption( 'nickname' );
2604 if ( '' == $k ) { $k = $n; }
2605 if ( isset( $wgLocaltimezone ) ) {
2606 $oldtz = getenv( 'TZ' );
2607 putenv( 'TZ='.$wgLocaltimezone );
2610 /* Note: This is the timestamp saved as hardcoded wikitext to
2611 * the database, we use $wgContLang here in order to give
2612 * everyone the same signiture and use the default one rather
2613 * than the one selected in each users preferences.
2615 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2616 ' (' . date( 'T' ) . ')';
2617 if ( isset( $wgLocaltimezone ) ) {
2618 putenv( 'TZ='.$oldtzs );
2621 if( $user->getOption( 'fancysig' ) ) {
2624 $sigText = '[[' . $wgContLang->getNsText( NS_USER
) . ":$n|$k]]";
2626 $text = preg_replace( '/~~~~~/', $d, $text );
2627 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2628 $text = preg_replace( '/~~~/', $sigText, $text );
2630 # Context links: [[|name]] and [[name (context)|]]
2632 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2633 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2634 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2635 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2637 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2638 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2639 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2640 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2642 $t = $this->mTitle
->getText();
2643 if ( preg_match( $conpat, $t, $m ) ) {
2646 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2647 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2648 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2650 if ( '' == $context ) {
2651 $text = preg_replace( $p2, '[[\\1]]', $text );
2653 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2656 # Trim trailing whitespace
2657 # MAG_END (__END__) tag allows for trailing
2658 # whitespace to be deliberately included
2659 $text = rtrim( $text );
2660 $mw =& MagicWord
::get( MAG_END
);
2661 $mw->matchAndRemove( $text );
2667 * Set up some variables which are usually set up in parse()
2668 * so that an external function can call some class members with confidence
2671 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2672 $this->mTitle
=& $title;
2673 $this->mOptions
= $options;
2674 $this->mOutputType
= $outputType;
2675 if ( $clearState ) {
2676 $this->clearState();
2681 * Transform a MediaWiki message by replacing magic variables.
2683 * @param string $text the text to transform
2684 * @param ParserOptions $options options
2685 * @return string the text with variables substituted
2688 function transformMsg( $text, $options ) {
2690 static $executing = false;
2692 # Guard against infinite recursion
2698 $this->mTitle
= $wgTitle;
2699 $this->mOptions
= $options;
2700 $this->mOutputType
= OT_MSG
;
2701 $this->clearState();
2702 $text = $this->replaceVariables( $text );
2709 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2710 * Callback will be called with the text within
2711 * Transform and return the text within
2714 function setHook( $tag, $callback ) {
2715 $oldVal = @$this->mTagHooks
[$tag];
2716 $this->mTagHooks
[$tag] = $callback;
2721 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2722 * Placeholders created in Skin::makeLinkObj()
2723 * Returns an array of links found, indexed by PDBK:
2727 * $options is a bit field, RLH_FOR_UPDATE to select for update
2729 function replaceLinkHolders( &$text, $options = 0 ) {
2730 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2731 global $wgInterwikiLinkHolders;
2732 global $outputReplace;
2734 if ( $wgUseOldExistenceCheck ) {
2738 $fname = 'Parser::replaceLinkHolders';
2739 wfProfileIn( $fname );
2744 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2745 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2746 wfProfileIn( $fname.'-check' );
2747 $dbr =& wfGetDB( DB_SLAVE
);
2748 $page = $dbr->tableName( 'page' );
2749 $sk = $wgUser->getSkin();
2750 $threshold = $wgUser->getOption('stubthreshold');
2753 asort( $wgLinkHolders['namespaces'] );
2757 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2759 $title = $wgLinkHolders['titles'][$key];
2761 # Skip invalid entries.
2762 # Result will be ugly, but prevents crash.
2763 if ( is_null( $title ) ) {
2766 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2768 # Check if it's in the link cache already
2769 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2770 $colours[$pdbk] = 1;
2771 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2772 $colours[$pdbk] = 0;
2774 # Not in the link cache, add it to the query
2775 if ( !isset( $current ) ) {
2777 $query = "SELECT page_id, page_namespace, page_title";
2778 if ( $threshold > 0 ) {
2779 $query .= ', page_len, page_is_redirect';
2781 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2782 } elseif ( $current != $val ) {
2784 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2789 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2794 if ( $options & RLH_FOR_UPDATE
) {
2795 $query .= ' FOR UPDATE';
2798 $res = $dbr->query( $query, $fname );
2800 # Fetch data and form into an associative array
2801 # non-existent = broken
2804 while ( $s = $dbr->fetchObject($res) ) {
2805 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
2806 $pdbk = $title->getPrefixedDBkey();
2807 $wgLinkCache->addGoodLink( $s->page_id
, $pdbk );
2809 if ( $threshold > 0 ) {
2810 $size = $s->page_len
;
2811 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
2812 $colours[$pdbk] = 1;
2814 $colours[$pdbk] = 2;
2817 $colours[$pdbk] = 1;
2821 wfProfileOut( $fname.'-check' );
2823 # Construct search and replace arrays
2824 wfProfileIn( $fname.'-construct' );
2825 $outputReplace = array();
2826 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2827 $pdbk = $pdbks[$key];
2828 $searchkey = '<!--LINK '.$key.'-->';
2829 $title = $wgLinkHolders['titles'][$key];
2830 if ( empty( $colours[$pdbk] ) ) {
2831 $wgLinkCache->addBadLink( $pdbk );
2832 $colours[$pdbk] = 0;
2833 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2834 $wgLinkHolders['texts'][$key],
2835 $wgLinkHolders['queries'][$key] );
2836 } elseif ( $colours[$pdbk] == 1 ) {
2837 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2838 $wgLinkHolders['texts'][$key],
2839 $wgLinkHolders['queries'][$key] );
2840 } elseif ( $colours[$pdbk] == 2 ) {
2841 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2842 $wgLinkHolders['texts'][$key],
2843 $wgLinkHolders['queries'][$key] );
2846 wfProfileOut( $fname.'-construct' );
2849 wfProfileIn( $fname.'-replace' );
2851 $text = preg_replace_callback(
2852 '/(<!--LINK .*?-->)/',
2853 "outputReplaceMatches",
2855 wfProfileOut( $fname.'-replace' );
2858 if ( !empty( $wgInterwikiLinkHolders ) ) {
2859 wfProfileIn( $fname.'-interwiki' );
2860 $outputReplace = $wgInterwikiLinkHolders;
2861 $text = preg_replace_callback(
2862 '/<!--IWLINK (.*?)-->/',
2863 "outputReplaceMatches",
2865 wfProfileOut( $fname.'-interwiki' );
2868 wfProfileOut( $fname );
2873 * Renders an image gallery from a text with one line per image.
2874 * text labels may be given by using |-style alternative text. E.g.
2875 * Image:one.jpg|The number "1"
2876 * Image:tree.jpg|A tree
2877 * given as text will return the HTML of a gallery with two images,
2878 * labeled 'The number "1"' and
2881 function renderImageGallery( $text ) {
2883 global $wgUser, $wgParser, $wgTitle;
2884 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2886 global $wgLinkCache;
2887 $ig = new ImageGallery();
2888 $ig->setShowBytes( false );
2889 $ig->setShowFilename( false );
2890 $lines = explode( "\n", $text );
2892 foreach ( $lines as $line ) {
2893 # match lines like these:
2894 # Image:someimage.jpg|This is some image
2895 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
2897 if ( count( $matches ) == 0 ) {
2900 $nt = Title
::newFromURL( $matches[1] );
2901 if( is_null( $nt ) ) {
2902 # Bogus title. Ignore these so we don't bomb out later.
2905 if ( isset( $matches[3] ) ) {
2906 $label = $matches[3];
2911 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
2912 $html = $html->mText
;
2914 $ig->add( new Image( $nt ), $html );
2915 $wgLinkCache->addImageLinkObj( $nt );
2917 return $ig->toHTML();
2923 * @package MediaWiki
2927 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2928 var $mCacheTime; # Used in ParserCache
2929 var $mVersion; # Compatibility check
2930 var $mTitleText; # title text of the chosen language variant
2932 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2933 $containsOldMagic = false, $titletext = '' )
2935 $this->mText
= $text;
2936 $this->mLanguageLinks
= $languageLinks;
2937 $this->mCategoryLinks
= $categoryLinks;
2938 $this->mContainsOldMagic
= $containsOldMagic;
2939 $this->mCacheTime
= '';
2940 $this->mVersion
= MW_PARSER_VERSION
;
2941 $this->mTitleText
= $titletext;
2944 function getText() { return $this->mText
; }
2945 function getLanguageLinks() { return $this->mLanguageLinks
; }
2946 function getCategoryLinks() { return array_keys( $this->mCategoryLinks
); }
2947 function getCacheTime() { return $this->mCacheTime
; }
2948 function getTitleText() { return $this->mTitleText
; }
2949 function containsOldMagic() { return $this->mContainsOldMagic
; }
2950 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
2951 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
2952 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks
, $cl ); }
2953 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
2954 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
2955 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
2957 function addCategoryLink( $c ) { $this->mCategoryLinks
[$c] = 1; }
2959 function merge( $other ) {
2960 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $other->mLanguageLinks
);
2961 $this->mCategoryLinks
= array_merge( $this->mCategoryLinks
, $this->mLanguageLinks
);
2962 $this->mContainsOldMagic
= $this->mContainsOldMagic ||
$other->mContainsOldMagic
;
2966 * Return true if this cached output object predates the global or
2967 * per-article cache invalidation timestamps, or if it comes from
2968 * an incompatible older version.
2970 * @param string $touched the affected article's last touched timestamp
2974 function expired( $touched ) {
2975 global $wgCacheEpoch;
2976 return $this->getCacheTime() <= $touched ||
2977 $this->getCacheTime() <= $wgCacheEpoch ||
2978 !isset( $this->mVersion
) ||
2979 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
2984 * Set options of the Parser
2986 * @package MediaWiki
2990 # All variables are private
2991 var $mUseTeX; # Use texvc to expand <math> tags
2992 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2993 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2994 var $mAllowExternalImages; # Allow external images inline
2995 var $mSkin; # Reference to the preferred skin
2996 var $mDateFormat; # Date format index
2997 var $mEditSection; # Create "edit section" links
2998 var $mNumberHeadings; # Automatically number headings
3000 function getUseTeX() { return $this->mUseTeX
; }
3001 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3002 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3003 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3004 function getSkin() { return $this->mSkin
; }
3005 function getDateFormat() { return $this->mDateFormat
; }
3006 function getEditSection() { return $this->mEditSection
; }
3007 function getNumberHeadings() { return $this->mNumberHeadings
; }
3009 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3010 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3011 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3012 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3013 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3014 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3015 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3017 function setSkin( &$x ) { $this->mSkin
=& $x; }
3020 * Get parser options
3023 function newFromUser( &$user ) {
3024 $popts = new ParserOptions
;
3025 $popts->initialiseFromUser( $user );
3029 /** Get user options */
3030 function initialiseFromUser( &$userInput ) {
3031 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3032 $fname = 'ParserOptions::initialiseFromUser';
3033 wfProfileIn( $fname );
3034 if ( !$userInput ) {
3036 $user->setLoaded( true );
3038 $user =& $userInput;
3041 $this->mUseTeX
= $wgUseTeX;
3042 $this->mUseDynamicDates
= $wgUseDynamicDates;
3043 $this->mInterwikiMagic
= $wgInterwikiMagic;
3044 $this->mAllowExternalImages
= $wgAllowExternalImages;
3045 wfProfileIn( $fname.'-skin' );
3046 $this->mSkin
=& $user->getSkin();
3047 wfProfileOut( $fname.'-skin' );
3048 $this->mDateFormat
= $user->getOption( 'date' );
3049 $this->mEditSection
= $user->getOption( 'editsection' );
3050 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3051 wfProfileOut( $fname );
3056 * Callback function used by Parser::replaceLinkHolders()
3057 * to substitute link placeholders.
3059 function &outputReplaceMatches( $matches ) {
3060 global $outputReplace;
3061 return $outputReplace[$matches[1]];
3065 * Return the total number of articles
3067 function wfNumberOfArticles() {
3068 global $wgNumberOfArticles;
3071 return $wgNumberOfArticles;
3075 * Get various statistics from the database
3078 function wfLoadSiteStats() {
3079 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3080 $fname = 'wfLoadSiteStats';
3082 if ( -1 != $wgNumberOfArticles ) return;
3083 $dbr =& wfGetDB( DB_SLAVE
);
3084 $s = $dbr->selectRow( 'site_stats',
3085 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3086 array( 'ss_row_id' => 1 ), $fname
3089 if ( $s === false ) {
3092 $wgTotalViews = $s->ss_total_views
;
3093 $wgTotalEdits = $s->ss_total_edits
;
3094 $wgNumberOfArticles = $s->ss_good_articles
;
3100 * Basicly replacing " > and < with HTML entities ( ", >, <)
3102 * @param string $in Text that might contain HTML tags
3103 * @return string Escaped string
3105 function wfEscapeHTMLTagsOnly( $in ) {
3107 array( '"', '>', '<' ),
3108 array( '"', '>', '<' ),