3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.6.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
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;
141 $this->mInterwikiLinkHolders
= array(
145 $this->mLinkHolders
= array(
146 'namespaces' => array(),
148 'queries' => array(),
152 $this->mRevisionId
= null;
153 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
155 # Clear these on every parse, bug 4549
156 $this->mTemplates
= array();
157 $this->mTemplatePath
= array();
159 wfRunHooks( 'ParserClearState', array( &$this ) );
163 * Accessor for mUniqPrefix.
167 function UniqPrefix() {
168 return $this->mUniqPrefix
;
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
198 $this->mOptions
= $options;
199 $this->mTitle
=& $title;
200 $this->mRevisionId
= $revid;
201 $this->mOutputType
= OT_HTML
;
203 $this->mStripState
= NULL;
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState
;
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
219 $text = $this->internalParse( $text );
221 $text = $this->unstrip( $text, $this->mStripState
);
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1 ',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
235 $text = $this->doBlockLevels( $text, $linestart );
237 $this->replaceLinkHolders( $text );
239 # the position of the convert() call should not be changed. it
240 # assumes that the links are all replaces and the only thing left
241 # is the <nowiki> mark.
242 $text = $wgContLang->convert($text);
243 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
245 $text = $this->unstripNoWiki( $text, $this->mStripState
);
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
249 $text = Sanitizer
::normalizeCharReferences( $text );
251 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
252 $text = Parser
::tidy($text);
255 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
257 $this->mOutput
->setText( $text );
258 wfProfileOut( $fname );
260 return $this->mOutput
;
264 * Get a random string
269 function getRandomString() {
270 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
274 * Replaces all occurrences of <$tag>content</$tag> in the text
275 * with a random marker and returns the new text. the output parameter
276 * $content will be an associative array filled with data on the form
277 * $unique_marker => content.
279 * If $content is already set, the additional entries will be appended
280 * If $tag is set to STRIP_COMMENTS, the function will extract
281 * <!-- HTML comments -->
286 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
287 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
302 if( $tag == STRIP_COMMENTS
) {
303 $start = '/<!--()()/';
306 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
307 $end = "/<\\/$tag\\s*>/i";
310 while ( '' != $text ) {
311 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
313 if( count( $p ) < 4 ) {
320 $marker = $rnd . sprintf('%08X', $n++
);
321 $stripped .= $marker;
323 $tags[$marker] = "<$tag$attributes$empty>";
324 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
326 if ( $empty === '/' ) {
327 // Empty element tag, <tag />
328 $content[$marker] = null;
331 $q = preg_split( $end, $inside, 2 );
332 $content[$marker] = $q[0];
333 if( count( $q ) < 2 ) {
334 # No end tag -- let it run out to the end of the text.
345 * Wrapper function for extractTagsAndParams
346 * for cases where $tags and $params isn't needed
347 * i.e. where tags will never have params, like <nowiki>
352 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
353 $dummy_tags = array();
354 $dummy_params = array();
356 return Parser
::extractTagsAndParams( $tag, $text, $content,
357 $dummy_tags, $dummy_params, $uniq_prefix );
361 * Strips and renders nowiki, pre, math, hiero
362 * If $render is set, performs necessary rendering operations on plugins
363 * Returns the text, and fills an array with data needed in unstrip()
364 * If the $state is already a valid strip state, it adds to the state
366 * @param bool $stripcomments when set, HTML comments <!-- like this -->
367 * will be stripped in addition to other tags. This is important
368 * for section editing, where these comments cause confusion when
369 * counting the sections in the wikisource
373 function strip( $text, &$state, $stripcomments = false ) {
374 $render = ($this->mOutputType
== OT_HTML
);
375 $html_content = array();
376 $nowiki_content = array();
377 $math_content = array();
378 $pre_content = array();
379 $comment_content = array();
380 $ext_content = array();
382 $ext_params = array();
383 $gallery_content = array();
385 # Replace any instances of the placeholders
386 $uniq_prefix = $this->mUniqPrefix
;
387 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
392 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
393 foreach( $html_content as $marker => $content ) {
395 # Raw and unchecked for validity.
396 $html_content[$marker] = $content;
398 $html_content[$marker] = '<html>'.$content.'</html>';
404 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
405 foreach( $nowiki_content as $marker => $content ) {
407 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
409 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
414 if( $this->mOptions
->getUseTeX() ) {
415 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
416 foreach( $math_content as $marker => $content ){
418 $math_content[$marker] = renderMath( $content );
420 $math_content[$marker] = '<math>'.$content.'</math>';
426 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
427 foreach( $pre_content as $marker => $content ){
429 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
431 $pre_content[$marker] = '<pre>'.$content.'</pre>';
436 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
437 foreach( $gallery_content as $marker => $content ) {
438 require_once( 'ImageGallery.php' );
440 $gallery_content[$marker] = $this->renderImageGallery( $content );
442 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
448 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
449 foreach( $comment_content as $marker => $content ){
450 $comment_content[$marker] = '<!--'.$content.'-->';
455 foreach ( $this->mTagHooks
as $tag => $callback ) {
456 $ext_content[$tag] = array();
457 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
458 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
459 foreach( $ext_content[$tag] as $marker => $content ) {
460 $full_tag = $ext_tags[$tag][$marker];
461 $params = $ext_params[$tag][$marker];
463 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
465 if ( is_null( $content ) ) {
467 $ext_content[$tag][$marker] = $full_tag;
469 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
475 # Merge state with the pre-existing state, if there is one
477 $state['html'] = $state['html'] +
$html_content;
478 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
479 $state['math'] = $state['math'] +
$math_content;
480 $state['pre'] = $state['pre'] +
$pre_content;
481 $state['comment'] = $state['comment'] +
$comment_content;
482 $state['gallery'] = $state['gallery'] +
$gallery_content;
484 foreach( $ext_content as $tag => $array ) {
485 if ( array_key_exists( $tag, $state ) ) {
486 $state[$tag] = $state[$tag] +
$array;
491 'html' => $html_content,
492 'nowiki' => $nowiki_content,
493 'math' => $math_content,
494 'pre' => $pre_content,
495 'comment' => $comment_content,
496 'gallery' => $gallery_content,
503 * restores pre, math, and hiero removed by strip()
505 * always call unstripNoWiki() after this one
508 function unstrip( $text, &$state ) {
509 if ( !is_array( $state ) ) {
513 # Must expand in reverse order, otherwise nested tags will be corrupted
514 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
515 if( $tag != 'nowiki' && $tag != 'html' ) {
516 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
517 $text = str_replace( $uniq, $content, $text );
526 * always call this after unstrip() to preserve the order
530 function unstripNoWiki( $text, &$state ) {
531 if ( !is_array( $state ) ) {
535 # Must expand in reverse order, otherwise nested tags will be corrupted
536 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
537 $text = str_replace( key( $state['nowiki'] ), $content, $text );
542 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
543 $text = str_replace( key( $state['html'] ), $content, $text );
551 * Add an item to the strip state
552 * Returns the unique tag which must be inserted into the stripped text
553 * The tag will be replaced with the original text in unstrip()
557 function insertStripItem( $text, &$state ) {
558 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
565 'comment' => array(),
566 'gallery' => array(),
569 $state['item'][$rnd] = $text;
574 * Interface with html tidy, used if $wgUseTidy = true.
575 * If tidy isn't able to correct the markup, the original will be
576 * returned in all its glory with a warning comment appended.
578 * Either the external tidy program or the in-process tidy extension
579 * will be used depending on availability. Override the default
580 * $wgTidyInternal setting to disable the internal if it's not working.
582 * @param string $text Hideous HTML input
583 * @return string Corrected HTML output
587 function tidy( $text ) {
588 global $wgTidyInternal;
589 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
590 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
591 '<head><title>test</title></head><body>'.$text.'</body></html>';
592 if( $wgTidyInternal ) {
593 $correctedtext = Parser
::internalTidy( $wrappedtext );
595 $correctedtext = Parser
::externalTidy( $wrappedtext );
597 if( is_null( $correctedtext ) ) {
598 wfDebug( "Tidy error detected!\n" );
599 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
601 return $correctedtext;
605 * Spawn an external HTML tidy process and get corrected markup back from it.
610 function externalTidy( $text ) {
611 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
612 $fname = 'Parser::externalTidy';
613 wfProfileIn( $fname );
618 $descriptorspec = array(
619 0 => array('pipe', 'r'),
620 1 => array('pipe', 'w'),
621 2 => array('file', '/dev/null', 'a')
624 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
625 if (is_resource($process)) {
626 fwrite($pipes[0], $text);
628 while (!feof($pipes[1])) {
629 $cleansource .= fgets($pipes[1], 1024);
632 proc_close($process);
635 wfProfileOut( $fname );
637 if( $cleansource == '' && $text != '') {
638 // Some kind of error happened, so we couldn't get the corrected text.
639 // Just give up; we'll use the source text and append a warning.
647 * Use the HTML tidy PECL extension to use the tidy library in-process,
648 * saving the overhead of spawning a new process. Currently written to
649 * the PHP 4.3.x version of the extension, may not work on PHP 5.
651 * 'pear install tidy' should be able to compile the extension module.
656 function internalTidy( $text ) {
658 $fname = 'Parser::internalTidy';
659 wfProfileIn( $fname );
661 tidy_load_config( $wgTidyConf );
662 tidy_set_encoding( 'utf8' );
663 tidy_parse_string( $text );
665 if( tidy_get_status() == 2 ) {
666 // 2 is magic number for fatal error
667 // http://www.php.net/manual/en/function.tidy-get-status.php
670 $cleansource = tidy_get_output();
672 wfProfileOut( $fname );
677 * parse the wiki syntax used to render tables
681 function doTableStuff ( $t ) {
682 $fname = 'Parser::doTableStuff';
683 wfProfileIn( $fname );
685 $t = explode ( "\n" , $t ) ;
686 $td = array () ; # Is currently a td tag open?
687 $ltd = array () ; # Was it TD or TH?
688 $tr = array () ; # Is currently a tr tag open?
689 $ltr = array () ; # tr attributes
690 $indent_level = 0; # indent level of the table
691 foreach ( $t AS $k => $x )
694 $fc = substr ( $x , 0 , 1 ) ;
695 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
696 $indent_level = strlen( $matches[1] );
698 $attributes = $this->unstripForHTML( $matches[2] );
700 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
701 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
702 array_push ( $td , false ) ;
703 array_push ( $ltd , '' ) ;
704 array_push ( $tr , false ) ;
705 array_push ( $ltr , '' ) ;
707 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
708 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
709 $z = "</table>" . substr ( $x , 2);
710 $l = array_pop ( $ltd ) ;
711 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
712 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
713 if ( $l == "" ) $z = "<tr><td/></tr>" . $z ;
715 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
717 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
718 $x = substr ( $x , 1 ) ;
719 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
721 $l = array_pop ( $ltd ) ;
722 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
723 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
726 array_push ( $tr , false ) ;
727 array_push ( $td , false ) ;
728 array_push ( $ltd , '' ) ;
729 $attributes = $this->unstripForHTML( $x );
730 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
732 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
734 if ( '|+' == substr ( $x , 0 , 2 ) ) {
736 $x = substr ( $x , 1 ) ;
738 $after = substr ( $x , 1 ) ;
739 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
740 $after = explode ( '||' , $after ) ;
743 # Loop through each table cell
744 foreach ( $after AS $theline )
749 $tra = array_pop ( $ltr ) ;
750 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
751 array_push ( $tr , true ) ;
752 array_push ( $ltr , '' ) ;
755 $l = array_pop ( $ltd ) ;
756 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
757 if ( $fc == '|' ) $l = 'td' ;
758 else if ( $fc == '!' ) $l = 'th' ;
759 else if ( $fc == '+' ) $l = 'caption' ;
761 array_push ( $ltd , $l ) ;
764 $y = explode ( '|' , $theline , 2 ) ;
765 # Note that a '|' inside an invalid link should not
766 # be mistaken as delimiting cell parameters
767 if ( strpos( $y[0], '[[' ) !== false ) {
768 $y = array ($theline);
770 if ( count ( $y ) == 1 )
771 $y = "{$z}<{$l}>{$y[0]}" ;
773 $attributes = $this->unstripForHTML( $y[0] );
774 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
777 array_push ( $td , true ) ;
782 # Closing open td, tr && table
783 while ( count ( $td ) > 0 )
785 $l = array_pop ( $ltd ) ;
786 if ( $l == "" ) $t[] = "<tr><td/></tr>" ;
787 if ( array_pop ( $td ) ) $t[] = '</td>' ;
788 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
792 $t = implode ( "\n" , $t ) ;
793 wfProfileOut( $fname );
798 * Helper function for parse() that transforms wiki markup into
799 * HTML. Only called for $mOutputType == OT_HTML.
803 function internalParse( $text ) {
807 $fname = 'Parser::internalParse';
808 wfProfileIn( $fname );
810 # Remove <noinclude> tags and <includeonly> sections
811 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
812 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
813 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
815 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
816 $text = $this->replaceVariables( $text, $args );
818 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
820 $text = $this->doHeadings( $text );
821 if($this->mOptions
->getUseDynamicDates()) {
822 $df =& DateFormatter
::getInstance();
823 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
825 $text = $this->doAllQuotes( $text );
826 $text = $this->replaceInternalLinks( $text );
827 $text = $this->replaceExternalLinks( $text );
829 # replaceInternalLinks may sometimes leave behind
830 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
831 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
833 $text = $this->doMagicLinks( $text );
834 $text = $this->doTableStuff( $text );
835 $text = $this->formatHeadings( $text, $isMain );
837 wfProfileOut( $fname );
842 * Replace special strings like "ISBN xxx" and "RFC xxx" with
843 * magic external links.
847 function &doMagicLinks( &$text ) {
848 $text = $this->magicISBN( $text );
849 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
850 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
855 * Parse headers and return html
859 function doHeadings( $text ) {
860 $fname = 'Parser::doHeadings';
861 wfProfileIn( $fname );
862 for ( $i = 6; $i >= 1; --$i ) {
863 $h = str_repeat( '=', $i );
864 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
865 "<h{$i}>\\1</h{$i}>\\2", $text );
867 wfProfileOut( $fname );
872 * Replace single quotes with HTML markup
874 * @return string the altered text
876 function doAllQuotes( $text ) {
877 $fname = 'Parser::doAllQuotes';
878 wfProfileIn( $fname );
880 $lines = explode( "\n", $text );
881 foreach ( $lines as $line ) {
882 $outtext .= $this->doQuotes ( $line ) . "\n";
884 $outtext = substr($outtext, 0,-1);
885 wfProfileOut( $fname );
890 * Helper function for doAllQuotes()
893 function doQuotes( $text ) {
894 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
895 if ( count( $arr ) == 1 )
899 # First, do some preliminary work. This may shift some apostrophes from
900 # being mark-up to being text. It also counts the number of occurrences
901 # of bold and italics mark-ups.
905 foreach ( $arr as $r )
907 if ( ( $i %
2 ) == 1 )
909 # If there are ever four apostrophes, assume the first is supposed to
910 # be text, and the remaining three constitute mark-up for bold text.
911 if ( strlen( $arr[$i] ) == 4 )
916 # If there are more than 5 apostrophes in a row, assume they're all
917 # text except for the last 5.
918 else if ( strlen( $arr[$i] ) > 5 )
920 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
923 # Count the number of occurrences of bold and italics mark-ups.
924 # We are not counting sequences of five apostrophes.
925 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
926 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
927 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
932 # If there is an odd number of both bold and italics, it is likely
933 # that one of the bold ones was meant to be an apostrophe followed
934 # by italics. Which one we cannot know for certain, but it is more
935 # likely to be one that has a single-letter word before it.
936 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
939 $firstsingleletterword = -1;
940 $firstmultiletterword = -1;
942 foreach ( $arr as $r )
944 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
946 $x1 = substr ($arr[$i-1], -1);
947 $x2 = substr ($arr[$i-1], -2, 1);
949 if ($firstspace == -1) $firstspace = $i;
950 } else if ($x2 == ' ') {
951 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
953 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
959 # If there is a single-letter word, use it!
960 if ($firstsingleletterword > -1)
962 $arr [ $firstsingleletterword ] = "''";
963 $arr [ $firstsingleletterword-1 ] .= "'";
965 # If not, but there's a multi-letter word, use that one.
966 else if ($firstmultiletterword > -1)
968 $arr [ $firstmultiletterword ] = "''";
969 $arr [ $firstmultiletterword-1 ] .= "'";
971 # ... otherwise use the first one that has neither.
972 # (notice that it is possible for all three to be -1 if, for example,
973 # there is only one pentuple-apostrophe in the line)
974 else if ($firstspace > -1)
976 $arr [ $firstspace ] = "''";
977 $arr [ $firstspace-1 ] .= "'";
981 # Now let's actually convert our apostrophic mush to HTML!
990 if ($state == 'both')
997 if (strlen ($r) == 2)
1000 { $output .= '</i>'; $state = ''; }
1001 else if ($state == 'bi')
1002 { $output .= '</i>'; $state = 'b'; }
1003 else if ($state == 'ib')
1004 { $output .= '</b></i><b>'; $state = 'b'; }
1005 else if ($state == 'both')
1006 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1007 else # $state can be 'b' or ''
1008 { $output .= '<i>'; $state .= 'i'; }
1010 else if (strlen ($r) == 3)
1013 { $output .= '</b>'; $state = ''; }
1014 else if ($state == 'bi')
1015 { $output .= '</i></b><i>'; $state = 'i'; }
1016 else if ($state == 'ib')
1017 { $output .= '</b>'; $state = 'i'; }
1018 else if ($state == 'both')
1019 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1020 else # $state can be 'i' or ''
1021 { $output .= '<b>'; $state .= 'b'; }
1023 else if (strlen ($r) == 5)
1026 { $output .= '</b><i>'; $state = 'i'; }
1027 else if ($state == 'i')
1028 { $output .= '</i><b>'; $state = 'b'; }
1029 else if ($state == 'bi')
1030 { $output .= '</i></b>'; $state = ''; }
1031 else if ($state == 'ib')
1032 { $output .= '</b></i>'; $state = ''; }
1033 else if ($state == 'both')
1034 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1035 else # ($state == '')
1036 { $buffer = ''; $state = 'both'; }
1041 # Now close all remaining tags. Notice that the order is important.
1042 if ($state == 'b' ||
$state == 'ib')
1044 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1048 if ($state == 'both')
1049 $output .= '<b><i>'.$buffer.'</i></b>';
1055 * Replace external links
1057 * Note: this is all very hackish and the order of execution matters a lot.
1058 * Make sure to run maintenance/parserTests.php if you change this code.
1062 function replaceExternalLinks( $text ) {
1064 $fname = 'Parser::replaceExternalLinks';
1065 wfProfileIn( $fname );
1067 $sk =& $this->mOptions
->getSkin();
1069 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1071 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1074 while ( $i<count( $bits ) ) {
1076 $protocol = $bits[$i++
];
1077 $text = $bits[$i++
];
1078 $trail = $bits[$i++
];
1080 # The characters '<' and '>' (which were escaped by
1081 # removeHTMLtags()) should not be included in
1082 # URLs, per RFC 2396.
1083 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1084 $text = substr($url, $m2[0][1]) . ' ' . $text;
1085 $url = substr($url, 0, $m2[0][1]);
1088 # If the link text is an image URL, replace it with an <img> tag
1089 # This happened by accident in the original parser, but some people used it extensively
1090 $img = $this->maybeMakeExternalImage( $text );
1091 if ( $img !== false ) {
1097 # Set linktype for CSS - if URL==text, link is essentially free
1098 $linktype = ($text == $url) ?
'free' : 'text';
1100 # No link text, e.g. [http://domain.tld/some.link]
1101 if ( $text == '' ) {
1102 # Autonumber if allowed
1103 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1104 $text = '[' . ++
$this->mAutonumber
. ']';
1105 $linktype = 'autonumber';
1107 # Otherwise just use the URL
1108 $text = htmlspecialchars( $url );
1112 # Have link text, e.g. [http://domain.tld/some.link text]s
1114 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1117 $text = $wgContLang->markNoConversion($text);
1119 # Replace & from obsolete syntax with &.
1120 # All HTML entities will be escaped by makeExternalLink()
1121 $url = str_replace( '&', '&', $url );
1122 # Replace unnecessary URL escape codes with the referenced character
1123 # This prevents spammers from hiding links from the filters
1124 $url = Parser
::replaceUnusualEscapes( $url );
1126 # Process the trail (i.e. everything after this link up until start of the next link),
1127 # replacing any non-bracketed links
1128 $trail = $this->replaceFreeExternalLinks( $trail );
1130 # Use the encoded URL
1131 # This means that users can paste URLs directly into the text
1132 # Funny characters like ö aren't valid in URLs anyway
1133 # This was changed in August 2004
1134 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1136 # Register link in the output object
1137 $this->mOutput
->addExternalLink( $url );
1140 wfProfileOut( $fname );
1145 * Replace anything that looks like a URL with a link
1148 function replaceFreeExternalLinks( $text ) {
1150 $fname = 'Parser::replaceFreeExternalLinks';
1151 wfProfileIn( $fname );
1153 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1154 $s = array_shift( $bits );
1157 $sk =& $this->mOptions
->getSkin();
1159 while ( $i < count( $bits ) ){
1160 $protocol = $bits[$i++
];
1161 $remainder = $bits[$i++
];
1163 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1164 # Found some characters after the protocol that look promising
1165 $url = $protocol . $m[1];
1168 # The characters '<' and '>' (which were escaped by
1169 # removeHTMLtags()) should not be included in
1170 # URLs, per RFC 2396.
1171 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1172 $trail = substr($url, $m2[0][1]) . $trail;
1173 $url = substr($url, 0, $m2[0][1]);
1176 # Move trailing punctuation to $trail
1178 # If there is no left bracket, then consider right brackets fair game too
1179 if ( strpos( $url, '(' ) === false ) {
1183 $numSepChars = strspn( strrev( $url ), $sep );
1184 if ( $numSepChars ) {
1185 $trail = substr( $url, -$numSepChars ) . $trail;
1186 $url = substr( $url, 0, -$numSepChars );
1189 # Replace & from obsolete syntax with &.
1190 # All HTML entities will be escaped by makeExternalLink()
1191 # or maybeMakeExternalImage()
1192 $url = str_replace( '&', '&', $url );
1193 # Replace unnecessary URL escape codes with their equivalent characters
1194 $url = Parser
::replaceUnusualEscapes( $url );
1196 # Is this an external image?
1197 $text = $this->maybeMakeExternalImage( $url );
1198 if ( $text === false ) {
1199 # Not an image, make a link
1200 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1201 # Register it in the output object
1202 $this->mOutput
->addExternalLink( $url );
1204 $s .= $text . $trail;
1206 $s .= $protocol . $remainder;
1209 wfProfileOut( $fname );
1214 * Replace unusual URL escape codes with their equivalent characters
1219 function replaceUnusualEscapes( $url ) {
1220 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1221 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1225 * Callback function used in replaceUnusualEscapes().
1226 * Replaces unusual URL escape codes with their equivalent character
1230 function replaceUnusualEscapesCallback( $matches ) {
1231 $char = urldecode( $matches[0] );
1232 $ord = ord( $char );
1233 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1234 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1235 // No, shouldn't be escaped
1238 // Yes, leave it escaped
1244 * make an image if it's allowed, either through the global
1245 * option or through the exception
1248 function maybeMakeExternalImage( $url ) {
1249 $sk =& $this->mOptions
->getSkin();
1250 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1251 $imagesexception = !empty($imagesfrom);
1253 if ( $this->mOptions
->getAllowExternalImages()
1254 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1255 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1257 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1264 * Process [[ ]] wikilinks
1268 function replaceInternalLinks( $s ) {
1270 static $fname = 'Parser::replaceInternalLinks' ;
1272 wfProfileIn( $fname );
1274 wfProfileIn( $fname.'-setup' );
1276 # the % is needed to support urlencoded titles as well
1277 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1279 $sk =& $this->mOptions
->getSkin();
1281 #split the entire text string on occurences of [[
1282 $a = explode( '[[', ' ' . $s );
1283 #get the first element (all text up to first [[), and remove the space we added
1284 $s = array_shift( $a );
1285 $s = substr( $s, 1 );
1287 # Match a link having the form [[namespace:link|alternate]]trail
1289 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1290 # Match cases where there is no "]]", which might still be images
1291 static $e1_img = FALSE;
1292 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1293 # Match the end of a line for a word that's not followed by whitespace,
1294 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1295 $e2 = wfMsgForContent( 'linkprefix' );
1297 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1299 if( is_null( $this->mTitle
) ) {
1300 wfDebugDieBacktrace( 'nooo' );
1302 $nottalk = !$this->mTitle
->isTalkPage();
1304 if ( $useLinkPrefixExtension ) {
1305 if ( preg_match( $e2, $s, $m ) ) {
1306 $first_prefix = $m[2];
1308 $first_prefix = false;
1314 $selflink = $this->mTitle
->getPrefixedText();
1315 wfProfileOut( $fname.'-setup' );
1317 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1318 $useSubpages = $this->areSubpagesAllowed();
1320 # Loop for each link
1321 for ($k = 0; isset( $a[$k] ); $k++
) {
1323 if ( $useLinkPrefixExtension ) {
1324 wfProfileIn( $fname.'-prefixhandling' );
1325 if ( preg_match( $e2, $s, $m ) ) {
1333 $prefix = $first_prefix;
1334 $first_prefix = false;
1336 wfProfileOut( $fname.'-prefixhandling' );
1339 $might_be_img = false;
1341 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1343 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1344 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1345 # the real problem is with the $e1 regex
1348 # Still some problems for cases where the ] is meant to be outside punctuation,
1349 # and no image is in sight. See bug 2095.
1351 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1352 $text .= ']'; # so that replaceExternalLinks($text) works later
1355 # fix up urlencoded title texts
1356 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1358 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1359 $might_be_img = true;
1361 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1363 } else { # Invalid form; output directly
1364 $s .= $prefix . '[[' . $line ;
1368 # Don't allow internal links to pages containing
1369 # PROTO: where PROTO is a valid URL protocol; these
1370 # should be external links.
1371 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1372 $s .= $prefix . '[[' . $line ;
1376 # Make subpage if necessary
1377 if( $useSubpages ) {
1378 $link = $this->maybeDoSubpageLink( $m[1], $text );
1383 $noforce = (substr($m[1], 0, 1) != ':');
1385 # Strip off leading ':'
1386 $link = substr($link, 1);
1389 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1391 $s .= $prefix . '[[' . $line;
1395 #check other language variants of the link
1396 #if the article does not exist
1397 if( $checkVariantLink
1398 && $nt->getArticleID() == 0 ) {
1399 $wgContLang->findVariantLink($link, $nt);
1402 $ns = $nt->getNamespace();
1403 $iw = $nt->getInterWiki();
1405 if ($might_be_img) { # if this is actually an invalid link
1406 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1408 while (isset ($a[$k+
1]) ) {
1409 #look at the next 'line' to see if we can close it there
1410 $spliced = array_splice( $a, $k +
1, 1 );
1411 $next_line = array_shift( $spliced );
1412 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1413 # the first ]] closes the inner link, the second the image
1415 $text .= '[[' . $m[1];
1418 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1419 #if there's exactly one ]] that's fine, we'll keep looking
1420 $text .= '[[' . $m[0];
1422 #if $next_line is invalid too, we need look no further
1423 $text .= '[[' . $next_line;
1428 # we couldn't find the end of this imageLink, so output it raw
1429 #but don't ignore what might be perfectly normal links in the text we've examined
1430 $text = $this->replaceInternalLinks($text);
1431 $s .= $prefix . '[[' . $link . '|' . $text;
1432 # note: no $trail, because without an end, there *is* no trail
1435 } else { #it's not an image, so output it raw
1436 $s .= $prefix . '[[' . $link . '|' . $text;
1437 # note: no $trail, because without an end, there *is* no trail
1442 $wasblank = ( '' == $text );
1443 if( $wasblank ) $text = $link;
1446 # Link not escaped by : , create the various objects
1450 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1451 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1452 $s = rtrim($s . "\n");
1453 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1457 if ( $ns == NS_IMAGE
) {
1458 wfProfileIn( "$fname-image" );
1459 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1460 # recursively parse links inside the image caption
1461 # actually, this will parse them in any other parameters, too,
1462 # but it might be hard to fix that, and it doesn't matter ATM
1463 $text = $this->replaceExternalLinks($text);
1464 $text = $this->replaceInternalLinks($text);
1466 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1467 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1468 $this->mOutput
->addImage( $nt->getDBkey() );
1470 wfProfileOut( "$fname-image" );
1473 wfProfileOut( "$fname-image" );
1477 if ( $ns == NS_CATEGORY
) {
1478 wfProfileIn( "$fname-category" );
1479 $s = rtrim($s . "\n"); # bug 87
1482 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1483 $sortkey = $this->mTitle
->getText();
1485 $sortkey = $this->mTitle
->getPrefixedText();
1490 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1491 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1492 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1495 * Strip the whitespace Category links produce, see bug 87
1496 * @todo We might want to use trim($tmp, "\n") here.
1498 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1500 wfProfileOut( "$fname-category" );
1505 if( ( $nt->getPrefixedText() === $selflink ) &&
1506 ( $nt->getFragment() === '' ) ) {
1507 # Self-links are handled specially; generally de-link and change to bold.
1508 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1512 # Special and Media are pseudo-namespaces; no pages actually exist in them
1513 if( $ns == NS_MEDIA
) {
1514 $link = $sk->makeMediaLinkObj( $nt, $text );
1515 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1516 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1517 $this->mOutput
->addImage( $nt->getDBkey() );
1519 } elseif( $ns == NS_SPECIAL
) {
1520 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1522 } elseif( $ns == NS_IMAGE
) {
1523 $img = Image
::newFromTitle( $nt );
1524 if( $img->exists() ) {
1525 // Force a blue link if the file exists; may be a remote
1526 // upload on the shared repository, and we want to see its
1527 // auto-generated page.
1528 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1532 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1534 wfProfileOut( $fname );
1539 * Make a link placeholder. The text returned can be later resolved to a real link with
1540 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1541 * parsing of interwiki links, and secondly to allow all extistence checks and
1542 * article length checks (for stub links) to be bundled into a single query.
1545 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1546 if ( ! is_object($nt) ) {
1548 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1550 # Separate the link trail from the rest of the link
1551 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1553 if ( $nt->isExternal() ) {
1554 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1555 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1556 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1558 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1559 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1560 $this->mLinkHolders
['queries'][] = $query;
1561 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1562 $this->mLinkHolders
['titles'][] = $nt;
1564 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1571 * Render a forced-blue link inline; protect against double expansion of
1572 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1573 * Since this little disaster has to split off the trail text to avoid
1574 * breaking URLs in the following text without breaking trails on the
1575 * wiki links, it's been made into a horrible function.
1578 * @param string $text
1579 * @param string $query
1580 * @param string $trail
1581 * @param string $prefix
1582 * @return string HTML-wikitext mix oh yuck
1584 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1585 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1586 $sk =& $this->mOptions
->getSkin();
1587 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1588 return $this->armorLinks( $link ) . $trail;
1592 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1593 * going to go through further parsing steps before inline URL expansion.
1595 * In particular this is important when using action=render, which causes
1596 * full URLs to be included.
1598 * Oh man I hate our multi-layer parser!
1600 * @param string more-or-less HTML
1601 * @return string less-or-more HTML with NOPARSE bits
1603 function armorLinks( $text ) {
1604 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1605 "{$this->mUniqPrefix}NOPARSE$1", $text );
1609 * Return true if subpage links should be expanded on this page.
1612 function areSubpagesAllowed() {
1613 # Some namespaces don't allow subpages
1614 global $wgNamespacesWithSubpages;
1615 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1619 * Handle link to subpage if necessary
1620 * @param string $target the source of the link
1621 * @param string &$text the link text, modified as necessary
1622 * @return string the full name of the link
1625 function maybeDoSubpageLink($target, &$text) {
1628 # :Foobar -- override special treatment of prefix (images, language links)
1629 # /Foobar -- convert to CurrentPage/Foobar
1630 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1631 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1632 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1634 $fname = 'Parser::maybeDoSubpageLink';
1635 wfProfileIn( $fname );
1636 $ret = $target; # default return value is no change
1638 # Some namespaces don't allow subpages,
1639 # so only perform processing if subpages are allowed
1640 if( $this->areSubpagesAllowed() ) {
1641 # Look at the first character
1642 if( $target != '' && $target{0} == '/' ) {
1643 # / at end means we don't want the slash to be shown
1644 if( substr( $target, -1, 1 ) == '/' ) {
1645 $target = substr( $target, 1, -1 );
1648 $noslash = substr( $target, 1 );
1651 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1652 if( '' === $text ) {
1654 } # this might be changed for ugliness reasons
1656 # check for .. subpage backlinks
1658 $nodotdot = $target;
1659 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1661 $nodotdot = substr( $nodotdot, 3 );
1663 if($dotdotcount > 0) {
1664 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1665 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1666 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1667 # / at the end means don't show full path
1668 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1669 $nodotdot = substr( $nodotdot, 0, -1 );
1670 if( '' === $text ) {
1674 $nodotdot = trim( $nodotdot );
1675 if( $nodotdot != '' ) {
1676 $ret .= '/' . $nodotdot;
1683 wfProfileOut( $fname );
1688 * Used by doBlockLevels()
1691 /* private */ function closeParagraph() {
1693 if ( '' != $this->mLastSection
) {
1694 $result = '</' . $this->mLastSection
. ">\n";
1696 $this->mInPre
= false;
1697 $this->mLastSection
= '';
1700 # getCommon() returns the length of the longest common substring
1701 # of both arguments, starting at the beginning of both.
1703 /* private */ function getCommon( $st1, $st2 ) {
1704 $fl = strlen( $st1 );
1705 $shorter = strlen( $st2 );
1706 if ( $fl < $shorter ) { $shorter = $fl; }
1708 for ( $i = 0; $i < $shorter; ++
$i ) {
1709 if ( $st1{$i} != $st2{$i} ) { break; }
1713 # These next three functions open, continue, and close the list
1714 # element appropriate to the prefix character passed into them.
1716 /* private */ function openList( $char ) {
1717 $result = $this->closeParagraph();
1719 if ( '*' == $char ) { $result .= '<ul><li>'; }
1720 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1721 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1722 else if ( ';' == $char ) {
1723 $result .= '<dl><dt>';
1724 $this->mDTopen
= true;
1726 else { $result = '<!-- ERR 1 -->'; }
1731 /* private */ function nextItem( $char ) {
1732 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1733 else if ( ':' == $char ||
';' == $char ) {
1735 if ( $this->mDTopen
) { $close = '</dt>'; }
1736 if ( ';' == $char ) {
1737 $this->mDTopen
= true;
1738 return $close . '<dt>';
1740 $this->mDTopen
= false;
1741 return $close . '<dd>';
1744 return '<!-- ERR 2 -->';
1747 /* private */ function closeList( $char ) {
1748 if ( '*' == $char ) { $text = '</li></ul>'; }
1749 else if ( '#' == $char ) { $text = '</li></ol>'; }
1750 else if ( ':' == $char ) {
1751 if ( $this->mDTopen
) {
1752 $this->mDTopen
= false;
1753 $text = '</dt></dl>';
1755 $text = '</dd></dl>';
1758 else { return '<!-- ERR 3 -->'; }
1764 * Make lists from lines starting with ':', '*', '#', etc.
1767 * @return string the lists rendered as HTML
1769 function doBlockLevels( $text, $linestart ) {
1770 $fname = 'Parser::doBlockLevels';
1771 wfProfileIn( $fname );
1773 # Parsing through the text line by line. The main thing
1774 # happening here is handling of block-level elements p, pre,
1775 # and making lists from lines starting with * # : etc.
1777 $textLines = explode( "\n", $text );
1779 $lastPrefix = $output = '';
1780 $this->mDTopen
= $inBlockElem = false;
1782 $paragraphStack = false;
1784 if ( !$linestart ) {
1785 $output .= array_shift( $textLines );
1787 foreach ( $textLines as $oLine ) {
1788 $lastPrefixLength = strlen( $lastPrefix );
1789 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1790 $preOpenMatch = preg_match('/<pre/i', $oLine );
1791 if ( !$this->mInPre
) {
1792 # Multiple prefixes may abut each other for nested lists.
1793 $prefixLength = strspn( $oLine, '*#:;' );
1794 $pref = substr( $oLine, 0, $prefixLength );
1797 $pref2 = str_replace( ';', ':', $pref );
1798 $t = substr( $oLine, $prefixLength );
1799 $this->mInPre
= !empty($preOpenMatch);
1801 # Don't interpret any other prefixes in preformatted text
1803 $pref = $pref2 = '';
1808 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1809 # Same as the last item, so no need to deal with nesting or opening stuff
1810 $output .= $this->nextItem( substr( $pref, -1 ) );
1811 $paragraphStack = false;
1813 if ( substr( $pref, -1 ) == ';') {
1814 # The one nasty exception: definition lists work like this:
1815 # ; title : definition text
1816 # So we check for : in the remainder text to split up the
1817 # title and definition, without b0rking links.
1819 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1821 $output .= $term . $this->nextItem( ':' );
1824 } elseif( $prefixLength ||
$lastPrefixLength ) {
1825 # Either open or close a level...
1826 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1827 $paragraphStack = false;
1829 while( $commonPrefixLength < $lastPrefixLength ) {
1830 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1831 --$lastPrefixLength;
1833 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1834 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1836 while ( $prefixLength > $commonPrefixLength ) {
1837 $char = substr( $pref, $commonPrefixLength, 1 );
1838 $output .= $this->openList( $char );
1840 if ( ';' == $char ) {
1841 # FIXME: This is dupe of code above
1842 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1844 $output .= $term . $this->nextItem( ':' );
1847 ++
$commonPrefixLength;
1849 $lastPrefix = $pref2;
1851 if( 0 == $prefixLength ) {
1852 wfProfileIn( "$fname-paragraph" );
1853 # No prefix (not in list)--go to paragraph mode
1854 // XXX: use a stack for nestable elements like span, table and div
1855 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1856 $closematch = preg_match(
1857 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1858 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1859 if ( $openmatch or $closematch ) {
1860 $paragraphStack = false;
1861 $output .= $this->closeParagraph();
1862 if ( $preOpenMatch and !$preCloseMatch ) {
1863 $this->mInPre
= true;
1865 if ( $closematch ) {
1866 $inBlockElem = false;
1868 $inBlockElem = true;
1870 } else if ( !$inBlockElem && !$this->mInPre
) {
1871 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1873 if ($this->mLastSection
!= 'pre') {
1874 $paragraphStack = false;
1875 $output .= $this->closeParagraph().'<pre>';
1876 $this->mLastSection
= 'pre';
1878 $t = substr( $t, 1 );
1881 if ( '' == trim($t) ) {
1882 if ( $paragraphStack ) {
1883 $output .= $paragraphStack.'<br />';
1884 $paragraphStack = false;
1885 $this->mLastSection
= 'p';
1887 if ($this->mLastSection
!= 'p' ) {
1888 $output .= $this->closeParagraph();
1889 $this->mLastSection
= '';
1890 $paragraphStack = '<p>';
1892 $paragraphStack = '</p><p>';
1896 if ( $paragraphStack ) {
1897 $output .= $paragraphStack;
1898 $paragraphStack = false;
1899 $this->mLastSection
= 'p';
1900 } else if ($this->mLastSection
!= 'p') {
1901 $output .= $this->closeParagraph().'<p>';
1902 $this->mLastSection
= 'p';
1907 wfProfileOut( "$fname-paragraph" );
1909 // somewhere above we forget to get out of pre block (bug 785)
1910 if($preCloseMatch && $this->mInPre
) {
1911 $this->mInPre
= false;
1913 if ($paragraphStack === false) {
1917 while ( $prefixLength ) {
1918 $output .= $this->closeList( $pref2{$prefixLength-1} );
1921 if ( '' != $this->mLastSection
) {
1922 $output .= '</' . $this->mLastSection
. '>';
1923 $this->mLastSection
= '';
1926 wfProfileOut( $fname );
1931 * Split up a string on ':', ignoring any occurences inside
1932 * <a>..</a> or <span>...</span>
1933 * @param string $str the string to split
1934 * @param string &$before set to everything before the ':'
1935 * @param string &$after set to everything after the ':'
1936 * return string the position of the ':', or false if none found
1938 function findColonNoLinks($str, &$before, &$after) {
1939 # I wonder if we should make this count all tags, not just <a>
1940 # and <span>. That would prevent us from matching a ':' that
1941 # comes in the middle of italics other such formatting....
1943 $fname = 'Parser::findColonNoLinks';
1944 wfProfileIn( $fname );
1947 $colon = strpos($str, ':', $pos);
1949 if ($colon !== false) {
1950 $before = substr($str, 0, $colon);
1951 $after = substr($str, $colon +
1);
1953 # Skip any ':' within <a> or <span> pairs
1954 $a = substr_count($before, '<a');
1955 $s = substr_count($before, '<span');
1956 $ca = substr_count($before, '</a>');
1957 $cs = substr_count($before, '</span>');
1959 if ($a <= $ca and $s <= $cs) {
1960 # Tags are balanced before ':'; ok
1965 } while ($colon !== false);
1966 wfProfileOut( $fname );
1971 * Return value of a magic variable (like PAGENAME)
1975 function getVariableValue( $index ) {
1976 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1979 * Some of these require message or data lookups and can be
1980 * expensive to check many times.
1982 static $varCache = array();
1983 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1984 if ( isset( $varCache[$index] ) )
1985 return $varCache[$index];
1988 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1991 case MAG_CURRENTMONTH
:
1992 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1993 case MAG_CURRENTMONTHNAME
:
1994 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
1995 case MAG_CURRENTMONTHNAMEGEN
:
1996 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
1997 case MAG_CURRENTMONTHABBREV
:
1998 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
1999 case MAG_CURRENTDAY
:
2000 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2001 case MAG_CURRENTDAY2
:
2002 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2004 return $this->mTitle
->getText();
2006 return $this->mTitle
->getPartialURL();
2007 case MAG_FULLPAGENAME
:
2008 return $this->mTitle
->getPrefixedText();
2009 case MAG_FULLPAGENAMEE
:
2010 return $this->mTitle
->getPrefixedURL();
2011 case MAG_REVISIONID
:
2012 return $this->mRevisionId
;
2014 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2015 case MAG_NAMESPACEE
:
2016 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2017 case MAG_CURRENTDAYNAME
:
2018 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2019 case MAG_CURRENTYEAR
:
2020 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2021 case MAG_CURRENTTIME
:
2022 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2023 case MAG_CURRENTWEEK
:
2024 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2025 // int to remove the padding
2026 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2027 case MAG_CURRENTDOW
:
2028 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2029 case MAG_NUMBEROFARTICLES
:
2030 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2031 case MAG_NUMBEROFFILES
:
2032 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2037 case MAG_SERVERNAME
:
2038 return $wgServerName;
2039 case MAG_SCRIPTPATH
:
2040 return $wgScriptPath;
2043 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2051 * initialise the magic variables (like CURRENTMONTHNAME)
2055 function initialiseVariables() {
2056 $fname = 'Parser::initialiseVariables';
2057 wfProfileIn( $fname );
2058 global $wgVariableIDs;
2059 $this->mVariables
= array();
2060 foreach ( $wgVariableIDs as $id ) {
2061 $mw =& MagicWord
::get( $id );
2062 $mw->addToArray( $this->mVariables
, $id );
2064 wfProfileOut( $fname );
2068 * parse any parentheses in format ((title|part|part))
2069 * and call callbacks to get a replacement text for any found piece
2071 * @param string $text The text to parse
2072 * @param array $callbacks rules in form:
2073 * '{' => array( # opening parentheses
2074 * 'end' => '}', # closing parentheses
2075 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2076 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2081 function replace_callback ($text, $callbacks) {
2082 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2083 $lastOpeningBrace = -1; # last not closed parentheses
2085 for ($i = 0; $i < strlen($text); $i++
) {
2086 # check for any opening brace
2089 foreach ($callbacks as $key => $value) {
2090 $pos = strpos ($text, $key, $i);
2091 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2097 if ($lastOpeningBrace >= 0) {
2098 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2100 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2105 $pos = strpos ($text, '|', $i);
2107 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2118 # found openning brace, lets add it to parentheses stack
2119 if (null != $rule) {
2120 $piece = array('brace' => $text[$i],
2121 'braceEnd' => $rule['end'],
2126 # count openning brace characters
2127 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2132 $piece['startAt'] = $i+
1;
2133 $piece['partStart'] = $i+
1;
2135 # we need to add to stack only if openning brace count is enough for any given rule
2136 foreach ($rule['cb'] as $cnt => $fn) {
2137 if ($piece['count'] >= $cnt) {
2138 $lastOpeningBrace ++
;
2139 $openingBraceStack[$lastOpeningBrace] = $piece;
2146 else if ($lastOpeningBrace >= 0) {
2147 # first check if it is a closing brace
2148 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2149 # lets check if it is enough characters for closing brace
2151 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2154 # if there are more closing parentheses than opening ones, we parse less
2155 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2156 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2158 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2160 $matchingCallback = null;
2161 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2162 if ($count >= $cnt && $matchingCount < $cnt) {
2163 $matchingCount = $cnt;
2164 $matchingCallback = $fn;
2168 if ($matchingCount == 0) {
2173 # lets set a title or last part (if '|' was found)
2174 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2175 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2177 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2179 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2180 $pieceEnd = $i +
$matchingCount;
2182 if( is_callable( $matchingCallback ) ) {
2184 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2185 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2186 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2187 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2189 # finally we can call a user callback and replace piece of text
2190 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2191 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2192 $i = $pieceStart +
strlen($replaceWith) - 1;
2195 # null value for callback means that parentheses should be parsed, but not replaced
2196 $i +
= $matchingCount - 1;
2199 # reset last openning parentheses, but keep it in case there are unused characters
2200 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2201 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2202 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2205 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2206 $openingBraceStack[$lastOpeningBrace--] = null;
2208 if ($matchingCount < $piece['count']) {
2209 $piece['count'] -= $matchingCount;
2210 $piece['startAt'] -= $matchingCount;
2211 $piece['partStart'] = $piece['startAt'];
2212 # do we still qualify for any callback with remaining count?
2213 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2214 if ($piece['count'] >= $cnt) {
2215 $lastOpeningBrace ++
;
2216 $openingBraceStack[$lastOpeningBrace] = $piece;
2224 # lets set a title if it is a first separator, or next part otherwise
2225 if ($text[$i] == '|') {
2226 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2227 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2228 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2231 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2233 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2242 * Replace magic variables, templates, and template arguments
2243 * with the appropriate text. Templates are substituted recursively,
2244 * taking care to avoid infinite loops.
2246 * Note that the substitution depends on value of $mOutputType:
2247 * OT_WIKI: only {{subst:}} templates
2248 * OT_MSG: only magic variables
2249 * OT_HTML: all templates and magic variables
2251 * @param string $tex The text to transform
2252 * @param array $args Key-value pairs representing template parameters to substitute
2253 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2256 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2257 # Prevent too big inclusions
2258 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2262 $fname = 'Parser::replaceVariables';
2263 wfProfileIn( $fname );
2265 # This function is called recursively. To keep track of arguments we need a stack:
2266 array_push( $this->mArgStack
, $args );
2268 $braceCallbacks = array();
2270 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2272 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2273 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2275 $callbacks = array();
2276 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2277 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2278 $text = $this->replace_callback ($text, $callbacks);
2280 array_pop( $this->mArgStack
);
2282 wfProfileOut( $fname );
2287 * Replace magic variables
2290 function variableSubstitution( $matches ) {
2291 $fname = 'Parser::variableSubstitution';
2292 $varname = $matches[1];
2293 wfProfileIn( $fname );
2294 if ( !$this->mVariables
) {
2295 $this->initialiseVariables();
2298 if ( $this->mOutputType
== OT_WIKI
) {
2299 # Do only magic variables prefixed by SUBST
2300 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2301 if (!$mwSubst->matchStartAndRemove( $varname ))
2303 # Note that if we don't substitute the variable below,
2304 # we don't remove the {{subst:}} magic word, in case
2305 # it is a template rather than a magic variable.
2307 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2308 $id = $this->mVariables
[$varname];
2309 $text = $this->getVariableValue( $id );
2310 $this->mOutput
->mContainsOldMagic
= true;
2312 $text = $matches[0];
2314 wfProfileOut( $fname );
2318 # Split template arguments
2319 function getTemplateArgs( $argsString ) {
2320 if ( $argsString === '' ) {
2324 $args = explode( '|', substr( $argsString, 1 ) );
2326 # If any of the arguments contains a '[[' but no ']]', it needs to be
2327 # merged with the next arg because the '|' character between belongs
2328 # to the link syntax and not the template parameter syntax.
2329 $argc = count($args);
2331 for ( $i = 0; $i < $argc-1; $i++
) {
2332 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2333 $args[$i] .= '|'.$args[$i+
1];
2334 array_splice($args, $i+
1, 1);
2344 * Return the text of a template, after recursively
2345 * replacing any variables or templates within the template.
2347 * @param array $piece The parts of the template
2348 * $piece['text']: matched text
2349 * $piece['title']: the title, i.e. the part before the |
2350 * $piece['parts']: the parameter array
2351 * @return string the text of the template
2354 function braceSubstitution( $piece ) {
2356 $fname = 'Parser::braceSubstitution';
2357 wfProfileIn( $fname );
2360 $found = false; # $text has been filled
2361 $nowiki = false; # wiki markup in $text should be escaped
2362 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2363 $noargs = false; # Don't replace triple-brace arguments in $text
2364 $replaceHeadings = false; # Make the edit section links go to the template not the article
2365 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2366 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2368 # Title object, where $text came from
2373 # $part1 is the bit before the first |, and must contain only title characters
2374 # $args is a list of arguments, starting from index 0, not including $part1
2376 $part1 = $piece['title'];
2377 # If the third subpattern matched anything, it will start with |
2379 if (null == $piece['parts']) {
2380 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2381 if ($replaceWith != $piece['text']) {
2382 $text = $replaceWith;
2389 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2390 $argc = count( $args );
2394 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2395 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2396 # One of two possibilities is true:
2397 # 1) Found SUBST but not in the PST phase
2398 # 2) Didn't find SUBST and in the PST phase
2399 # In either case, return without further processing
2400 $text = $piece['text'];
2407 # MSG, MSGNW, INT and RAW
2410 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2411 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2414 # Remove obsolete MSG:
2415 $mwMsg =& MagicWord
::get( MAG_MSG
);
2416 $mwMsg->matchStartAndRemove( $part1 );
2420 $mwRaw =& MagicWord
::get( MAG_RAW
);
2421 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2422 $forceRawInterwiki = true;
2425 # Check if it is an internal message
2426 $mwInt =& MagicWord
::get( MAG_INT
);
2427 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2428 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2429 $text = $linestart . wfMsgReal( $part1, $args, true );
2437 # Check for NS: (namespace expansion)
2438 $mwNs = MagicWord
::get( MAG_NS
);
2439 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2440 if ( intval( $part1 ) ||
$part1 == "0" ) {
2441 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2444 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2445 if ( !is_null( $index ) ) {
2446 $text = $linestart . $wgContLang->getNsText( $index );
2453 # LCFIRST, UCFIRST, LC and UC
2455 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2456 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2457 $lc =& MagicWord
::get( MAG_LC
);
2458 $uc =& MagicWord
::get( MAG_UC
);
2459 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2460 $text = $linestart . $wgContLang->lcfirst( $part1 );
2462 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2463 $text = $linestart . $wgContLang->ucfirst( $part1 );
2465 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2466 $text = $linestart . $wgContLang->lc( $part1 );
2468 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2469 $text = $linestart . $wgContLang->uc( $part1 );
2474 # LOCALURL and FULLURL
2476 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2477 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2478 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2479 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2482 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2483 $func = 'getLocalURL';
2484 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2485 $func = 'escapeLocalURL';
2486 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2487 $func = 'getFullURL';
2488 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2489 $func = 'escapeFullURL';
2494 if ( $func !== false ) {
2495 $title = Title
::newFromText( $part1 );
2496 if ( !is_null( $title ) ) {
2498 $text = $linestart . $title->$func( $args[0] );
2500 $text = $linestart . $title->$func();
2508 if ( !$found && $argc == 1 ) {
2509 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2510 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2511 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2517 if ( !$found && $argc >= 2 ) {
2518 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2519 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2520 if ($argc==2) {$args[2]=$args[1];}
2521 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2526 # Template table test
2528 # Did we encounter this template already? If yes, it is in the cache
2529 # and we need to check for loops.
2530 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2533 # Infinite loop test
2534 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2538 $text = $linestart .
2539 '{{' . $part1 . '}}' .
2540 '<!-- WARNING: template loop detected -->';
2541 wfDebug( "$fname: template loop broken at '$part1'\n" );
2543 # set $text to cached message.
2544 $text = $linestart . $this->mTemplates
[$piece['title']];
2548 # Load from database
2549 $lastPathLevel = $this->mTemplatePath
;
2552 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2553 if ($subpage !== '') {
2554 $ns = $this->mTitle
->getNamespace();
2556 $title = Title
::newFromText( $part1, $ns );
2558 if ( !is_null( $title ) ) {
2559 if ( !$title->isExternal() ) {
2560 # Check for excessive inclusion
2561 $dbk = $title->getPrefixedDBkey();
2562 if ( $this->incrementIncludeCount( $dbk ) ) {
2563 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2564 # Capture special page output
2565 $text = SpecialPage
::capturePath( $title );
2566 if ( is_string( $text ) ) {
2571 $this->disableCache();
2574 $articleContent = $this->fetchTemplate( $title );
2575 if ( $articleContent !== false ) {
2577 $text = $articleContent;
2578 $replaceHeadings = true;
2583 # If the title is valid but undisplayable, make a link to it
2584 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2585 $text = '[['.$title->getPrefixedText().']]';
2588 } elseif ( $title->isTrans() ) {
2589 // Interwiki transclusion
2590 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2591 $text = $this->interwikiTransclude( $title, 'render' );
2595 $text = $this->interwikiTransclude( $title, 'raw' );
2596 $replaceHeadings = true;
2601 # Template cache array insertion
2602 # Use the original $piece['title'] not the mangled $part1, so that
2603 # modifiers such as RAW: produce separate cache entries
2605 $this->mTemplates
[$piece['title']] = $text;
2606 $text = $linestart . $text;
2611 # Recursive parsing, escaping and link table handling
2612 # Only for HTML output
2613 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2614 $text = wfEscapeWikiText( $text );
2615 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2617 # Clean up argument array
2618 $assocArgs = array();
2620 foreach( $args as $arg ) {
2621 $eqpos = strpos( $arg, '=' );
2622 if ( $eqpos === false ) {
2623 $assocArgs[$index++
] = $arg;
2625 $name = trim( substr( $arg, 0, $eqpos ) );
2626 $value = trim( substr( $arg, $eqpos+
1 ) );
2627 if ( $value === false ) {
2630 if ( $name !== false ) {
2631 $assocArgs[$name] = $value;
2636 # Add a new element to the templace recursion path
2637 $this->mTemplatePath
[$part1] = 1;
2641 # If there are any <onlyinclude> tags, only include them
2642 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2643 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2645 foreach ($m[1] as $piece)
2648 # Remove <noinclude> sections and <includeonly> tags
2649 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2650 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2652 if( $this->mOutputType
== OT_HTML
) {
2653 # Strip <nowiki>, <pre>, etc.
2654 $text = $this->strip( $text, $this->mStripState
);
2655 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2657 $text = $this->replaceVariables( $text, $assocArgs );
2659 # If the template begins with a table or block-level
2660 # element, it should be treated as beginning a new line.
2661 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2662 $text = "\n" . $text;
2664 } elseif ( !$noargs ) {
2665 # $noparse and !$noargs
2666 # Just replace the arguments, not any double-brace items
2667 # This is used for rendered interwiki transclusion
2668 $text = $this->replaceVariables( $text, $assocArgs, true );
2671 # Prune lower levels off the recursion check path
2672 $this->mTemplatePath
= $lastPathLevel;
2675 wfProfileOut( $fname );
2676 return $piece['text'];
2679 # Replace raw HTML by a placeholder
2680 # Add a blank line preceding, to prevent it from mucking up
2681 # immediately preceding headings
2682 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2684 # replace ==section headers==
2685 # XXX this needs to go away once we have a better parser.
2686 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2687 if( !is_null( $title ) )
2688 $encodedname = base64_encode($title->getPrefixedDBkey());
2690 $encodedname = base64_encode("");
2691 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2692 PREG_SPLIT_DELIM_CAPTURE
);
2695 for( $i = 0; $i < count($m); $i +
= 2 ) {
2697 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2699 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2703 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2704 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2705 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2713 # Prune lower levels off the recursion check path
2714 $this->mTemplatePath
= $lastPathLevel;
2717 wfProfileOut( $fname );
2718 return $piece['text'];
2720 wfProfileOut( $fname );
2726 * Fetch the unparsed text of a template and register a reference to it.
2728 function fetchTemplate( $title ) {
2730 // Loop to fetch the article, with up to 1 redirect
2731 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2732 $rev = Revision
::newFromTitle( $title );
2733 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2737 $text = $rev->getText();
2738 if ( $text === false ) {
2742 $title = Title
::newFromRedirect( $text );
2748 * Transclude an interwiki link.
2750 function interwikiTransclude( $title, $action ) {
2751 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2753 if (!$wgEnableScaryTranscluding)
2754 return wfMsg('scarytranscludedisabled');
2756 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2757 // But we'll handle it generally anyway
2758 if ( $title->getNamespace() ) {
2759 // Use the canonical namespace, which should work anywhere
2760 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2762 $articleName = $title->getDBkey();
2765 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2766 $url .= "?action=$action";
2767 if (strlen($url) > 255)
2768 return wfMsg('scarytranscludetoolong');
2769 return $this->fetchScaryTemplateMaybeFromCache($url);
2772 function fetchScaryTemplateMaybeFromCache($url) {
2773 global $wgTranscludeCacheExpiry;
2774 $dbr =& wfGetDB(DB_SLAVE
);
2775 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2776 array('tc_url' => $url));
2778 $time = $obj->tc_time
;
2779 $text = $obj->tc_contents
;
2780 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2785 $text = wfGetHTTP($url);
2787 return wfMsg('scarytranscludefailed', $url);
2789 $dbw =& wfGetDB(DB_MASTER
);
2790 $dbw->replace('transcache', array('tc_url'), array(
2792 'tc_time' => time(),
2793 'tc_contents' => $text));
2799 * Triple brace replacement -- used for template arguments
2802 function argSubstitution( $matches ) {
2803 $arg = trim( $matches['title'] );
2804 $text = $matches['text'];
2805 $inputArgs = end( $this->mArgStack
);
2807 if ( array_key_exists( $arg, $inputArgs ) ) {
2808 $text = $inputArgs[$arg];
2809 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2810 $text = $matches['parts'][0];
2817 * Returns true if the function is allowed to include this entity
2820 function incrementIncludeCount( $dbk ) {
2821 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2822 $this->mIncludeCount
[$dbk] = 0;
2824 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2832 * This function accomplishes several tasks:
2833 * 1) Auto-number headings if that option is enabled
2834 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2835 * 3) Add a Table of contents on the top for users who have enabled the option
2836 * 4) Auto-anchor headings
2838 * It loops through all headlines, collects the necessary data, then splits up the
2839 * string and re-inserts the newly formatted headlines.
2841 * @param string $text
2842 * @param boolean $isMain
2845 function formatHeadings( $text, $isMain=true ) {
2846 global $wgMaxTocLevel, $wgContLang;
2848 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2850 $forceTocHere = false;
2851 if( !$this->mTitle
->userCanEdit() ) {
2854 $showEditLink = $this->mOptions
->getEditSection();
2857 # Inhibit editsection links if requested in the page
2858 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2859 if( $esw->matchAndRemove( $text ) ) {
2862 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2864 $mw =& MagicWord
::get( MAG_NOTOC
);
2865 if( $mw->matchAndRemove( $text ) ) {
2869 # Get all headlines for numbering them and adding funky stuff like [edit]
2870 # links - this is for later, but we need the number of headlines right now
2871 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2873 # if there are fewer than 4 headlines in the article, do not show TOC
2874 if( $numMatches < 4 ) {
2878 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2879 # override above conditions and always show TOC at that place
2881 $mw =& MagicWord
::get( MAG_TOC
);
2882 if($mw->match( $text ) ) {
2884 $forceTocHere = true;
2886 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2887 # override above conditions and always show TOC above first header
2888 $mw =& MagicWord
::get( MAG_FORCETOC
);
2889 if ($mw->matchAndRemove( $text ) ) {
2894 # Never ever show TOC if no headers
2895 if( $numMatches < 1 ) {
2899 # We need this to perform operations on the HTML
2900 $sk =& $this->mOptions
->getSkin();
2904 $sectionCount = 0; # headlineCount excluding template sections
2906 # Ugh .. the TOC should have neat indentation levels which can be
2907 # passed to the skin functions. These are determined here
2911 $sublevelCount = array();
2912 $levelCount = array();
2919 foreach( $matches[3] as $headline ) {
2921 $templatetitle = '';
2922 $templatesection = 0;
2925 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2927 $templatetitle = base64_decode($mat[1]);
2928 $templatesection = 1 +
(int)base64_decode($mat[2]);
2929 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2933 $prevlevel = $level;
2934 $prevtoclevel = $toclevel;
2936 $level = $matches[1][$headlineCount];
2938 if( $doNumberHeadings ||
$doShowToc ) {
2940 if ( $level > $prevlevel ) {
2941 # Increase TOC level
2943 $sublevelCount[$toclevel] = 0;
2944 $toc .= $sk->tocIndent();
2946 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2947 # Decrease TOC level, find level to jump to
2949 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2950 # Can only go down to level 1
2953 for ($i = $toclevel; $i > 0; $i--) {
2954 if ( $levelCount[$i] == $level ) {
2955 # Found last matching level
2959 elseif ( $levelCount[$i] < $level ) {
2960 # Found first matching level below current level
2967 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2970 # No change in level, end TOC line
2971 $toc .= $sk->tocLineEnd();
2974 $levelCount[$toclevel] = $level;
2976 # count number of headlines for each level
2977 @$sublevelCount[$toclevel]++
;
2979 for( $i = 1; $i <= $toclevel; $i++
) {
2980 if( !empty( $sublevelCount[$i] ) ) {
2984 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2990 # The canonized header is a version of the header text safe to use for links
2991 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2992 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2993 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2995 # Remove link placeholders by the link text.
2996 # <!--LINK number-->
2998 # link text with suffix
2999 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3000 "\$this->mLinkHolders['texts'][\$1]",
3001 $canonized_headline );
3002 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3003 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3004 $canonized_headline );
3007 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3008 $tocline = trim( $canonized_headline );
3009 $canonized_headline = Sanitizer
::escapeId( $tocline );
3010 $refers[$headlineCount] = $canonized_headline;
3012 # count how many in assoc. array so we can track dupes in anchors
3013 @$refers[$canonized_headline]++
;
3014 $refcount[$headlineCount]=$refers[$canonized_headline];
3016 # Don't number the heading if it is the only one (looks silly)
3017 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3018 # the two are different if the line contains a link
3019 $headline=$numbering . ' ' . $headline;
3022 # Create the anchor for linking from the TOC to the section
3023 $anchor = $canonized_headline;
3024 if($refcount[$headlineCount] > 1 ) {
3025 $anchor .= '_' . $refcount[$headlineCount];
3027 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3028 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3030 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3031 if ( empty( $head[$headlineCount] ) ) {
3032 $head[$headlineCount] = '';
3035 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3037 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
3040 # give headline the correct <h#> tag
3041 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3049 $toc .= $sk->tocUnindent( $toclevel - 1 );
3050 $toc = $sk->tocList( $toc );
3053 # split up and insert constructed headlines
3055 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3058 foreach( $blocks as $block ) {
3059 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3060 # This is the [edit] link that appears for the top block of text when
3061 # section editing is enabled
3063 # Disabled because it broke block formatting
3064 # For example, a bullet point in the top line
3065 # $full .= $sk->editSectionLink(0);
3068 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3069 # Top anchor now in skin
3073 if( !empty( $head[$i] ) ) {
3079 $mw =& MagicWord
::get( MAG_TOC
);
3080 return $mw->replace( $toc, $full );
3087 * Return an HTML link for the "ISBN 123456" text
3090 function magicISBN( $text ) {
3091 $fname = 'Parser::magicISBN';
3092 wfProfileIn( $fname );
3094 $a = split( 'ISBN ', ' '.$text );
3095 if ( count ( $a ) < 2 ) {
3096 wfProfileOut( $fname );
3099 $text = substr( array_shift( $a ), 1);
3100 $valid = '0123456789-Xx';
3102 foreach ( $a as $x ) {
3103 $isbn = $blank = '' ;
3104 while ( ' ' == $x{0} ) {
3106 $x = substr( $x, 1 );
3108 if ( $x == '' ) { # blank isbn
3109 $text .= "ISBN $blank";
3112 while ( strstr( $valid, $x{0} ) != false ) {
3114 $x = substr( $x, 1 );
3116 $num = str_replace( '-', '', $isbn );
3117 $num = str_replace( ' ', '', $num );
3118 $num = str_replace( 'x', 'X', $num );
3121 $text .= "ISBN $blank$x";
3123 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3124 $text .= '<a href="' .
3125 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3126 "\" class=\"internal\">ISBN $isbn</a>";
3130 wfProfileOut( $fname );
3135 * Return an HTML link for the "RFC 1234" text
3138 * @param string $text Text to be processed
3139 * @param string $keyword Magic keyword to use (default RFC)
3140 * @param string $urlmsg Interface message to use (default rfcurl)
3143 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3145 $valid = '0123456789';
3148 $a = split( $keyword, ' '.$text );
3149 if ( count ( $a ) < 2 ) {
3152 $text = substr( array_shift( $a ), 1);
3154 /* Check if keyword is preceed by [[.
3155 * This test is made here cause of the array_shift above
3156 * that prevent the test to be done in the foreach.
3158 if ( substr( $text, -2 ) == '[[' ) {
3162 foreach ( $a as $x ) {
3163 /* token might be empty if we have RFC RFC 1234 */
3171 /** remove and save whitespaces in $blank */
3172 while ( $x{0} == ' ' ) {
3174 $x = substr( $x, 1 );
3177 /** remove and save the rfc number in $id */
3178 while ( strstr( $valid, $x{0} ) != false ) {
3180 $x = substr( $x, 1 );
3184 /* call back stripped spaces*/
3185 $text .= $keyword.$blank.$x;
3186 } elseif( $internal ) {
3188 $text .= $keyword.$id.$x;
3190 /* build the external link*/
3191 $url = wfMsg( $urlmsg, $id);
3192 $sk =& $this->mOptions
->getSkin();
3193 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3194 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3197 /* Check if the next RFC keyword is preceed by [[ */
3198 $internal = ( substr($x,-2) == '[[' );
3204 * Transform wiki markup when saving a page by doing \r\n -> \n
3205 * conversion, substitting signatures, {{subst:}} templates, etc.
3207 * @param string $text the text to transform
3208 * @param Title &$title the Title object for the current article
3209 * @param User &$user the User object describing the current user
3210 * @param ParserOptions $options parsing options
3211 * @param bool $clearState whether to clear the parser state first
3212 * @return string the altered wiki markup
3215 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3216 $this->mOptions
= $options;
3217 $this->mTitle
=& $title;
3218 $this->mOutputType
= OT_WIKI
;
3220 if ( $clearState ) {
3221 $this->clearState();
3224 $stripState = false;
3228 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3229 $text = $this->strip( $text, $stripState, true );
3230 $text = $this->pstPass2( $text, $user );
3231 $text = $this->unstrip( $text, $stripState );
3232 $text = $this->unstripNoWiki( $text, $stripState );
3237 * Pre-save transform helper function
3240 function pstPass2( $text, &$user ) {
3241 global $wgContLang, $wgLocaltimezone;
3243 /* Note: This is the timestamp saved as hardcoded wikitext to
3244 * the database, we use $wgContLang here in order to give
3245 * everyone the same signiture and use the default one rather
3246 * than the one selected in each users preferences.
3248 if ( isset( $wgLocaltimezone ) ) {
3249 $oldtz = getenv( 'TZ' );
3250 putenv( 'TZ='.$wgLocaltimezone );
3252 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3253 ' (' . date( 'T' ) . ')';
3254 if ( isset( $wgLocaltimezone ) ) {
3255 putenv( 'TZ='.$oldtz );
3258 # Variable replacement
3259 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3260 $text = $this->replaceVariables( $text );
3263 $sigText = $this->getUserSig( $user );
3264 $text = strtr( $text, array(
3266 '~~~~' => "$sigText $d",
3270 # Context links: [[|name]] and [[name (context)|]]
3272 global $wgLegalTitleChars;
3273 $tc = "[$wgLegalTitleChars]";
3274 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3276 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3277 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3279 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3280 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3281 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3282 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3284 $t = $this->mTitle
->getText();
3285 if ( preg_match( $conpat, $t, $m ) ) {
3288 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3289 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3290 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3292 if ( '' == $context ) {
3293 $text = preg_replace( $p2, '[[\\1]]', $text );
3295 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3298 # Trim trailing whitespace
3299 # MAG_END (__END__) tag allows for trailing
3300 # whitespace to be deliberately included
3301 $text = rtrim( $text );
3302 $mw =& MagicWord
::get( MAG_END
);
3303 $mw->matchAndRemove( $text );
3309 * Fetch the user's signature text, if any, and normalize to
3310 * validated, ready-to-insert wikitext.
3316 function getUserSig( &$user ) {
3319 $username = $user->getName();
3320 $nickname = $user->getOption( 'nickname' );
3321 $nickname = $nickname === '' ?
$username : $nickname;
3323 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3324 # Sig. might contain markup; validate this
3325 if( $this->validateSig( $nickname ) !== false ) {
3326 # Validated; clean up (if needed) and return it
3327 return( $this->cleanSig( $nickname ) );
3329 # Failed to validate; fall back to the default
3330 $nickname = $username;
3331 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3335 # If we're still here, make it a link to the user page
3336 $userpage = $user->getUserPage();
3337 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3341 * Check that the user's signature contains no bad XML
3343 * @param string $text
3344 * @return mixed An expanded string, or false if invalid.
3346 function validateSig( $text ) {
3347 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3351 * Clean up signature text
3353 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3354 * 2) Substitute all transclusions
3356 * @param string $text
3357 * @return string Signature text
3359 function cleanSig( $text ) {
3360 $substWord = MagicWord
::get( MAG_SUBST
);
3361 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3362 $substText = '{{' . $substWord->getSynonym( 0 );
3364 $text = preg_replace( $substRegex, $substText, $text );
3365 $text = preg_replace( '/~{3,5}/', '', $text );
3366 $text = $this->replaceVariables( $text );
3372 * Set up some variables which are usually set up in parse()
3373 * so that an external function can call some class members with confidence
3376 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3377 $this->mTitle
=& $title;
3378 $this->mOptions
= $options;
3379 $this->mOutputType
= $outputType;
3380 if ( $clearState ) {
3381 $this->clearState();
3386 * Transform a MediaWiki message by replacing magic variables.
3388 * @param string $text the text to transform
3389 * @param ParserOptions $options options
3390 * @return string the text with variables substituted
3393 function transformMsg( $text, $options ) {
3395 static $executing = false;
3397 $fname = "Parser::transformMsg";
3399 # Guard against infinite recursion
3405 wfProfileIn($fname);
3407 $this->mTitle
= $wgTitle;
3408 $this->mOptions
= $options;
3409 $this->mOutputType
= OT_MSG
;
3410 $this->clearState();
3411 $text = $this->replaceVariables( $text );
3414 wfProfileOut($fname);
3419 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3420 * Callback will be called with the text within
3421 * Transform and return the text within
3425 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3426 * @param mixed $callback The callback function (and object) to use for the tag
3428 * @return The old value of the mTagHooks array associated with the hook
3430 function setHook( $tag, $callback ) {
3431 $oldVal = @$this->mTagHooks
[$tag];
3432 $this->mTagHooks
[$tag] = $callback;
3438 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3439 * Placeholders created in Skin::makeLinkObj()
3440 * Returns an array of links found, indexed by PDBK:
3444 * $options is a bit field, RLH_FOR_UPDATE to select for update
3446 function replaceLinkHolders( &$text, $options = 0 ) {
3448 global $wgOutputReplace;
3450 $fname = 'Parser::replaceLinkHolders';
3451 wfProfileIn( $fname );
3455 $sk =& $this->mOptions
->getSkin();
3456 $linkCache =& LinkCache
::singleton();
3458 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3459 wfProfileIn( $fname.'-check' );
3460 $dbr =& wfGetDB( DB_SLAVE
);
3461 $page = $dbr->tableName( 'page' );
3462 $threshold = $wgUser->getOption('stubthreshold');
3465 asort( $this->mLinkHolders
['namespaces'] );
3469 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3471 $title = $this->mLinkHolders
['titles'][$key];
3473 # Skip invalid entries.
3474 # Result will be ugly, but prevents crash.
3475 if ( is_null( $title ) ) {
3478 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3480 # Check if it's a static known link, e.g. interwiki
3481 if ( $title->isAlwaysKnown() ) {
3482 $colours[$pdbk] = 1;
3483 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3484 $colours[$pdbk] = 1;
3485 $this->mOutput
->addLink( $title, $id );
3486 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3487 $colours[$pdbk] = 0;
3489 # Not in the link cache, add it to the query
3490 if ( !isset( $current ) ) {
3492 $query = "SELECT page_id, page_namespace, page_title";
3493 if ( $threshold > 0 ) {
3494 $query .= ', page_len, page_is_redirect';
3496 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3497 } elseif ( $current != $ns ) {
3499 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3504 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3509 if ( $options & RLH_FOR_UPDATE
) {
3510 $query .= ' FOR UPDATE';
3513 $res = $dbr->query( $query, $fname );
3515 # Fetch data and form into an associative array
3516 # non-existent = broken
3519 while ( $s = $dbr->fetchObject($res) ) {
3520 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3521 $pdbk = $title->getPrefixedDBkey();
3522 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3523 $this->mOutput
->addLink( $title, $s->page_id
);
3525 if ( $threshold > 0 ) {
3526 $size = $s->page_len
;
3527 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3528 $colours[$pdbk] = 1;
3530 $colours[$pdbk] = 2;
3533 $colours[$pdbk] = 1;
3537 wfProfileOut( $fname.'-check' );
3539 # Construct search and replace arrays
3540 wfProfileIn( $fname.'-construct' );
3541 $wgOutputReplace = array();
3542 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3543 $pdbk = $pdbks[$key];
3544 $searchkey = "<!--LINK $key-->";
3545 $title = $this->mLinkHolders
['titles'][$key];
3546 if ( empty( $colours[$pdbk] ) ) {
3547 $linkCache->addBadLinkObj( $title );
3548 $colours[$pdbk] = 0;
3549 $this->mOutput
->addLink( $title, 0 );
3550 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3551 $this->mLinkHolders
['texts'][$key],
3552 $this->mLinkHolders
['queries'][$key] );
3553 } elseif ( $colours[$pdbk] == 1 ) {
3554 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3555 $this->mLinkHolders
['texts'][$key],
3556 $this->mLinkHolders
['queries'][$key] );
3557 } elseif ( $colours[$pdbk] == 2 ) {
3558 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3559 $this->mLinkHolders
['texts'][$key],
3560 $this->mLinkHolders
['queries'][$key] );
3563 wfProfileOut( $fname.'-construct' );
3566 wfProfileIn( $fname.'-replace' );
3568 $text = preg_replace_callback(
3569 '/(<!--LINK .*?-->)/',
3570 "wfOutputReplaceMatches",
3573 wfProfileOut( $fname.'-replace' );
3576 # Now process interwiki link holders
3577 # This is quite a bit simpler than internal links
3578 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3579 wfProfileIn( $fname.'-interwiki' );
3580 # Make interwiki link HTML
3581 $wgOutputReplace = array();
3582 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3583 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3584 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3587 $text = preg_replace_callback(
3588 '/<!--IWLINK (.*?)-->/',
3589 "wfOutputReplaceMatches",
3591 wfProfileOut( $fname.'-interwiki' );
3594 wfProfileOut( $fname );
3599 * Replace <!--LINK--> link placeholders with plain text of links
3600 * (not HTML-formatted).
3601 * @param string $text
3604 function replaceLinkHoldersText( $text ) {
3606 global $wgOutputReplace;
3608 $fname = 'Parser::replaceLinkHoldersText';
3609 wfProfileIn( $fname );
3611 $text = preg_replace_callback(
3612 '/<!--(LINK|IWLINK) (.*?)-->/',
3613 array( &$this, 'replaceLinkHoldersTextCallback' ),
3616 wfProfileOut( $fname );
3621 * @param array $matches
3625 function replaceLinkHoldersTextCallback( $matches ) {
3626 $type = $matches[1];
3628 if( $type == 'LINK' ) {
3629 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3630 return $this->mLinkHolders
['texts'][$key];
3632 } elseif( $type == 'IWLINK' ) {
3633 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3634 return $this->mInterwikiLinkHolders
['texts'][$key];
3641 * Renders an image gallery from a text with one line per image.
3642 * text labels may be given by using |-style alternative text. E.g.
3643 * Image:one.jpg|The number "1"
3644 * Image:tree.jpg|A tree
3645 * given as text will return the HTML of a gallery with two images,
3646 * labeled 'The number "1"' and
3649 function renderImageGallery( $text ) {
3651 $parserOptions = new ParserOptions
;
3652 $localParser = new Parser();
3654 $ig = new ImageGallery();
3655 $ig->setShowBytes( false );
3656 $ig->setShowFilename( false );
3657 $lines = explode( "\n", $text );
3659 foreach ( $lines as $line ) {
3660 # match lines like these:
3661 # Image:someimage.jpg|This is some image
3662 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3664 if ( count( $matches ) == 0 ) {
3667 $nt =& Title
::newFromText( $matches[1] );
3668 if( is_null( $nt ) ) {
3669 # Bogus title. Ignore these so we don't bomb out later.
3672 if ( isset( $matches[3] ) ) {
3673 $label = $matches[3];
3678 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3679 $html = $pout->getText();
3681 $ig->add( new Image( $nt ), $html );
3682 $this->mOutput
->addImage( $nt->getDBkey() );
3684 return $ig->toHTML();
3688 * Parse image options text and use it to make an image
3690 function makeImage( &$nt, $options ) {
3691 global $wgContLang, $wgUseImageResize, $wgUser;
3695 # Check if the options text is of the form "options|alt text"
3697 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3698 # * left no resizing, just left align. label is used for alt= only
3699 # * right same, but right aligned
3700 # * none same, but not aligned
3701 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3702 # * center center the image
3703 # * framed Keep original image size, no magnify-button.
3705 $part = explode( '|', $options);
3707 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3708 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3709 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3710 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3711 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3712 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3713 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3714 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3717 $width = $height = $framed = $thumb = false;
3718 $manual_thumb = '' ;
3720 foreach( $part as $key => $val ) {
3721 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3723 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3724 # use manually specified thumbnail
3726 $manual_thumb = $match;
3727 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3728 # remember to set an alignment, don't render immediately
3730 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3731 # remember to set an alignment, don't render immediately
3733 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3734 # remember to set an alignment, don't render immediately
3736 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3737 # remember to set an alignment, don't render immediately
3739 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3740 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3741 # $match is the image width in pixels
3742 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3743 $width = intval( $m[1] );
3744 $height = intval( $m[2] );
3746 $width = intval($match);
3748 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3754 # Strip bad stuff out of the alt text
3755 $alt = $this->replaceLinkHoldersText( $caption );
3756 $alt = Sanitizer
::stripAllTags( $alt );
3758 # Linker does the rest
3759 $sk =& $this->mOptions
->getSkin();
3760 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3764 * Set a flag in the output object indicating that the content is dynamic and
3765 * shouldn't be cached.
3767 function disableCache() {
3768 $this->mOutput
->mCacheTime
= -1;
3772 * Callback from the Sanitizer for expanding items found in HTML attribute
3773 * values, so they can be safely tested and escaped.
3774 * @param string $text
3775 * @param array $args
3779 function attributeStripCallback( &$text, $args ) {
3780 $text = $this->replaceVariables( $text, $args );
3781 $text = $this->unstripForHTML( $text );
3785 function unstripForHTML( $text ) {
3786 $text = $this->unstrip( $text, $this->mStripState
);
3787 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3795 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3796 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3797 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3803 function getTags() { return array_keys( $this->mTagHooks
); }
3809 * @package MediaWiki
3813 var $mText, # The output text
3814 $mLanguageLinks, # List of the full text of language links, in the order they appear
3815 $mCategories, # Map of category names to sort keys
3816 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3817 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3818 $mVersion, # Compatibility check
3819 $mTitleText, # title text of the chosen language variant
3820 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3821 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3822 $mImages, # DB keys of the images used, in the array key only
3823 $mExternalLinks; # External link URLs, in the key only
3825 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3826 $containsOldMagic = false, $titletext = '' )
3828 $this->mText
= $text;
3829 $this->mLanguageLinks
= $languageLinks;
3830 $this->mCategories
= $categoryLinks;
3831 $this->mContainsOldMagic
= $containsOldMagic;
3832 $this->mCacheTime
= '';
3833 $this->mVersion
= MW_PARSER_VERSION
;
3834 $this->mTitleText
= $titletext;
3835 $this->mLinks
= array();
3836 $this->mTemplates
= array();
3837 $this->mImages
= array();
3838 $this->mExternalLinks
= array();
3841 function getText() { return $this->mText
; }
3842 function getLanguageLinks() { return $this->mLanguageLinks
; }
3843 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3844 function &getCategories() { return $this->mCategories
; }
3845 function getCacheTime() { return $this->mCacheTime
; }
3846 function getTitleText() { return $this->mTitleText
; }
3847 function &getLinks() { return $this->mLinks
; }
3848 function &getTemplates() { return $this->mTemplates
; }
3849 function &getImages() { return $this->mImages
; }
3850 function &getExternalLinks() { return $this->mExternalLinks
; }
3852 function containsOldMagic() { return $this->mContainsOldMagic
; }
3853 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3854 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3855 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3856 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3857 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3858 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3860 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3861 function addImage( $name ) { $this->mImages
[$name] = 1; }
3862 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3863 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3865 function addLink( $title, $id ) {
3866 $ns = $title->getNamespace();
3867 $dbk = $title->getDBkey();
3868 if ( !isset( $this->mLinks
[$ns] ) ) {
3869 $this->mLinks
[$ns] = array();
3871 $this->mLinks
[$ns][$dbk] = $id;
3874 function addTemplate( $title, $id ) {
3875 $ns = $title->getNamespace();
3876 $dbk = $title->getDBkey();
3877 if ( !isset( $this->mTemplates
[$ns] ) ) {
3878 $this->mTemplates
[$ns] = array();
3880 $this->mTemplates
[$ns][$dbk] = $id;
3887 function merge( $other ) {
3888 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3889 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3890 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3894 * Return true if this cached output object predates the global or
3895 * per-article cache invalidation timestamps, or if it comes from
3896 * an incompatible older version.
3898 * @param string $touched the affected article's last touched timestamp
3902 function expired( $touched ) {
3903 global $wgCacheEpoch;
3904 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3905 $this->getCacheTime() < $touched ||
3906 $this->getCacheTime() <= $wgCacheEpoch ||
3907 !isset( $this->mVersion
) ||
3908 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3913 * Set options of the Parser
3915 * @package MediaWiki
3919 # All variables are private
3920 var $mUseTeX; # Use texvc to expand <math> tags
3921 var $mUseDynamicDates; # Use DateFormatter to format dates
3922 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3923 var $mAllowExternalImages; # Allow external images inline
3924 var $mAllowExternalImagesFrom; # If not, any exception?
3925 var $mSkin; # Reference to the preferred skin
3926 var $mDateFormat; # Date format index
3927 var $mEditSection; # Create "edit section" links
3928 var $mNumberHeadings; # Automatically number headings
3929 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3930 var $mTidy; # Ask for tidy cleanup
3932 function getUseTeX() { return $this->mUseTeX
; }
3933 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3934 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3935 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3936 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3937 function &getSkin() { return $this->mSkin
; }
3938 function getDateFormat() { return $this->mDateFormat
; }
3939 function getEditSection() { return $this->mEditSection
; }
3940 function getNumberHeadings() { return $this->mNumberHeadings
; }
3941 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3942 function getTidy() { return $this->mTidy
; }
3944 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3945 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3946 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3947 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3948 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3949 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3950 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3951 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3952 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3953 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
3954 function setSkin( &$x ) { $this->mSkin
=& $x; }
3956 function ParserOptions() {
3958 $this->initialiseFromUser( $wgUser );
3962 * Get parser options
3965 function newFromUser( &$user ) {
3966 $popts = new ParserOptions
;
3967 $popts->initialiseFromUser( $user );
3971 /** Get user options */
3972 function initialiseFromUser( &$userInput ) {
3973 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3974 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3975 $fname = 'ParserOptions::initialiseFromUser';
3976 wfProfileIn( $fname );
3977 if ( !$userInput ) {
3979 $user->setLoaded( true );
3981 $user =& $userInput;
3984 $this->mUseTeX
= $wgUseTeX;
3985 $this->mUseDynamicDates
= $wgUseDynamicDates;
3986 $this->mInterwikiMagic
= $wgInterwikiMagic;
3987 $this->mAllowExternalImages
= $wgAllowExternalImages;
3988 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3989 wfProfileIn( $fname.'-skin' );
3990 $this->mSkin
=& $user->getSkin();
3991 wfProfileOut( $fname.'-skin' );
3992 $this->mDateFormat
= $user->getOption( 'date' );
3993 $this->mEditSection
= true;
3994 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3995 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3996 $this->mTidy
= false;
3997 wfProfileOut( $fname );
4002 * Callback function used by Parser::replaceLinkHolders()
4003 * to substitute link placeholders.
4005 function &wfOutputReplaceMatches( $matches ) {
4006 global $wgOutputReplace;
4007 return $wgOutputReplace[$matches[1]];
4011 * Return the total number of articles
4013 function wfNumberOfArticles() {
4014 global $wgNumberOfArticles;
4017 return $wgNumberOfArticles;
4021 * Return the number of files
4023 function wfNumberOfFiles() {
4024 $fname = 'Parser::wfNumberOfFiles';
4026 wfProfileIn( $fname );
4027 $dbr =& wfGetDB( DB_SLAVE
);
4028 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4029 wfProfileOut( $fname );
4035 * Get various statistics from the database
4038 function wfLoadSiteStats() {
4039 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4040 $fname = 'wfLoadSiteStats';
4042 if ( -1 != $wgNumberOfArticles ) return;
4043 $dbr =& wfGetDB( DB_SLAVE
);
4044 $s = $dbr->selectRow( 'site_stats',
4045 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4046 array( 'ss_row_id' => 1 ), $fname
4049 if ( $s === false ) {
4052 $wgTotalViews = $s->ss_total_views
;
4053 $wgTotalEdits = $s->ss_total_edits
;
4054 $wgNumberOfArticles = $s->ss_good_articles
;
4060 * Basically replacing " > and < with HTML entities ( ", >, <)
4062 * @param string $in Text that might contain HTML tags
4063 * @return string Escaped string
4065 function wfEscapeHTMLTagsOnly( $in ) {
4067 array( '"', '>', '<' ),
4068 array( '"', '>', '<' ),