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;
104 var $mOptions, // ParserOptions object
105 $mTitle, // Title context, used for self-link rendering and similar things
106 $mOutputType, // Output type, one of the OT_xxx constants
107 $mTemplates, // cache of already loaded templates, avoids
108 // multiple SQL queries for the same string
109 $mTemplatePath, // stores an unsorted hash of all the templates already loaded
110 // in this path. Used for loop detection.
111 $mIWTransData = array(),
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
122 $this->mTemplates
= array();
123 $this->mTemplatePath
= array();
124 $this->mTagHooks
= array();
133 function clearState() {
134 $this->mOutput
= new ParserOutput
;
135 $this->mAutonumber
= 0;
136 $this->mLastSection
= '';
137 $this->mDTopen
= false;
138 $this->mVariables
= false;
139 $this->mIncludeCount
= array();
140 $this->mStripState
= array();
141 $this->mArgStack
= array();
142 $this->mInPre
= false;
143 $this->mInterwikiLinkHolders
= array(
147 $this->mLinkHolders
= array(
148 'namespaces' => array(),
150 'queries' => array(),
154 $this->mRevisionId
= null;
155 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
157 wfRunHooks( 'ParserClearState', array( &$this ) );
161 * Accessor for mUniqPrefix.
165 function UniqPrefix() {
166 return $this->mUniqPrefix
;
170 * Convert wikitext to HTML
171 * Do not call this function recursively.
174 * @param string $text Text we want to parse
175 * @param Title &$title A title object
176 * @param array $options
177 * @param boolean $linestart
178 * @param boolean $clearState
179 * @param int $revid number to pass in {{REVISIONID}}
180 * @return ParserOutput a ParserOutput
182 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
184 * First pass--just handle <nowiki> sections, pass the rest off
185 * to internalParse() which does all the real work.
188 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
189 $fname = 'Parser::parse';
190 wfProfileIn( $fname );
196 $this->mOptions
= $options;
197 $this->mTitle
=& $title;
198 $this->mRevisionId
= $revid;
199 $this->mOutputType
= OT_HTML
;
201 $this->mStripState
= NULL;
203 //$text = $this->strip( $text, $this->mStripState );
204 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
205 $x =& $this->mStripState
;
207 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
208 $text = $this->strip( $text, $x );
209 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
211 # Hook to suspend the parser in this state
212 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
213 wfProfileOut( $fname );
217 $text = $this->internalParse( $text );
219 $text = $this->unstrip( $text, $this->mStripState
);
221 # Clean up special characters, only run once, next-to-last before doBlockLevels
223 # french spaces, last one Guillemet-left
224 # only if there is something before the space
225 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
226 # french spaces, Guillemet-right
227 '/(\\302\\253) /' => '\\1 ',
228 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
230 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
233 $text = $this->doBlockLevels( $text, $linestart );
235 $this->replaceLinkHolders( $text );
237 # the position of the convert() call should not be changed. it
238 # assumes that the links are all replaces and the only thing left
239 # is the <nowiki> mark.
240 $text = $wgContLang->convert($text);
241 $this->mOutput
->setTitleText($wgContLang->getParsedTitle());
243 $text = $this->unstripNoWiki( $text, $this->mStripState
);
245 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
247 $text = Sanitizer
::normalizeCharReferences( $text );
249 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
250 $text = Parser
::tidy($text);
253 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
255 $this->mOutput
->setText( $text );
256 wfProfileOut( $fname );
258 return $this->mOutput
;
262 * Get a random string
267 function getRandomString() {
268 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
272 * Replaces all occurrences of <$tag>content</$tag> in the text
273 * with a random marker and returns the new text. the output parameter
274 * $content will be an associative array filled with data on the form
275 * $unique_marker => content.
277 * If $content is already set, the additional entries will be appended
278 * If $tag is set to STRIP_COMMENTS, the function will extract
279 * <!-- HTML comments -->
284 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
285 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
300 if( $tag == STRIP_COMMENTS
) {
301 $start = '/<!--()()/';
304 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
305 $end = "/<\\/$tag\\s*>/i";
308 while ( '' != $text ) {
309 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
311 if( count( $p ) < 4 ) {
318 $marker = $rnd . sprintf('%08X', $n++
);
319 $stripped .= $marker;
321 $tags[$marker] = "<$tag$attributes$empty>";
322 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
324 if ( $empty === '/' ) {
325 // Empty element tag, <tag />
326 $content[$marker] = null;
329 $q = preg_split( $end, $inside, 2 );
330 $content[$marker] = $q[0];
331 if( count( $q ) < 2 ) {
332 # No end tag -- let it run out to the end of the text.
343 * Wrapper function for extractTagsAndParams
344 * for cases where $tags and $params isn't needed
345 * i.e. where tags will never have params, like <nowiki>
350 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
351 $dummy_tags = array();
352 $dummy_params = array();
354 return Parser
::extractTagsAndParams( $tag, $text, $content,
355 $dummy_tags, $dummy_params, $uniq_prefix );
359 * Strips and renders nowiki, pre, math, hiero
360 * If $render is set, performs necessary rendering operations on plugins
361 * Returns the text, and fills an array with data needed in unstrip()
362 * If the $state is already a valid strip state, it adds to the state
364 * @param bool $stripcomments when set, HTML comments <!-- like this -->
365 * will be stripped in addition to other tags. This is important
366 * for section editing, where these comments cause confusion when
367 * counting the sections in the wikisource
371 function strip( $text, &$state, $stripcomments = false ) {
372 $render = ($this->mOutputType
== OT_HTML
);
373 $html_content = array();
374 $nowiki_content = array();
375 $math_content = array();
376 $pre_content = array();
377 $comment_content = array();
378 $ext_content = array();
380 $ext_params = array();
381 $gallery_content = array();
383 # Replace any instances of the placeholders
384 $uniq_prefix = $this->mUniqPrefix
;
385 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
390 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
391 foreach( $html_content as $marker => $content ) {
393 # Raw and unchecked for validity.
394 $html_content[$marker] = $content;
396 $html_content[$marker] = '<html>'.$content.'</html>';
402 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
403 foreach( $nowiki_content as $marker => $content ) {
405 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
407 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
412 if( $this->mOptions
->getUseTeX() ) {
413 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
414 foreach( $math_content as $marker => $content ){
416 $math_content[$marker] = renderMath( $content );
418 $math_content[$marker] = '<math>'.$content.'</math>';
424 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
425 foreach( $pre_content as $marker => $content ){
427 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
429 $pre_content[$marker] = '<pre>'.$content.'</pre>';
434 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
435 foreach( $gallery_content as $marker => $content ) {
436 require_once( 'ImageGallery.php' );
438 $gallery_content[$marker] = $this->renderImageGallery( $content );
440 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
446 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
447 foreach( $comment_content as $marker => $content ){
448 $comment_content[$marker] = '<!--'.$content.'-->';
453 foreach ( $this->mTagHooks
as $tag => $callback ) {
454 $ext_content[$tag] = array();
455 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
456 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
457 foreach( $ext_content[$tag] as $marker => $content ) {
458 $full_tag = $ext_tags[$tag][$marker];
459 $params = $ext_params[$tag][$marker];
461 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
463 if ( is_null( $content ) ) {
465 $ext_content[$tag][$marker] = $full_tag;
467 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
473 # Merge state with the pre-existing state, if there is one
475 $state['html'] = $state['html'] +
$html_content;
476 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
477 $state['math'] = $state['math'] +
$math_content;
478 $state['pre'] = $state['pre'] +
$pre_content;
479 $state['comment'] = $state['comment'] +
$comment_content;
480 $state['gallery'] = $state['gallery'] +
$gallery_content;
482 foreach( $ext_content as $tag => $array ) {
483 if ( array_key_exists( $tag, $state ) ) {
484 $state[$tag] = $state[$tag] +
$array;
489 'html' => $html_content,
490 'nowiki' => $nowiki_content,
491 'math' => $math_content,
492 'pre' => $pre_content,
493 'comment' => $comment_content,
494 'gallery' => $gallery_content,
501 * restores pre, math, and hiero removed by strip()
503 * always call unstripNoWiki() after this one
506 function unstrip( $text, &$state ) {
507 if ( !is_array( $state ) ) {
511 # Must expand in reverse order, otherwise nested tags will be corrupted
512 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
513 if( $tag != 'nowiki' && $tag != 'html' ) {
514 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
515 $text = str_replace( $uniq, $content, $text );
524 * always call this after unstrip() to preserve the order
528 function unstripNoWiki( $text, &$state ) {
529 if ( !is_array( $state ) ) {
533 # Must expand in reverse order, otherwise nested tags will be corrupted
534 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
535 $text = str_replace( key( $state['nowiki'] ), $content, $text );
540 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
541 $text = str_replace( key( $state['html'] ), $content, $text );
549 * Add an item to the strip state
550 * Returns the unique tag which must be inserted into the stripped text
551 * The tag will be replaced with the original text in unstrip()
555 function insertStripItem( $text, &$state ) {
556 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
563 'comment' => array(),
564 'gallery' => array(),
567 $state['item'][$rnd] = $text;
572 * Interface with html tidy, used if $wgUseTidy = true.
573 * If tidy isn't able to correct the markup, the original will be
574 * returned in all its glory with a warning comment appended.
576 * Either the external tidy program or the in-process tidy extension
577 * will be used depending on availability. Override the default
578 * $wgTidyInternal setting to disable the internal if it's not working.
580 * @param string $text Hideous HTML input
581 * @return string Corrected HTML output
585 function tidy( $text ) {
586 global $wgTidyInternal;
587 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
588 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
589 '<head><title>test</title></head><body>'.$text.'</body></html>';
590 if( $wgTidyInternal ) {
591 $correctedtext = Parser
::internalTidy( $wrappedtext );
593 $correctedtext = Parser
::externalTidy( $wrappedtext );
595 if( is_null( $correctedtext ) ) {
596 wfDebug( "Tidy error detected!\n" );
597 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
599 return $correctedtext;
603 * Spawn an external HTML tidy process and get corrected markup back from it.
608 function externalTidy( $text ) {
609 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
610 $fname = 'Parser::externalTidy';
611 wfProfileIn( $fname );
616 $descriptorspec = array(
617 0 => array('pipe', 'r'),
618 1 => array('pipe', 'w'),
619 2 => array('file', '/dev/null', 'a')
622 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
623 if (is_resource($process)) {
624 fwrite($pipes[0], $text);
626 while (!feof($pipes[1])) {
627 $cleansource .= fgets($pipes[1], 1024);
630 proc_close($process);
633 wfProfileOut( $fname );
635 if( $cleansource == '' && $text != '') {
636 // Some kind of error happened, so we couldn't get the corrected text.
637 // Just give up; we'll use the source text and append a warning.
645 * Use the HTML tidy PECL extension to use the tidy library in-process,
646 * saving the overhead of spawning a new process. Currently written to
647 * the PHP 4.3.x version of the extension, may not work on PHP 5.
649 * 'pear install tidy' should be able to compile the extension module.
654 function internalTidy( $text ) {
656 $fname = 'Parser::internalTidy';
657 wfProfileIn( $fname );
659 tidy_load_config( $wgTidyConf );
660 tidy_set_encoding( 'utf8' );
661 tidy_parse_string( $text );
663 if( tidy_get_status() == 2 ) {
664 // 2 is magic number for fatal error
665 // http://www.php.net/manual/en/function.tidy-get-status.php
668 $cleansource = tidy_get_output();
670 wfProfileOut( $fname );
675 * parse the wiki syntax used to render tables
679 function doTableStuff ( $t ) {
680 $fname = 'Parser::doTableStuff';
681 wfProfileIn( $fname );
683 $t = explode ( "\n" , $t ) ;
684 $td = array () ; # Is currently a td tag open?
685 $ltd = array () ; # Was it TD or TH?
686 $tr = array () ; # Is currently a tr tag open?
687 $ltr = array () ; # tr attributes
688 $indent_level = 0; # indent level of the table
689 foreach ( $t AS $k => $x )
692 $fc = substr ( $x , 0 , 1 ) ;
693 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
694 $indent_level = strlen( $matches[1] );
696 $attributes = $this->unstripForHTML( $matches[2] );
698 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
699 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
700 array_push ( $td , false ) ;
701 array_push ( $ltd , '' ) ;
702 array_push ( $tr , false ) ;
703 array_push ( $ltr , '' ) ;
705 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
706 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
707 $z = "</table>" . substr ( $x , 2);
708 $l = array_pop ( $ltd ) ;
709 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
710 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
712 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
714 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
715 $x = substr ( $x , 1 ) ;
716 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
718 $l = array_pop ( $ltd ) ;
719 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
720 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
723 array_push ( $tr , false ) ;
724 array_push ( $td , false ) ;
725 array_push ( $ltd , '' ) ;
726 $attributes = $this->unstripForHTML( $x );
727 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
729 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
731 if ( '|+' == substr ( $x , 0 , 2 ) ) {
733 $x = substr ( $x , 1 ) ;
735 $after = substr ( $x , 1 ) ;
736 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
737 $after = explode ( '||' , $after ) ;
740 # Loop through each table cell
741 foreach ( $after AS $theline )
746 $tra = array_pop ( $ltr ) ;
747 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
748 array_push ( $tr , true ) ;
749 array_push ( $ltr , '' ) ;
752 $l = array_pop ( $ltd ) ;
753 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
754 if ( $fc == '|' ) $l = 'td' ;
755 else if ( $fc == '!' ) $l = 'th' ;
756 else if ( $fc == '+' ) $l = 'caption' ;
758 array_push ( $ltd , $l ) ;
761 $y = explode ( '|' , $theline , 2 ) ;
762 # Note that a '|' inside an invalid link should not
763 # be mistaken as delimiting cell parameters
764 if ( strpos( $y[0], '[[' ) !== false ) {
765 $y = array ($theline);
767 if ( count ( $y ) == 1 )
768 $y = "{$z}<{$l}>{$y[0]}" ;
770 $attributes = $this->unstripForHTML( $y[0] );
771 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
774 array_push ( $td , true ) ;
779 # Closing open td, tr && table
780 while ( count ( $td ) > 0 )
782 if ( array_pop ( $td ) ) $t[] = '</td>' ;
783 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
787 $t = implode ( "\n" , $t ) ;
788 wfProfileOut( $fname );
793 * Helper function for parse() that transforms wiki markup into
794 * HTML. Only called for $mOutputType == OT_HTML.
798 function internalParse( $text ) {
802 $fname = 'Parser::internalParse';
803 wfProfileIn( $fname );
805 # Remove <noinclude> tags and <includeonly> sections
806 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
807 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
808 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
810 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
811 $text = $this->replaceVariables( $text, $args );
813 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
815 $text = $this->doHeadings( $text );
816 if($this->mOptions
->getUseDynamicDates()) {
817 $df =& DateFormatter
::getInstance();
818 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
820 $text = $this->doAllQuotes( $text );
821 $text = $this->replaceInternalLinks( $text );
822 $text = $this->replaceExternalLinks( $text );
824 # replaceInternalLinks may sometimes leave behind
825 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
826 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
828 $text = $this->doMagicLinks( $text );
829 $text = $this->doTableStuff( $text );
830 $text = $this->formatHeadings( $text, $isMain );
832 $regex = '/<!--IW_TRANSCLUDE (\d+)-->/';
833 $text = preg_replace_callback($regex, array(&$this, 'scarySubstitution'), $text);
835 wfProfileOut( $fname );
839 function scarySubstitution($matches) {
840 # return "[[".$matches[0]."]]";
841 return $this->mIWTransData
[(int)$matches[0]];
845 * Replace special strings like "ISBN xxx" and "RFC xxx" with
846 * magic external links.
850 function &doMagicLinks( &$text ) {
851 $text = $this->magicISBN( $text );
852 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
853 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
858 * Parse headers and return html
862 function doHeadings( $text ) {
863 $fname = 'Parser::doHeadings';
864 wfProfileIn( $fname );
865 for ( $i = 6; $i >= 1; --$i ) {
866 $h = str_repeat( '=', $i );
867 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
868 "<h{$i}>\\1</h{$i}>\\2", $text );
870 wfProfileOut( $fname );
875 * Replace single quotes with HTML markup
877 * @return string the altered text
879 function doAllQuotes( $text ) {
880 $fname = 'Parser::doAllQuotes';
881 wfProfileIn( $fname );
883 $lines = explode( "\n", $text );
884 foreach ( $lines as $line ) {
885 $outtext .= $this->doQuotes ( $line ) . "\n";
887 $outtext = substr($outtext, 0,-1);
888 wfProfileOut( $fname );
893 * Helper function for doAllQuotes()
896 function doQuotes( $text ) {
897 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
898 if ( count( $arr ) == 1 )
902 # First, do some preliminary work. This may shift some apostrophes from
903 # being mark-up to being text. It also counts the number of occurrences
904 # of bold and italics mark-ups.
908 foreach ( $arr as $r )
910 if ( ( $i %
2 ) == 1 )
912 # If there are ever four apostrophes, assume the first is supposed to
913 # be text, and the remaining three constitute mark-up for bold text.
914 if ( strlen( $arr[$i] ) == 4 )
919 # If there are more than 5 apostrophes in a row, assume they're all
920 # text except for the last 5.
921 else if ( strlen( $arr[$i] ) > 5 )
923 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
926 # Count the number of occurrences of bold and italics mark-ups.
927 # We are not counting sequences of five apostrophes.
928 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
929 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
930 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
935 # If there is an odd number of both bold and italics, it is likely
936 # that one of the bold ones was meant to be an apostrophe followed
937 # by italics. Which one we cannot know for certain, but it is more
938 # likely to be one that has a single-letter word before it.
939 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
942 $firstsingleletterword = -1;
943 $firstmultiletterword = -1;
945 foreach ( $arr as $r )
947 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
949 $x1 = substr ($arr[$i-1], -1);
950 $x2 = substr ($arr[$i-1], -2, 1);
952 if ($firstspace == -1) $firstspace = $i;
953 } else if ($x2 == ' ') {
954 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
956 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
962 # If there is a single-letter word, use it!
963 if ($firstsingleletterword > -1)
965 $arr [ $firstsingleletterword ] = "''";
966 $arr [ $firstsingleletterword-1 ] .= "'";
968 # If not, but there's a multi-letter word, use that one.
969 else if ($firstmultiletterword > -1)
971 $arr [ $firstmultiletterword ] = "''";
972 $arr [ $firstmultiletterword-1 ] .= "'";
974 # ... otherwise use the first one that has neither.
975 # (notice that it is possible for all three to be -1 if, for example,
976 # there is only one pentuple-apostrophe in the line)
977 else if ($firstspace > -1)
979 $arr [ $firstspace ] = "''";
980 $arr [ $firstspace-1 ] .= "'";
984 # Now let's actually convert our apostrophic mush to HTML!
993 if ($state == 'both')
1000 if (strlen ($r) == 2)
1003 { $output .= '</i>'; $state = ''; }
1004 else if ($state == 'bi')
1005 { $output .= '</i>'; $state = 'b'; }
1006 else if ($state == 'ib')
1007 { $output .= '</b></i><b>'; $state = 'b'; }
1008 else if ($state == 'both')
1009 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1010 else # $state can be 'b' or ''
1011 { $output .= '<i>'; $state .= 'i'; }
1013 else if (strlen ($r) == 3)
1016 { $output .= '</b>'; $state = ''; }
1017 else if ($state == 'bi')
1018 { $output .= '</i></b><i>'; $state = 'i'; }
1019 else if ($state == 'ib')
1020 { $output .= '</b>'; $state = 'i'; }
1021 else if ($state == 'both')
1022 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1023 else # $state can be 'i' or ''
1024 { $output .= '<b>'; $state .= 'b'; }
1026 else if (strlen ($r) == 5)
1029 { $output .= '</b><i>'; $state = 'i'; }
1030 else if ($state == 'i')
1031 { $output .= '</i><b>'; $state = 'b'; }
1032 else if ($state == 'bi')
1033 { $output .= '</i></b>'; $state = ''; }
1034 else if ($state == 'ib')
1035 { $output .= '</b></i>'; $state = ''; }
1036 else if ($state == 'both')
1037 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1038 else # ($state == '')
1039 { $buffer = ''; $state = 'both'; }
1044 # Now close all remaining tags. Notice that the order is important.
1045 if ($state == 'b' ||
$state == 'ib')
1047 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1051 if ($state == 'both')
1052 $output .= '<b><i>'.$buffer.'</i></b>';
1058 * Replace external links
1060 * Note: this is all very hackish and the order of execution matters a lot.
1061 * Make sure to run maintenance/parserTests.php if you change this code.
1065 function replaceExternalLinks( $text ) {
1067 $fname = 'Parser::replaceExternalLinks';
1068 wfProfileIn( $fname );
1070 $sk =& $this->mOptions
->getSkin();
1072 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1074 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1077 while ( $i<count( $bits ) ) {
1079 $protocol = $bits[$i++
];
1080 $text = $bits[$i++
];
1081 $trail = $bits[$i++
];
1083 # The characters '<' and '>' (which were escaped by
1084 # removeHTMLtags()) should not be included in
1085 # URLs, per RFC 2396.
1086 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1087 $text = substr($url, $m2[0][1]) . ' ' . $text;
1088 $url = substr($url, 0, $m2[0][1]);
1091 # If the link text is an image URL, replace it with an <img> tag
1092 # This happened by accident in the original parser, but some people used it extensively
1093 $img = $this->maybeMakeExternalImage( $text );
1094 if ( $img !== false ) {
1100 # Set linktype for CSS - if URL==text, link is essentially free
1101 $linktype = ($text == $url) ?
'free' : 'text';
1103 # No link text, e.g. [http://domain.tld/some.link]
1104 if ( $text == '' ) {
1105 # Autonumber if allowed
1106 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1107 $text = '[' . ++
$this->mAutonumber
. ']';
1108 $linktype = 'autonumber';
1110 # Otherwise just use the URL
1111 $text = htmlspecialchars( $url );
1115 # Have link text, e.g. [http://domain.tld/some.link text]s
1117 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1120 $text = $wgContLang->markNoConversion($text);
1122 # Replace & from obsolete syntax with &.
1123 # All HTML entities will be escaped by makeExternalLink()
1124 $url = str_replace( '&', '&', $url );
1125 # Replace unnecessary URL escape codes with the referenced character
1126 # This prevents spammers from hiding links from the filters
1127 $url = Parser
::replaceUnusualEscapes( $url );
1129 # Process the trail (i.e. everything after this link up until start of the next link),
1130 # replacing any non-bracketed links
1131 $trail = $this->replaceFreeExternalLinks( $trail );
1133 # Use the encoded URL
1134 # This means that users can paste URLs directly into the text
1135 # Funny characters like ö aren't valid in URLs anyway
1136 # This was changed in August 2004
1137 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1139 # Register link in the output object
1140 $this->mOutput
->addExternalLink( $url );
1143 wfProfileOut( $fname );
1148 * Replace anything that looks like a URL with a link
1151 function replaceFreeExternalLinks( $text ) {
1153 $fname = 'Parser::replaceFreeExternalLinks';
1154 wfProfileIn( $fname );
1156 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1157 $s = array_shift( $bits );
1160 $sk =& $this->mOptions
->getSkin();
1162 while ( $i < count( $bits ) ){
1163 $protocol = $bits[$i++
];
1164 $remainder = $bits[$i++
];
1166 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1167 # Found some characters after the protocol that look promising
1168 $url = $protocol . $m[1];
1171 # The characters '<' and '>' (which were escaped by
1172 # removeHTMLtags()) should not be included in
1173 # URLs, per RFC 2396.
1174 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1175 $trail = substr($url, $m2[0][1]) . $trail;
1176 $url = substr($url, 0, $m2[0][1]);
1179 # Move trailing punctuation to $trail
1181 # If there is no left bracket, then consider right brackets fair game too
1182 if ( strpos( $url, '(' ) === false ) {
1186 $numSepChars = strspn( strrev( $url ), $sep );
1187 if ( $numSepChars ) {
1188 $trail = substr( $url, -$numSepChars ) . $trail;
1189 $url = substr( $url, 0, -$numSepChars );
1192 # Replace & from obsolete syntax with &.
1193 # All HTML entities will be escaped by makeExternalLink()
1194 # or maybeMakeExternalImage()
1195 $url = str_replace( '&', '&', $url );
1196 # Replace unnecessary URL escape codes with their equivalent characters
1197 $url = Parser
::replaceUnusualEscapes( $url );
1199 # Is this an external image?
1200 $text = $this->maybeMakeExternalImage( $url );
1201 if ( $text === false ) {
1202 # Not an image, make a link
1203 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1204 # Register it in the output object
1205 $this->mOutput
->addExternalLink( $url );
1207 $s .= $text . $trail;
1209 $s .= $protocol . $remainder;
1212 wfProfileOut( $fname );
1217 * Replace unusual URL escape codes with their equivalent characters
1222 function replaceUnusualEscapes( $url ) {
1223 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1224 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1228 * Callback function used in replaceUnusualEscapes().
1229 * Replaces unusual URL escape codes with their equivalent character
1233 function replaceUnusualEscapesCallback( $matches ) {
1234 $char = urldecode( $matches[0] );
1235 $ord = ord( $char );
1236 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1237 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1238 // No, shouldn't be escaped
1241 // Yes, leave it escaped
1247 * make an image if it's allowed, either through the global
1248 * option or through the exception
1251 function maybeMakeExternalImage( $url ) {
1252 $sk =& $this->mOptions
->getSkin();
1253 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1254 $imagesexception = !empty($imagesfrom);
1256 if ( $this->mOptions
->getAllowExternalImages()
1257 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1258 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1260 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1267 * Process [[ ]] wikilinks
1271 function replaceInternalLinks( $s ) {
1273 static $fname = 'Parser::replaceInternalLinks' ;
1275 wfProfileIn( $fname );
1277 wfProfileIn( $fname.'-setup' );
1279 # the % is needed to support urlencoded titles as well
1280 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1282 $sk =& $this->mOptions
->getSkin();
1284 #split the entire text string on occurences of [[
1285 $a = explode( '[[', ' ' . $s );
1286 #get the first element (all text up to first [[), and remove the space we added
1287 $s = array_shift( $a );
1288 $s = substr( $s, 1 );
1290 # Match a link having the form [[namespace:link|alternate]]trail
1292 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1293 # Match cases where there is no "]]", which might still be images
1294 static $e1_img = FALSE;
1295 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1296 # Match the end of a line for a word that's not followed by whitespace,
1297 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1298 $e2 = wfMsgForContent( 'linkprefix' );
1300 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1302 if( is_null( $this->mTitle
) ) {
1303 wfDebugDieBacktrace( 'nooo' );
1305 $nottalk = !$this->mTitle
->isTalkPage();
1307 if ( $useLinkPrefixExtension ) {
1308 if ( preg_match( $e2, $s, $m ) ) {
1309 $first_prefix = $m[2];
1311 $first_prefix = false;
1317 $selflink = $this->mTitle
->getPrefixedText();
1318 wfProfileOut( $fname.'-setup' );
1320 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1321 $useSubpages = $this->areSubpagesAllowed();
1323 # Loop for each link
1324 for ($k = 0; isset( $a[$k] ); $k++
) {
1326 if ( $useLinkPrefixExtension ) {
1327 wfProfileIn( $fname.'-prefixhandling' );
1328 if ( preg_match( $e2, $s, $m ) ) {
1336 $prefix = $first_prefix;
1337 $first_prefix = false;
1339 wfProfileOut( $fname.'-prefixhandling' );
1342 $might_be_img = false;
1344 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1346 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1347 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1348 # the real problem is with the $e1 regex
1351 # Still some problems for cases where the ] is meant to be outside punctuation,
1352 # and no image is in sight. See bug 2095.
1354 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1355 $text .= ']'; # so that replaceExternalLinks($text) works later
1358 # fix up urlencoded title texts
1359 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1361 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1362 $might_be_img = true;
1364 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1366 } else { # Invalid form; output directly
1367 $s .= $prefix . '[[' . $line ;
1371 # Don't allow internal links to pages containing
1372 # PROTO: where PROTO is a valid URL protocol; these
1373 # should be external links.
1374 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1375 $s .= $prefix . '[[' . $line ;
1379 # Make subpage if necessary
1380 if( $useSubpages ) {
1381 $link = $this->maybeDoSubpageLink( $m[1], $text );
1386 $noforce = (substr($m[1], 0, 1) != ':');
1388 # Strip off leading ':'
1389 $link = substr($link, 1);
1392 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1394 $s .= $prefix . '[[' . $line;
1398 #check other language variants of the link
1399 #if the article does not exist
1400 if( $checkVariantLink
1401 && $nt->getArticleID() == 0 ) {
1402 $wgContLang->findVariantLink($link, $nt);
1405 $ns = $nt->getNamespace();
1406 $iw = $nt->getInterWiki();
1408 if ($might_be_img) { # if this is actually an invalid link
1409 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1411 while (isset ($a[$k+
1]) ) {
1412 #look at the next 'line' to see if we can close it there
1413 $spliced = array_splice( $a, $k +
1, 1 );
1414 $next_line = array_shift( $spliced );
1415 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1416 # the first ]] closes the inner link, the second the image
1418 $text .= '[[' . $m[1];
1421 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1422 #if there's exactly one ]] that's fine, we'll keep looking
1423 $text .= '[[' . $m[0];
1425 #if $next_line is invalid too, we need look no further
1426 $text .= '[[' . $next_line;
1431 # we couldn't find the end of this imageLink, so output it raw
1432 #but don't ignore what might be perfectly normal links in the text we've examined
1433 $text = $this->replaceInternalLinks($text);
1434 $s .= $prefix . '[[' . $link . '|' . $text;
1435 # note: no $trail, because without an end, there *is* no trail
1438 } else { #it's not an image, so output it raw
1439 $s .= $prefix . '[[' . $link . '|' . $text;
1440 # note: no $trail, because without an end, there *is* no trail
1445 $wasblank = ( '' == $text );
1446 if( $wasblank ) $text = $link;
1449 # Link not escaped by : , create the various objects
1453 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1454 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1455 $s = rtrim($s . "\n");
1456 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1460 if ( $ns == NS_IMAGE
) {
1461 wfProfileIn( "$fname-image" );
1462 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1463 # recursively parse links inside the image caption
1464 # actually, this will parse them in any other parameters, too,
1465 # but it might be hard to fix that, and it doesn't matter ATM
1466 $text = $this->replaceExternalLinks($text);
1467 $text = $this->replaceInternalLinks($text);
1469 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1470 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1471 $this->mOutput
->addImage( $nt->getDBkey() );
1473 wfProfileOut( "$fname-image" );
1476 wfProfileOut( "$fname-image" );
1480 if ( $ns == NS_CATEGORY
) {
1481 wfProfileIn( "$fname-category" );
1482 $s = rtrim($s . "\n"); # bug 87
1485 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1486 $sortkey = $this->mTitle
->getText();
1488 $sortkey = $this->mTitle
->getPrefixedText();
1493 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1494 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1495 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1498 * Strip the whitespace Category links produce, see bug 87
1499 * @todo We might want to use trim($tmp, "\n") here.
1501 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1503 wfProfileOut( "$fname-category" );
1508 if( ( $nt->getPrefixedText() === $selflink ) &&
1509 ( $nt->getFragment() === '' ) ) {
1510 # Self-links are handled specially; generally de-link and change to bold.
1511 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1515 # Special and Media are pseudo-namespaces; no pages actually exist in them
1516 if( $ns == NS_MEDIA
) {
1517 $link = $sk->makeMediaLinkObj( $nt, $text );
1518 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1519 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1520 $this->mOutput
->addImage( $nt->getDBkey() );
1522 } elseif( $ns == NS_SPECIAL
) {
1523 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1525 } elseif( $ns == NS_IMAGE
) {
1526 $img = Image
::newFromTitle( $nt );
1527 if( $img->exists() ) {
1528 // Force a blue link if the file exists; may be a remote
1529 // upload on the shared repository, and we want to see its
1530 // auto-generated page.
1531 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1535 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1537 wfProfileOut( $fname );
1542 * Make a link placeholder. The text returned can be later resolved to a real link with
1543 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1544 * parsing of interwiki links, and secondly to allow all extistence checks and
1545 * article length checks (for stub links) to be bundled into a single query.
1548 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1549 if ( ! is_object($nt) ) {
1551 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1553 # Separate the link trail from the rest of the link
1554 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1556 if ( $nt->isExternal() ) {
1557 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1558 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1559 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1561 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1562 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1563 $this->mLinkHolders
['queries'][] = $query;
1564 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1565 $this->mLinkHolders
['titles'][] = $nt;
1567 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1574 * Render a forced-blue link inline; protect against double expansion of
1575 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1576 * Since this little disaster has to split off the trail text to avoid
1577 * breaking URLs in the following text without breaking trails on the
1578 * wiki links, it's been made into a horrible function.
1581 * @param string $text
1582 * @param string $query
1583 * @param string $trail
1584 * @param string $prefix
1585 * @return string HTML-wikitext mix oh yuck
1587 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1588 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1589 $sk =& $this->mOptions
->getSkin();
1590 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1591 return $this->armorLinks( $link ) . $trail;
1595 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1596 * going to go through further parsing steps before inline URL expansion.
1598 * In particular this is important when using action=render, which causes
1599 * full URLs to be included.
1601 * Oh man I hate our multi-layer parser!
1603 * @param string more-or-less HTML
1604 * @return string less-or-more HTML with NOPARSE bits
1606 function armorLinks( $text ) {
1607 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1608 "{$this->mUniqPrefix}NOPARSE$1", $text );
1612 * Return true if subpage links should be expanded on this page.
1615 function areSubpagesAllowed() {
1616 # Some namespaces don't allow subpages
1617 global $wgNamespacesWithSubpages;
1618 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1622 * Handle link to subpage if necessary
1623 * @param string $target the source of the link
1624 * @param string &$text the link text, modified as necessary
1625 * @return string the full name of the link
1628 function maybeDoSubpageLink($target, &$text) {
1631 # :Foobar -- override special treatment of prefix (images, language links)
1632 # /Foobar -- convert to CurrentPage/Foobar
1633 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1634 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1635 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1637 $fname = 'Parser::maybeDoSubpageLink';
1638 wfProfileIn( $fname );
1639 $ret = $target; # default return value is no change
1641 # Some namespaces don't allow subpages,
1642 # so only perform processing if subpages are allowed
1643 if( $this->areSubpagesAllowed() ) {
1644 # Look at the first character
1645 if( $target != '' && $target{0} == '/' ) {
1646 # / at end means we don't want the slash to be shown
1647 if( substr( $target, -1, 1 ) == '/' ) {
1648 $target = substr( $target, 1, -1 );
1651 $noslash = substr( $target, 1 );
1654 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1655 if( '' === $text ) {
1657 } # this might be changed for ugliness reasons
1659 # check for .. subpage backlinks
1661 $nodotdot = $target;
1662 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1664 $nodotdot = substr( $nodotdot, 3 );
1666 if($dotdotcount > 0) {
1667 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1668 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1669 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1670 # / at the end means don't show full path
1671 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1672 $nodotdot = substr( $nodotdot, 0, -1 );
1673 if( '' === $text ) {
1677 $nodotdot = trim( $nodotdot );
1678 if( $nodotdot != '' ) {
1679 $ret .= '/' . $nodotdot;
1686 wfProfileOut( $fname );
1691 * Used by doBlockLevels()
1694 /* private */ function closeParagraph() {
1696 if ( '' != $this->mLastSection
) {
1697 $result = '</' . $this->mLastSection
. ">\n";
1699 $this->mInPre
= false;
1700 $this->mLastSection
= '';
1703 # getCommon() returns the length of the longest common substring
1704 # of both arguments, starting at the beginning of both.
1706 /* private */ function getCommon( $st1, $st2 ) {
1707 $fl = strlen( $st1 );
1708 $shorter = strlen( $st2 );
1709 if ( $fl < $shorter ) { $shorter = $fl; }
1711 for ( $i = 0; $i < $shorter; ++
$i ) {
1712 if ( $st1{$i} != $st2{$i} ) { break; }
1716 # These next three functions open, continue, and close the list
1717 # element appropriate to the prefix character passed into them.
1719 /* private */ function openList( $char ) {
1720 $result = $this->closeParagraph();
1722 if ( '*' == $char ) { $result .= '<ul><li>'; }
1723 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1724 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1725 else if ( ';' == $char ) {
1726 $result .= '<dl><dt>';
1727 $this->mDTopen
= true;
1729 else { $result = '<!-- ERR 1 -->'; }
1734 /* private */ function nextItem( $char ) {
1735 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1736 else if ( ':' == $char ||
';' == $char ) {
1738 if ( $this->mDTopen
) { $close = '</dt>'; }
1739 if ( ';' == $char ) {
1740 $this->mDTopen
= true;
1741 return $close . '<dt>';
1743 $this->mDTopen
= false;
1744 return $close . '<dd>';
1747 return '<!-- ERR 2 -->';
1750 /* private */ function closeList( $char ) {
1751 if ( '*' == $char ) { $text = '</li></ul>'; }
1752 else if ( '#' == $char ) { $text = '</li></ol>'; }
1753 else if ( ':' == $char ) {
1754 if ( $this->mDTopen
) {
1755 $this->mDTopen
= false;
1756 $text = '</dt></dl>';
1758 $text = '</dd></dl>';
1761 else { return '<!-- ERR 3 -->'; }
1767 * Make lists from lines starting with ':', '*', '#', etc.
1770 * @return string the lists rendered as HTML
1772 function doBlockLevels( $text, $linestart ) {
1773 $fname = 'Parser::doBlockLevels';
1774 wfProfileIn( $fname );
1776 # Parsing through the text line by line. The main thing
1777 # happening here is handling of block-level elements p, pre,
1778 # and making lists from lines starting with * # : etc.
1780 $textLines = explode( "\n", $text );
1782 $lastPrefix = $output = '';
1783 $this->mDTopen
= $inBlockElem = false;
1785 $paragraphStack = false;
1787 if ( !$linestart ) {
1788 $output .= array_shift( $textLines );
1790 foreach ( $textLines as $oLine ) {
1791 $lastPrefixLength = strlen( $lastPrefix );
1792 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1793 $preOpenMatch = preg_match('/<pre/i', $oLine );
1794 if ( !$this->mInPre
) {
1795 # Multiple prefixes may abut each other for nested lists.
1796 $prefixLength = strspn( $oLine, '*#:;' );
1797 $pref = substr( $oLine, 0, $prefixLength );
1800 $pref2 = str_replace( ';', ':', $pref );
1801 $t = substr( $oLine, $prefixLength );
1802 $this->mInPre
= !empty($preOpenMatch);
1804 # Don't interpret any other prefixes in preformatted text
1806 $pref = $pref2 = '';
1811 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1812 # Same as the last item, so no need to deal with nesting or opening stuff
1813 $output .= $this->nextItem( substr( $pref, -1 ) );
1814 $paragraphStack = false;
1816 if ( substr( $pref, -1 ) == ';') {
1817 # The one nasty exception: definition lists work like this:
1818 # ; title : definition text
1819 # So we check for : in the remainder text to split up the
1820 # title and definition, without b0rking links.
1822 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1824 $output .= $term . $this->nextItem( ':' );
1827 } elseif( $prefixLength ||
$lastPrefixLength ) {
1828 # Either open or close a level...
1829 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1830 $paragraphStack = false;
1832 while( $commonPrefixLength < $lastPrefixLength ) {
1833 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1834 --$lastPrefixLength;
1836 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1837 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1839 while ( $prefixLength > $commonPrefixLength ) {
1840 $char = substr( $pref, $commonPrefixLength, 1 );
1841 $output .= $this->openList( $char );
1843 if ( ';' == $char ) {
1844 # FIXME: This is dupe of code above
1845 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1847 $output .= $term . $this->nextItem( ':' );
1850 ++
$commonPrefixLength;
1852 $lastPrefix = $pref2;
1854 if( 0 == $prefixLength ) {
1855 wfProfileIn( "$fname-paragraph" );
1856 # No prefix (not in list)--go to paragraph mode
1857 // XXX: use a stack for nestable elements like span, table and div
1858 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1859 $closematch = preg_match(
1860 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1861 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1862 if ( $openmatch or $closematch ) {
1863 $paragraphStack = false;
1864 $output .= $this->closeParagraph();
1865 if ( $preOpenMatch and !$preCloseMatch ) {
1866 $this->mInPre
= true;
1868 if ( $closematch ) {
1869 $inBlockElem = false;
1871 $inBlockElem = true;
1873 } else if ( !$inBlockElem && !$this->mInPre
) {
1874 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1876 if ($this->mLastSection
!= 'pre') {
1877 $paragraphStack = false;
1878 $output .= $this->closeParagraph().'<pre>';
1879 $this->mLastSection
= 'pre';
1881 $t = substr( $t, 1 );
1884 if ( '' == trim($t) ) {
1885 if ( $paragraphStack ) {
1886 $output .= $paragraphStack.'<br />';
1887 $paragraphStack = false;
1888 $this->mLastSection
= 'p';
1890 if ($this->mLastSection
!= 'p' ) {
1891 $output .= $this->closeParagraph();
1892 $this->mLastSection
= '';
1893 $paragraphStack = '<p>';
1895 $paragraphStack = '</p><p>';
1899 if ( $paragraphStack ) {
1900 $output .= $paragraphStack;
1901 $paragraphStack = false;
1902 $this->mLastSection
= 'p';
1903 } else if ($this->mLastSection
!= 'p') {
1904 $output .= $this->closeParagraph().'<p>';
1905 $this->mLastSection
= 'p';
1910 wfProfileOut( "$fname-paragraph" );
1912 // somewhere above we forget to get out of pre block (bug 785)
1913 if($preCloseMatch && $this->mInPre
) {
1914 $this->mInPre
= false;
1916 if ($paragraphStack === false) {
1920 while ( $prefixLength ) {
1921 $output .= $this->closeList( $pref2{$prefixLength-1} );
1924 if ( '' != $this->mLastSection
) {
1925 $output .= '</' . $this->mLastSection
. '>';
1926 $this->mLastSection
= '';
1929 wfProfileOut( $fname );
1934 * Split up a string on ':', ignoring any occurences inside
1935 * <a>..</a> or <span>...</span>
1936 * @param string $str the string to split
1937 * @param string &$before set to everything before the ':'
1938 * @param string &$after set to everything after the ':'
1939 * return string the position of the ':', or false if none found
1941 function findColonNoLinks($str, &$before, &$after) {
1942 # I wonder if we should make this count all tags, not just <a>
1943 # and <span>. That would prevent us from matching a ':' that
1944 # comes in the middle of italics other such formatting....
1946 $fname = 'Parser::findColonNoLinks';
1947 wfProfileIn( $fname );
1950 $colon = strpos($str, ':', $pos);
1952 if ($colon !== false) {
1953 $before = substr($str, 0, $colon);
1954 $after = substr($str, $colon +
1);
1956 # Skip any ':' within <a> or <span> pairs
1957 $a = substr_count($before, '<a');
1958 $s = substr_count($before, '<span');
1959 $ca = substr_count($before, '</a>');
1960 $cs = substr_count($before, '</span>');
1962 if ($a <= $ca and $s <= $cs) {
1963 # Tags are balanced before ':'; ok
1968 } while ($colon !== false);
1969 wfProfileOut( $fname );
1974 * Return value of a magic variable (like PAGENAME)
1978 function getVariableValue( $index ) {
1979 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1982 * Some of these require message or data lookups and can be
1983 * expensive to check many times.
1985 static $varCache = array();
1986 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1987 if ( isset( $varCache[$index] ) )
1988 return $varCache[$index];
1991 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1994 case MAG_CURRENTMONTH
:
1995 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1996 case MAG_CURRENTMONTHNAME
:
1997 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
1998 case MAG_CURRENTMONTHNAMEGEN
:
1999 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2000 case MAG_CURRENTMONTHABBREV
:
2001 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2002 case MAG_CURRENTDAY
:
2003 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2004 case MAG_CURRENTDAY2
:
2005 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2007 return $this->mTitle
->getText();
2009 return $this->mTitle
->getPartialURL();
2010 case MAG_FULLPAGENAME
:
2011 return $this->mTitle
->getPrefixedText();
2012 case MAG_FULLPAGENAMEE
:
2013 return $this->mTitle
->getPrefixedURL();
2014 case MAG_REVISIONID
:
2015 return $this->mRevisionId
;
2017 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2018 case MAG_NAMESPACEE
:
2019 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2020 case MAG_CURRENTDAYNAME
:
2021 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2022 case MAG_CURRENTYEAR
:
2023 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2024 case MAG_CURRENTTIME
:
2025 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2026 case MAG_CURRENTWEEK
:
2027 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2028 // int to remove the padding
2029 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2030 case MAG_CURRENTDOW
:
2031 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2032 case MAG_NUMBEROFARTICLES
:
2033 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2034 case MAG_NUMBEROFFILES
:
2035 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2040 case MAG_SERVERNAME
:
2041 return $wgServerName;
2042 case MAG_SCRIPTPATH
:
2043 return $wgScriptPath;
2046 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2054 * initialise the magic variables (like CURRENTMONTHNAME)
2058 function initialiseVariables() {
2059 $fname = 'Parser::initialiseVariables';
2060 wfProfileIn( $fname );
2061 global $wgVariableIDs;
2062 $this->mVariables
= array();
2063 foreach ( $wgVariableIDs as $id ) {
2064 $mw =& MagicWord
::get( $id );
2065 $mw->addToArray( $this->mVariables
, $id );
2067 wfProfileOut( $fname );
2071 * parse any parentheses in format ((title|part|part))
2072 * and call callbacks to get a replacement text for any found piece
2074 * @param string $text The text to parse
2075 * @param array $callbacks rules in form:
2076 * '{' => array( # opening parentheses
2077 * 'end' => '}', # closing parentheses
2078 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2079 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2084 function replace_callback ($text, $callbacks) {
2085 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2086 $lastOpeningBrace = -1; # last not closed parentheses
2088 for ($i = 0; $i < strlen($text); $i++
) {
2089 # check for any opening brace
2092 foreach ($callbacks as $key => $value) {
2093 $pos = strpos ($text, $key, $i);
2094 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2100 if ($lastOpeningBrace >= 0) {
2101 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2103 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2108 $pos = strpos ($text, '|', $i);
2110 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2121 # found openning brace, lets add it to parentheses stack
2122 if (null != $rule) {
2123 $piece = array('brace' => $text[$i],
2124 'braceEnd' => $rule['end'],
2129 # count openning brace characters
2130 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2135 $piece['startAt'] = $i+
1;
2136 $piece['partStart'] = $i+
1;
2138 # we need to add to stack only if openning brace count is enough for any given rule
2139 foreach ($rule['cb'] as $cnt => $fn) {
2140 if ($piece['count'] >= $cnt) {
2141 $lastOpeningBrace ++
;
2142 $openingBraceStack[$lastOpeningBrace] = $piece;
2149 else if ($lastOpeningBrace >= 0) {
2150 # first check if it is a closing brace
2151 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2152 # lets check if it is enough characters for closing brace
2154 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2157 # if there are more closing parentheses than opening ones, we parse less
2158 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2159 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2161 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2163 $matchingCallback = null;
2164 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2165 if ($count >= $cnt && $matchingCount < $cnt) {
2166 $matchingCount = $cnt;
2167 $matchingCallback = $fn;
2171 if ($matchingCount == 0) {
2176 # lets set a title or last part (if '|' was found)
2177 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2178 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2180 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2182 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2183 $pieceEnd = $i +
$matchingCount;
2185 if( is_callable( $matchingCallback ) ) {
2187 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2188 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2189 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2190 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2192 # finally we can call a user callback and replace piece of text
2193 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2194 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2195 $i = $pieceStart +
strlen($replaceWith) - 1;
2198 # null value for callback means that parentheses should be parsed, but not replaced
2199 $i +
= $matchingCount - 1;
2202 # reset last openning parentheses, but keep it in case there are unused characters
2203 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2204 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2205 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2208 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2209 $openingBraceStack[$lastOpeningBrace--] = null;
2211 if ($matchingCount < $piece['count']) {
2212 $piece['count'] -= $matchingCount;
2213 $piece['startAt'] -= $matchingCount;
2214 $piece['partStart'] = $piece['startAt'];
2215 # do we still qualify for any callback with remaining count?
2216 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2217 if ($piece['count'] >= $cnt) {
2218 $lastOpeningBrace ++
;
2219 $openingBraceStack[$lastOpeningBrace] = $piece;
2227 # lets set a title if it is a first separator, or next part otherwise
2228 if ($text[$i] == '|') {
2229 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2230 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2231 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2234 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2236 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2245 * Replace magic variables, templates, and template arguments
2246 * with the appropriate text. Templates are substituted recursively,
2247 * taking care to avoid infinite loops.
2249 * Note that the substitution depends on value of $mOutputType:
2250 * OT_WIKI: only {{subst:}} templates
2251 * OT_MSG: only magic variables
2252 * OT_HTML: all templates and magic variables
2254 * @param string $tex The text to transform
2255 * @param array $args Key-value pairs representing template parameters to substitute
2258 function replaceVariables( $text, $args = array() ) {
2259 # Prevent too big inclusions
2260 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2264 $fname = 'Parser::replaceVariables';
2265 wfProfileIn( $fname );
2267 # This function is called recursively. To keep track of arguments we need a stack:
2268 array_push( $this->mArgStack
, $args );
2270 $braceCallbacks = array();
2271 $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 );
2367 # $part1 is the bit before the first |, and must contain only title characters
2368 # $args is a list of arguments, starting from index 0, not including $part1
2370 $part1 = $piece['title'];
2371 # If the third subpattern matched anything, it will start with |
2373 if (null == $piece['parts']) {
2374 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2375 if ($replaceWith != $piece['text']) {
2376 $text = $replaceWith;
2382 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2383 $argc = count( $args );
2387 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2388 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2389 # One of two possibilities is true:
2390 # 1) Found SUBST but not in the PST phase
2391 # 2) Didn't find SUBST and in the PST phase
2392 # In either case, return without further processing
2393 $text = $piece['text'];
2399 # MSG, MSGNW and INT
2402 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2403 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2406 # Remove obsolete MSG:
2407 $mwMsg =& MagicWord
::get( MAG_MSG
);
2408 $mwMsg->matchStartAndRemove( $part1 );
2411 # Check if it is an internal message
2412 $mwInt =& MagicWord
::get( MAG_INT
);
2413 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2414 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2415 $text = $linestart . wfMsgReal( $part1, $args, true );
2423 # Check for NS: (namespace expansion)
2424 $mwNs = MagicWord
::get( MAG_NS
);
2425 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2426 if ( intval( $part1 ) ) {
2427 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2430 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2431 if ( !is_null( $index ) ) {
2432 $text = $linestart . $wgContLang->getNsText( $index );
2439 # LCFIRST, UCFIRST, LC and UC
2441 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2442 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2443 $lc =& MagicWord
::get( MAG_LC
);
2444 $uc =& MagicWord
::get( MAG_UC
);
2445 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2446 $text = $linestart . $wgContLang->lcfirst( $part1 );
2448 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2449 $text = $linestart . $wgContLang->ucfirst( $part1 );
2451 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2452 $text = $linestart . $wgContLang->lc( $part1 );
2454 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2455 $text = $linestart . $wgContLang->uc( $part1 );
2460 # LOCALURL and FULLURL
2462 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2463 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2464 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2465 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2468 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2469 $func = 'getLocalURL';
2470 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2471 $func = 'escapeLocalURL';
2472 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2473 $func = 'getFullURL';
2474 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2475 $func = 'escapeFullURL';
2480 if ( $func !== false ) {
2481 $title = Title
::newFromText( $part1 );
2482 if ( !is_null( $title ) ) {
2484 $text = $linestart . $title->$func( $args[0] );
2486 $text = $linestart . $title->$func();
2494 if ( !$found && $argc == 1 ) {
2495 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2496 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2497 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2503 if ( !$found && $argc >= 2 ) {
2504 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2505 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2506 if ($argc==2) {$args[2]=$args[1];}
2507 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2512 # Template table test
2514 # Did we encounter this template already? If yes, it is in the cache
2515 # and we need to check for loops.
2516 if ( !$found && isset( $this->mTemplates
[$part1] ) ) {
2519 # Infinite loop test
2520 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2523 $text = $linestart .
2524 '{{' . $part1 . '}}' .
2525 '<!-- WARNING: template loop detected -->';
2526 wfDebug( "$fname: template loop broken at '$part1'\n" );
2528 # set $text to cached message.
2529 $text = $linestart . $this->mTemplates
[$part1];
2533 # Load from database
2534 $replaceHeadings = false;
2536 $lastPathLevel = $this->mTemplatePath
;
2539 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2540 if ($subpage !== '') {
2541 $ns = $this->mTitle
->getNamespace();
2543 $title = Title
::newFromText( $part1, $ns );
2546 $interwiki = Title
::getInterwikiLink($title->getInterwiki());
2547 if ($interwiki != '' && $title->isTrans()) {
2548 return $this->scarytransclude($title, $interwiki);
2552 if ( !is_null( $title ) && !$title->isExternal() ) {
2553 # Check for excessive inclusion
2554 $dbk = $title->getPrefixedDBkey();
2555 if ( $this->incrementIncludeCount( $dbk ) ) {
2556 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2557 # Capture special page output
2558 $text = SpecialPage
::capturePath( $title );
2559 if ( is_string( $text ) ) {
2563 $this->disableCache();
2566 $articleContent = $this->fetchTemplate( $title );
2567 if ( $articleContent !== false ) {
2569 $text = $articleContent;
2570 $replaceHeadings = true;
2575 # If the title is valid but undisplayable, make a link to it
2576 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2577 $text = '[['.$title->getPrefixedText().']]';
2581 # Template cache array insertion
2583 $this->mTemplates
[$part1] = $text;
2584 $text = $linestart . $text;
2589 # Recursive parsing, escaping and link table handling
2590 # Only for HTML output
2591 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2592 $text = wfEscapeWikiText( $text );
2593 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found && !$noparse) {
2594 # Clean up argument array
2595 $assocArgs = array();
2597 foreach( $args as $arg ) {
2598 $eqpos = strpos( $arg, '=' );
2599 if ( $eqpos === false ) {
2600 $assocArgs[$index++
] = $arg;
2602 $name = trim( substr( $arg, 0, $eqpos ) );
2603 $value = trim( substr( $arg, $eqpos+
1 ) );
2604 if ( $value === false ) {
2607 if ( $name !== false ) {
2608 $assocArgs[$name] = $value;
2613 # Add a new element to the templace recursion path
2614 $this->mTemplatePath
[$part1] = 1;
2616 # If there are any <onlyinclude> tags, only include them
2617 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2618 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2620 foreach ($m[1] as $piece)
2623 # Remove <noinclude> sections and <includeonly> tags
2624 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2625 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2627 if( $this->mOutputType
== OT_HTML
) {
2628 # Strip <nowiki>, <pre>, etc.
2629 $text = $this->strip( $text, $this->mStripState
);
2630 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2632 $text = $this->replaceVariables( $text, $assocArgs );
2634 # If the template begins with a table or block-level
2635 # element, it should be treated as beginning a new line.
2636 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2637 $text = "\n" . $text;
2640 # Prune lower levels off the recursion check path
2641 $this->mTemplatePath
= $lastPathLevel;
2644 wfProfileOut( $fname );
2645 return $piece['text'];
2648 # Replace raw HTML by a placeholder
2649 # Add a blank line preceding, to prevent it from mucking up
2650 # immediately preceding headings
2651 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2653 # replace ==section headers==
2654 # XXX this needs to go away once we have a better parser.
2655 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2656 if( !is_null( $title ) )
2657 $encodedname = base64_encode($title->getPrefixedDBkey());
2659 $encodedname = base64_encode("");
2660 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2661 PREG_SPLIT_DELIM_CAPTURE
);
2664 for( $i = 0; $i < count($m); $i +
= 2 ) {
2666 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2668 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2672 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2673 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2674 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2682 # Prune lower levels off the recursion check path
2683 $this->mTemplatePath
= $lastPathLevel;
2686 wfProfileOut( $fname );
2687 return $piece['text'];
2689 wfProfileOut( $fname );
2695 * Fetch the unparsed text of a template and register a reference to it.
2697 function fetchTemplate( $title ) {
2699 // Loop to fetch the article, with up to 1 redirect
2700 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2701 $rev = Revision
::newFromTitle( $title );
2702 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2706 $text = $rev->getText();
2707 if ( $text === false ) {
2711 $title = Title
::newFromRedirect( $text );
2717 * Translude an interwiki link.
2719 function scarytransclude($title, $interwiki) {
2720 global $wgEnableScaryTranscluding;
2722 if (!$wgEnableScaryTranscluding)
2723 return wfMsg('scarytranscludedisabled');
2725 $articlename = "Template:" . $title->getDBkey();
2726 $url = str_replace('$1', urlencode($articlename), $interwiki);
2727 if (strlen($url) > 255)
2728 return wfMsg('scarytranscludetoolong');
2729 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2730 $this->mIWTransData
[] = $text;
2731 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData
) - 1)."-->";
2734 function fetchScaryTemplateMaybeFromCache($url) {
2735 $dbr =& wfGetDB(DB_SLAVE
);
2736 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2737 array('tc_url' => $url));
2739 $time = $obj->tc_time
;
2740 $text = $obj->tc_contents
;
2741 if ($time && $time < (time() +
(60*60))) {
2746 $text = wfGetHTTP($url . '?action=render');
2748 return wfMsg('scarytranscludefailed', $url);
2750 $dbw =& wfGetDB(DB_MASTER
);
2751 $dbw->replace('transcache', array(), array(
2753 'tc_time' => time(),
2754 'tc_contents' => $text));
2760 * Triple brace replacement -- used for template arguments
2763 function argSubstitution( $matches ) {
2764 $arg = trim( $matches['title'] );
2765 $text = $matches['text'];
2766 $inputArgs = end( $this->mArgStack
);
2768 if ( array_key_exists( $arg, $inputArgs ) ) {
2769 $text = $inputArgs[$arg];
2770 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2771 $text = $matches['parts'][0];
2778 * Returns true if the function is allowed to include this entity
2781 function incrementIncludeCount( $dbk ) {
2782 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2783 $this->mIncludeCount
[$dbk] = 0;
2785 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2793 * This function accomplishes several tasks:
2794 * 1) Auto-number headings if that option is enabled
2795 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2796 * 3) Add a Table of contents on the top for users who have enabled the option
2797 * 4) Auto-anchor headings
2799 * It loops through all headlines, collects the necessary data, then splits up the
2800 * string and re-inserts the newly formatted headlines.
2802 * @param string $text
2803 * @param boolean $isMain
2806 function formatHeadings( $text, $isMain=true ) {
2807 global $wgMaxTocLevel, $wgContLang;
2809 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2811 $forceTocHere = false;
2812 if( !$this->mTitle
->userCanEdit() ) {
2815 $showEditLink = $this->mOptions
->getEditSection();
2818 # Inhibit editsection links if requested in the page
2819 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2820 if( $esw->matchAndRemove( $text ) ) {
2823 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2825 $mw =& MagicWord
::get( MAG_NOTOC
);
2826 if( $mw->matchAndRemove( $text ) ) {
2830 # Get all headlines for numbering them and adding funky stuff like [edit]
2831 # links - this is for later, but we need the number of headlines right now
2832 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2834 # if there are fewer than 4 headlines in the article, do not show TOC
2835 if( $numMatches < 4 ) {
2839 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2840 # override above conditions and always show TOC at that place
2842 $mw =& MagicWord
::get( MAG_TOC
);
2843 if($mw->match( $text ) ) {
2845 $forceTocHere = true;
2847 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2848 # override above conditions and always show TOC above first header
2849 $mw =& MagicWord
::get( MAG_FORCETOC
);
2850 if ($mw->matchAndRemove( $text ) ) {
2855 # Never ever show TOC if no headers
2856 if( $numMatches < 1 ) {
2860 # We need this to perform operations on the HTML
2861 $sk =& $this->mOptions
->getSkin();
2865 $sectionCount = 0; # headlineCount excluding template sections
2867 # Ugh .. the TOC should have neat indentation levels which can be
2868 # passed to the skin functions. These are determined here
2872 $sublevelCount = array();
2873 $levelCount = array();
2880 foreach( $matches[3] as $headline ) {
2882 $templatetitle = '';
2883 $templatesection = 0;
2886 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2888 $templatetitle = base64_decode($mat[1]);
2889 $templatesection = 1 +
(int)base64_decode($mat[2]);
2890 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2894 $prevlevel = $level;
2895 $prevtoclevel = $toclevel;
2897 $level = $matches[1][$headlineCount];
2899 if( $doNumberHeadings ||
$doShowToc ) {
2901 if ( $level > $prevlevel ) {
2902 # Increase TOC level
2904 $sublevelCount[$toclevel] = 0;
2905 $toc .= $sk->tocIndent();
2907 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2908 # Decrease TOC level, find level to jump to
2910 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2911 # Can only go down to level 1
2914 for ($i = $toclevel; $i > 0; $i--) {
2915 if ( $levelCount[$i] == $level ) {
2916 # Found last matching level
2920 elseif ( $levelCount[$i] < $level ) {
2921 # Found first matching level below current level
2928 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2931 # No change in level, end TOC line
2932 $toc .= $sk->tocLineEnd();
2935 $levelCount[$toclevel] = $level;
2937 # count number of headlines for each level
2938 @$sublevelCount[$toclevel]++
;
2940 for( $i = 1; $i <= $toclevel; $i++
) {
2941 if( !empty( $sublevelCount[$i] ) ) {
2945 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2951 # The canonized header is a version of the header text safe to use for links
2952 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2953 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
2954 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
2956 # Remove link placeholders by the link text.
2957 # <!--LINK number-->
2959 # link text with suffix
2960 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2961 "\$this->mLinkHolders['texts'][\$1]",
2962 $canonized_headline );
2963 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2964 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2965 $canonized_headline );
2968 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2969 $tocline = trim( $canonized_headline );
2970 $canonized_headline = Sanitizer
::escapeId( $tocline );
2971 $refers[$headlineCount] = $canonized_headline;
2973 # count how many in assoc. array so we can track dupes in anchors
2974 @$refers[$canonized_headline]++
;
2975 $refcount[$headlineCount]=$refers[$canonized_headline];
2977 # Don't number the heading if it is the only one (looks silly)
2978 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2979 # the two are different if the line contains a link
2980 $headline=$numbering . ' ' . $headline;
2983 # Create the anchor for linking from the TOC to the section
2984 $anchor = $canonized_headline;
2985 if($refcount[$headlineCount] > 1 ) {
2986 $anchor .= '_' . $refcount[$headlineCount];
2988 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
2989 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2991 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
2992 if ( empty( $head[$headlineCount] ) ) {
2993 $head[$headlineCount] = '';
2996 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2998 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1);
3001 # give headline the correct <h#> tag
3002 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3010 $toc .= $sk->tocUnindent( $toclevel - 1 );
3011 $toc = $sk->tocList( $toc );
3014 # split up and insert constructed headlines
3016 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3019 foreach( $blocks as $block ) {
3020 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3021 # This is the [edit] link that appears for the top block of text when
3022 # section editing is enabled
3024 # Disabled because it broke block formatting
3025 # For example, a bullet point in the top line
3026 # $full .= $sk->editSectionLink(0);
3029 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3030 # Top anchor now in skin
3034 if( !empty( $head[$i] ) ) {
3040 $mw =& MagicWord
::get( MAG_TOC
);
3041 return $mw->replace( $toc, $full );
3048 * Return an HTML link for the "ISBN 123456" text
3051 function magicISBN( $text ) {
3052 $fname = 'Parser::magicISBN';
3053 wfProfileIn( $fname );
3055 $a = split( 'ISBN ', ' '.$text );
3056 if ( count ( $a ) < 2 ) {
3057 wfProfileOut( $fname );
3060 $text = substr( array_shift( $a ), 1);
3061 $valid = '0123456789-Xx';
3063 foreach ( $a as $x ) {
3064 $isbn = $blank = '' ;
3065 while ( ' ' == $x{0} ) {
3067 $x = substr( $x, 1 );
3069 if ( $x == '' ) { # blank isbn
3070 $text .= "ISBN $blank";
3073 while ( strstr( $valid, $x{0} ) != false ) {
3075 $x = substr( $x, 1 );
3077 $num = str_replace( '-', '', $isbn );
3078 $num = str_replace( ' ', '', $num );
3079 $num = str_replace( 'x', 'X', $num );
3082 $text .= "ISBN $blank$x";
3084 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3085 $text .= '<a href="' .
3086 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3087 "\" class=\"internal\">ISBN $isbn</a>";
3091 wfProfileOut( $fname );
3096 * Return an HTML link for the "RFC 1234" text
3099 * @param string $text Text to be processed
3100 * @param string $keyword Magic keyword to use (default RFC)
3101 * @param string $urlmsg Interface message to use (default rfcurl)
3104 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3106 $valid = '0123456789';
3109 $a = split( $keyword, ' '.$text );
3110 if ( count ( $a ) < 2 ) {
3113 $text = substr( array_shift( $a ), 1);
3115 /* Check if keyword is preceed by [[.
3116 * This test is made here cause of the array_shift above
3117 * that prevent the test to be done in the foreach.
3119 if ( substr( $text, -2 ) == '[[' ) {
3123 foreach ( $a as $x ) {
3124 /* token might be empty if we have RFC RFC 1234 */
3132 /** remove and save whitespaces in $blank */
3133 while ( $x{0} == ' ' ) {
3135 $x = substr( $x, 1 );
3138 /** remove and save the rfc number in $id */
3139 while ( strstr( $valid, $x{0} ) != false ) {
3141 $x = substr( $x, 1 );
3145 /* call back stripped spaces*/
3146 $text .= $keyword.$blank.$x;
3147 } elseif( $internal ) {
3149 $text .= $keyword.$id.$x;
3151 /* build the external link*/
3152 $url = wfMsg( $urlmsg, $id);
3153 $sk =& $this->mOptions
->getSkin();
3154 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3155 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3158 /* Check if the next RFC keyword is preceed by [[ */
3159 $internal = ( substr($x,-2) == '[[' );
3165 * Transform wiki markup when saving a page by doing \r\n -> \n
3166 * conversion, substitting signatures, {{subst:}} templates, etc.
3168 * @param string $text the text to transform
3169 * @param Title &$title the Title object for the current article
3170 * @param User &$user the User object describing the current user
3171 * @param ParserOptions $options parsing options
3172 * @param bool $clearState whether to clear the parser state first
3173 * @return string the altered wiki markup
3176 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3177 $this->mOptions
= $options;
3178 $this->mTitle
=& $title;
3179 $this->mOutputType
= OT_WIKI
;
3181 if ( $clearState ) {
3182 $this->clearState();
3185 $stripState = false;
3189 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3190 $text = $this->strip( $text, $stripState, true );
3191 $text = $this->pstPass2( $text, $user );
3192 $text = $this->unstrip( $text, $stripState );
3193 $text = $this->unstripNoWiki( $text, $stripState );
3198 * Pre-save transform helper function
3201 function pstPass2( $text, &$user ) {
3202 global $wgContLang, $wgLocaltimezone;
3204 /* Note: This is the timestamp saved as hardcoded wikitext to
3205 * the database, we use $wgContLang here in order to give
3206 * everyone the same signiture and use the default one rather
3207 * than the one selected in each users preferences.
3209 if ( isset( $wgLocaltimezone ) ) {
3210 $oldtz = getenv( 'TZ' );
3211 putenv( 'TZ='.$wgLocaltimezone );
3213 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3214 ' (' . date( 'T' ) . ')';
3215 if ( isset( $wgLocaltimezone ) ) {
3216 putenv( 'TZ='.$oldtz );
3219 # Variable replacement
3220 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3221 $text = $this->replaceVariables( $text );
3224 $sigText = $this->getUserSig( $user );
3225 $text = strtr( $text, array(
3227 '~~~~' => "$sigText $d",
3231 # Context links: [[|name]] and [[name (context)|]]
3233 global $wgLegalTitleChars;
3234 $tc = "[$wgLegalTitleChars]";
3235 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3237 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3238 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3240 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3241 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3242 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3243 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3245 $t = $this->mTitle
->getText();
3246 if ( preg_match( $conpat, $t, $m ) ) {
3249 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3250 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3251 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3253 if ( '' == $context ) {
3254 $text = preg_replace( $p2, '[[\\1]]', $text );
3256 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3259 # Trim trailing whitespace
3260 # MAG_END (__END__) tag allows for trailing
3261 # whitespace to be deliberately included
3262 $text = rtrim( $text );
3263 $mw =& MagicWord
::get( MAG_END
);
3264 $mw->matchAndRemove( $text );
3270 * Fetch the user's signature text, if any, and normalize to
3271 * validated, ready-to-insert wikitext.
3277 function getUserSig( &$user ) {
3280 $username = $user->getName();
3281 $nickname = $user->getOption( 'nickname' );
3282 $nickname = $nickname === '' ?
$username : $nickname;
3284 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3285 # Sig. might contain markup; validate this
3286 if( $this->validateSig( $nickname ) !== false ) {
3287 # Validated; clean up (if needed) and return it
3288 return( $this->cleanSig( $nickname ) );
3290 # Failed to validate; fall back to the default
3291 $nickname = $username;
3292 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3296 # If we're still here, make it a link to the user page
3297 $userpage = $user->getUserPage();
3298 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3302 * Check that the user's signature contains no bad XML
3304 * @param string $text
3305 * @return mixed An expanded string, or false if invalid.
3307 function validateSig( $text ) {
3308 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3312 * Clean up signature text
3314 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3315 * 2) Substitute all transclusions
3317 * @param string $text
3318 * @return string Signature text
3320 function cleanSig( $text ) {
3321 $substWord = MagicWord
::get( MAG_SUBST
);
3322 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3323 $substText = '{{' . $substWord->getSynonym( 0 );
3325 $text = preg_replace( $substRegex, $substText, $text );
3326 $text = preg_replace( '/~{3,5}/', '', $text );
3327 $text = $this->replaceVariables( $text );
3333 * Set up some variables which are usually set up in parse()
3334 * so that an external function can call some class members with confidence
3337 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3338 $this->mTitle
=& $title;
3339 $this->mOptions
= $options;
3340 $this->mOutputType
= $outputType;
3341 if ( $clearState ) {
3342 $this->clearState();
3347 * Transform a MediaWiki message by replacing magic variables.
3349 * @param string $text the text to transform
3350 * @param ParserOptions $options options
3351 * @return string the text with variables substituted
3354 function transformMsg( $text, $options ) {
3356 static $executing = false;
3358 $fname = "Parser::transformMsg";
3360 # Guard against infinite recursion
3366 wfProfileIn($fname);
3368 $this->mTitle
= $wgTitle;
3369 $this->mOptions
= $options;
3370 $this->mOutputType
= OT_MSG
;
3371 $this->clearState();
3372 $text = $this->replaceVariables( $text );
3375 wfProfileOut($fname);
3380 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3381 * Callback will be called with the text within
3382 * Transform and return the text within
3386 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3387 * @param mixed $callback The callback function (and object) to use for the tag
3389 * @return The old value of the mTagHooks array associated with the hook
3391 function setHook( $tag, $callback ) {
3392 $oldVal = @$this->mTagHooks
[$tag];
3393 $this->mTagHooks
[$tag] = $callback;
3399 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3400 * Placeholders created in Skin::makeLinkObj()
3401 * Returns an array of links found, indexed by PDBK:
3405 * $options is a bit field, RLH_FOR_UPDATE to select for update
3407 function replaceLinkHolders( &$text, $options = 0 ) {
3409 global $wgOutputReplace;
3411 $fname = 'Parser::replaceLinkHolders';
3412 wfProfileIn( $fname );
3416 $sk =& $this->mOptions
->getSkin();
3417 $linkCache =& LinkCache
::singleton();
3419 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3420 wfProfileIn( $fname.'-check' );
3421 $dbr =& wfGetDB( DB_SLAVE
);
3422 $page = $dbr->tableName( 'page' );
3423 $threshold = $wgUser->getOption('stubthreshold');
3426 asort( $this->mLinkHolders
['namespaces'] );
3430 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3432 $title = $this->mLinkHolders
['titles'][$key];
3434 # Skip invalid entries.
3435 # Result will be ugly, but prevents crash.
3436 if ( is_null( $title ) ) {
3439 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3441 # Check if it's a static known link, e.g. interwiki
3442 if ( $title->isAlwaysKnown() ) {
3443 $colours[$pdbk] = 1;
3444 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3445 $colours[$pdbk] = 1;
3446 $this->mOutput
->addLink( $title, $id );
3447 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3448 $colours[$pdbk] = 0;
3450 # Not in the link cache, add it to the query
3451 if ( !isset( $current ) ) {
3453 $query = "SELECT page_id, page_namespace, page_title";
3454 if ( $threshold > 0 ) {
3455 $query .= ', page_len, page_is_redirect';
3457 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3458 } elseif ( $current != $ns ) {
3460 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3465 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3470 if ( $options & RLH_FOR_UPDATE
) {
3471 $query .= ' FOR UPDATE';
3474 $res = $dbr->query( $query, $fname );
3476 # Fetch data and form into an associative array
3477 # non-existent = broken
3480 while ( $s = $dbr->fetchObject($res) ) {
3481 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3482 $pdbk = $title->getPrefixedDBkey();
3483 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3484 $this->mOutput
->addLink( $title, $s->page_id
);
3486 if ( $threshold > 0 ) {
3487 $size = $s->page_len
;
3488 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3489 $colours[$pdbk] = 1;
3491 $colours[$pdbk] = 2;
3494 $colours[$pdbk] = 1;
3498 wfProfileOut( $fname.'-check' );
3500 # Construct search and replace arrays
3501 wfProfileIn( $fname.'-construct' );
3502 $wgOutputReplace = array();
3503 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3504 $pdbk = $pdbks[$key];
3505 $searchkey = "<!--LINK $key-->";
3506 $title = $this->mLinkHolders
['titles'][$key];
3507 if ( empty( $colours[$pdbk] ) ) {
3508 $linkCache->addBadLinkObj( $title );
3509 $colours[$pdbk] = 0;
3510 $this->mOutput
->addLink( $title, 0 );
3511 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3512 $this->mLinkHolders
['texts'][$key],
3513 $this->mLinkHolders
['queries'][$key] );
3514 } elseif ( $colours[$pdbk] == 1 ) {
3515 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3516 $this->mLinkHolders
['texts'][$key],
3517 $this->mLinkHolders
['queries'][$key] );
3518 } elseif ( $colours[$pdbk] == 2 ) {
3519 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3520 $this->mLinkHolders
['texts'][$key],
3521 $this->mLinkHolders
['queries'][$key] );
3524 wfProfileOut( $fname.'-construct' );
3527 wfProfileIn( $fname.'-replace' );
3529 $text = preg_replace_callback(
3530 '/(<!--LINK .*?-->)/',
3531 "wfOutputReplaceMatches",
3534 wfProfileOut( $fname.'-replace' );
3537 # Now process interwiki link holders
3538 # This is quite a bit simpler than internal links
3539 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3540 wfProfileIn( $fname.'-interwiki' );
3541 # Make interwiki link HTML
3542 $wgOutputReplace = array();
3543 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3544 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3545 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3548 $text = preg_replace_callback(
3549 '/<!--IWLINK (.*?)-->/',
3550 "wfOutputReplaceMatches",
3552 wfProfileOut( $fname.'-interwiki' );
3555 wfProfileOut( $fname );
3560 * Replace <!--LINK--> link placeholders with plain text of links
3561 * (not HTML-formatted).
3562 * @param string $text
3565 function replaceLinkHoldersText( $text ) {
3567 global $wgOutputReplace;
3569 $fname = 'Parser::replaceLinkHoldersText';
3570 wfProfileIn( $fname );
3572 $text = preg_replace_callback(
3573 '/<!--(LINK|IWLINK) (.*?)-->/',
3574 array( &$this, 'replaceLinkHoldersTextCallback' ),
3577 wfProfileOut( $fname );
3582 * @param array $matches
3586 function replaceLinkHoldersTextCallback( $matches ) {
3587 $type = $matches[1];
3589 if( $type == 'LINK' ) {
3590 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3591 return $this->mLinkHolders
['texts'][$key];
3593 } elseif( $type == 'IWLINK' ) {
3594 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3595 return $this->mInterwikiLinkHolders
['texts'][$key];
3602 * Renders an image gallery from a text with one line per image.
3603 * text labels may be given by using |-style alternative text. E.g.
3604 * Image:one.jpg|The number "1"
3605 * Image:tree.jpg|A tree
3606 * given as text will return the HTML of a gallery with two images,
3607 * labeled 'The number "1"' and
3610 function renderImageGallery( $text ) {
3612 $parserOptions = new ParserOptions
;
3613 $localParser = new Parser();
3615 $ig = new ImageGallery();
3616 $ig->setShowBytes( false );
3617 $ig->setShowFilename( false );
3618 $lines = explode( "\n", $text );
3620 foreach ( $lines as $line ) {
3621 # match lines like these:
3622 # Image:someimage.jpg|This is some image
3623 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3625 if ( count( $matches ) == 0 ) {
3628 $nt =& Title
::newFromText( $matches[1] );
3629 if( is_null( $nt ) ) {
3630 # Bogus title. Ignore these so we don't bomb out later.
3633 if ( isset( $matches[3] ) ) {
3634 $label = $matches[3];
3639 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3640 $html = $pout->getText();
3642 $ig->add( new Image( $nt ), $html );
3643 $this->mOutput
->addImage( $nt->getDBkey() );
3645 return $ig->toHTML();
3649 * Parse image options text and use it to make an image
3651 function makeImage( &$nt, $options ) {
3652 global $wgContLang, $wgUseImageResize, $wgUser;
3656 # Check if the options text is of the form "options|alt text"
3658 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3659 # * left no resizing, just left align. label is used for alt= only
3660 # * right same, but right aligned
3661 # * none same, but not aligned
3662 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3663 # * center center the image
3664 # * framed Keep original image size, no magnify-button.
3666 $part = explode( '|', $options);
3668 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3669 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3670 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3671 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3672 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3673 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3674 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3675 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3678 $width = $height = $framed = $thumb = false;
3679 $manual_thumb = '' ;
3681 foreach( $part as $key => $val ) {
3682 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3684 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3685 # use manually specified thumbnail
3687 $manual_thumb = $match;
3688 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3689 # remember to set an alignment, don't render immediately
3691 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3692 # remember to set an alignment, don't render immediately
3694 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3695 # remember to set an alignment, don't render immediately
3697 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3698 # remember to set an alignment, don't render immediately
3700 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3701 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3702 # $match is the image width in pixels
3703 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3704 $width = intval( $m[1] );
3705 $height = intval( $m[2] );
3707 $width = intval($match);
3709 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3715 # Strip bad stuff out of the alt text
3716 $alt = $this->replaceLinkHoldersText( $caption );
3717 $alt = Sanitizer
::stripAllTags( $alt );
3719 # Linker does the rest
3720 $sk =& $this->mOptions
->getSkin();
3721 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3725 * Set a flag in the output object indicating that the content is dynamic and
3726 * shouldn't be cached.
3728 function disableCache() {
3729 $this->mOutput
->mCacheTime
= -1;
3733 * Callback from the Sanitizer for expanding items found in HTML attribute
3734 * values, so they can be safely tested and escaped.
3735 * @param string $text
3736 * @param array $args
3740 function attributeStripCallback( &$text, $args ) {
3741 $text = $this->replaceVariables( $text, $args );
3742 $text = $this->unstripForHTML( $text );
3746 function unstripForHTML( $text ) {
3747 $text = $this->unstrip( $text, $this->mStripState
);
3748 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3756 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3757 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3758 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3764 function getTags() { return array_keys( $this->mTagHooks
); }
3770 * @package MediaWiki
3774 var $mText, # The output text
3775 $mLanguageLinks, # List of the full text of language links, in the order they appear
3776 $mCategories, # Map of category names to sort keys
3777 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3778 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3779 $mVersion, # Compatibility check
3780 $mTitleText, # title text of the chosen language variant
3781 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3782 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3783 $mImages, # DB keys of the images used, in the array key only
3784 $mExternalLinks; # External link URLs, in the key only
3786 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3787 $containsOldMagic = false, $titletext = '' )
3789 $this->mText
= $text;
3790 $this->mLanguageLinks
= $languageLinks;
3791 $this->mCategories
= $categoryLinks;
3792 $this->mContainsOldMagic
= $containsOldMagic;
3793 $this->mCacheTime
= '';
3794 $this->mVersion
= MW_PARSER_VERSION
;
3795 $this->mTitleText
= $titletext;
3796 $this->mLinks
= array();
3797 $this->mTemplates
= array();
3798 $this->mImages
= array();
3799 $this->mExternalLinks
= array();
3802 function getText() { return $this->mText
; }
3803 function getLanguageLinks() { return $this->mLanguageLinks
; }
3804 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3805 function &getCategories() { return $this->mCategories
; }
3806 function getCacheTime() { return $this->mCacheTime
; }
3807 function getTitleText() { return $this->mTitleText
; }
3808 function &getLinks() { return $this->mLinks
; }
3809 function &getTemplates() { return $this->mTemplates
; }
3810 function &getImages() { return $this->mImages
; }
3811 function &getExternalLinks() { return $this->mExternalLinks
; }
3813 function containsOldMagic() { return $this->mContainsOldMagic
; }
3814 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3815 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3816 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3817 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3818 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3819 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3821 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3822 function addImage( $name ) { $this->mImages
[$name] = 1; }
3823 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3824 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3826 function addLink( $title, $id ) {
3827 $ns = $title->getNamespace();
3828 $dbk = $title->getDBkey();
3829 if ( !isset( $this->mLinks
[$ns] ) ) {
3830 $this->mLinks
[$ns] = array();
3832 $this->mLinks
[$ns][$dbk] = $id;
3835 function addTemplate( $title, $id ) {
3836 $ns = $title->getNamespace();
3837 $dbk = $title->getDBkey();
3838 if ( !isset( $this->mTemplates
[$ns] ) ) {
3839 $this->mTemplates
[$ns] = array();
3841 $this->mTemplates
[$ns][$dbk] = $id;
3848 function merge( $other ) {
3849 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3850 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3851 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3855 * Return true if this cached output object predates the global or
3856 * per-article cache invalidation timestamps, or if it comes from
3857 * an incompatible older version.
3859 * @param string $touched the affected article's last touched timestamp
3863 function expired( $touched ) {
3864 global $wgCacheEpoch;
3865 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3866 $this->getCacheTime() < $touched ||
3867 $this->getCacheTime() <= $wgCacheEpoch ||
3868 !isset( $this->mVersion
) ||
3869 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3874 * Set options of the Parser
3876 * @package MediaWiki
3880 # All variables are private
3881 var $mUseTeX; # Use texvc to expand <math> tags
3882 var $mUseDynamicDates; # Use DateFormatter to format dates
3883 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3884 var $mAllowExternalImages; # Allow external images inline
3885 var $mAllowExternalImagesFrom; # If not, any exception?
3886 var $mSkin; # Reference to the preferred skin
3887 var $mDateFormat; # Date format index
3888 var $mEditSection; # Create "edit section" links
3889 var $mNumberHeadings; # Automatically number headings
3890 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3891 var $mTidy; # Ask for tidy cleanup
3893 function getUseTeX() { return $this->mUseTeX
; }
3894 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3895 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3896 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3897 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3898 function &getSkin() { return $this->mSkin
; }
3899 function getDateFormat() { return $this->mDateFormat
; }
3900 function getEditSection() { return $this->mEditSection
; }
3901 function getNumberHeadings() { return $this->mNumberHeadings
; }
3902 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3903 function getTidy() { return $this->mTidy
; }
3905 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3906 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3907 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3908 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3909 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3910 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3911 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3912 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3913 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3914 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
3915 function setSkin( &$x ) { $this->mSkin
=& $x; }
3917 function ParserOptions() {
3919 $this->initialiseFromUser( $wgUser );
3923 * Get parser options
3926 function newFromUser( &$user ) {
3927 $popts = new ParserOptions
;
3928 $popts->initialiseFromUser( $user );
3932 /** Get user options */
3933 function initialiseFromUser( &$userInput ) {
3934 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3935 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3936 $fname = 'ParserOptions::initialiseFromUser';
3937 wfProfileIn( $fname );
3938 if ( !$userInput ) {
3940 $user->setLoaded( true );
3942 $user =& $userInput;
3945 $this->mUseTeX
= $wgUseTeX;
3946 $this->mUseDynamicDates
= $wgUseDynamicDates;
3947 $this->mInterwikiMagic
= $wgInterwikiMagic;
3948 $this->mAllowExternalImages
= $wgAllowExternalImages;
3949 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
3950 wfProfileIn( $fname.'-skin' );
3951 $this->mSkin
=& $user->getSkin();
3952 wfProfileOut( $fname.'-skin' );
3953 $this->mDateFormat
= $user->getOption( 'date' );
3954 $this->mEditSection
= true;
3955 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
3956 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
3957 $this->mTidy
= false;
3958 wfProfileOut( $fname );
3963 * Callback function used by Parser::replaceLinkHolders()
3964 * to substitute link placeholders.
3966 function &wfOutputReplaceMatches( $matches ) {
3967 global $wgOutputReplace;
3968 return $wgOutputReplace[$matches[1]];
3972 * Return the total number of articles
3974 function wfNumberOfArticles() {
3975 global $wgNumberOfArticles;
3978 return $wgNumberOfArticles;
3982 * Return the number of files
3984 function wfNumberOfFiles() {
3985 $fname = 'Parser::wfNumberOfFiles';
3987 wfProfileIn( $fname );
3988 $dbr =& wfGetDB( DB_SLAVE
);
3989 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3990 wfProfileOut( $fname );
3996 * Get various statistics from the database
3999 function wfLoadSiteStats() {
4000 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4001 $fname = 'wfLoadSiteStats';
4003 if ( -1 != $wgNumberOfArticles ) return;
4004 $dbr =& wfGetDB( DB_SLAVE
);
4005 $s = $dbr->selectRow( 'site_stats',
4006 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4007 array( 'ss_row_id' => 1 ), $fname
4010 if ( $s === false ) {
4013 $wgTotalViews = $s->ss_total_views
;
4014 $wgTotalEdits = $s->ss_total_edits
;
4015 $wgNumberOfArticles = $s->ss_good_articles
;
4021 * Basically replacing " > and < with HTML entities ( ", >, <)
4023 * @param string $in Text that might contain HTML tags
4024 * @return string Escaped string
4026 function wfEscapeHTMLTagsOnly( $in ) {
4028 array( '"', '>', '<' ),
4029 array( '"', '>', '<' ),