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
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
122 $this->mTagHooks
= array();
131 function clearState() {
132 $this->mOutput
= new ParserOutput
;
133 $this->mAutonumber
= 0;
134 $this->mLastSection
= '';
135 $this->mDTopen
= false;
136 $this->mVariables
= false;
137 $this->mIncludeCount
= array();
138 $this->mStripState
= array();
139 $this->mArgStack
= array();
140 $this->mInPre
= false;
141 $this->mInterwikiLinkHolders
= array(
145 $this->mLinkHolders
= array(
146 'namespaces' => array(),
148 'queries' => array(),
152 $this->mRevisionId
= null;
153 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
155 # Clear these on every parse, bug 4549
156 $this->mTemplates
= array();
157 $this->mTemplatePath
= array();
159 wfRunHooks( 'ParserClearState', array( &$this ) );
163 * Accessor for mUniqPrefix.
167 function UniqPrefix() {
168 return $this->mUniqPrefix
;
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
198 $this->mOptions
= $options;
199 $this->mTitle
=& $title;
200 $this->mRevisionId
= $revid;
201 $this->mOutputType
= OT_HTML
;
203 $this->mStripState
= NULL;
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState
;
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
219 $text = $this->internalParse( $text );
221 $text = $this->unstrip( $text, $this->mStripState
);
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1 ',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
235 $text = $this->doBlockLevels( $text, $linestart );
237 $this->replaceLinkHolders( $text );
239 # the position of the parserConvert() call should not be changed. it
240 # assumes that the links are all replaced and the only thing left
241 # is the <nowiki> mark.
242 # Side-effects: this calls $this->mOutput->setTitleText()
243 $text = $wgContLang->parserConvert( $text, $this );
245 $text = $this->unstripNoWiki( $text, $this->mStripState
);
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
249 $text = Sanitizer
::normalizeCharReferences( $text );
251 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
252 $text = Parser
::tidy($text);
254 # attempt to sanitize at least some nesting problems
255 # (bug #2702 and quite a few others)
257 # ''Something [http://www.cool.com cool''] -->
258 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
259 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
260 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
261 # fix up an anchor inside another anchor, only
262 # at least for a single single nested link (bug 3695)
263 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
264 '\\1\\2</a>\\3</a>\\1\\4</a>',
265 # fix div inside inline elements- doBlockLevels won't wrap a line which
266 # contains a div, so fix it up here; replace
267 # div with escaped text
268 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
269 '\\1\\3<div\\5>\\6</div>\\8\\9',
270 # remove empty italic or bold tag pairs, some
271 # introduced by rules above
272 '/<([bi])><\/\\1>/' => ''
275 $text = preg_replace(
276 array_keys( $tidyregs ),
277 array_values( $tidyregs ),
281 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
283 $this->mOutput
->setText( $text );
284 wfProfileOut( $fname );
286 return $this->mOutput
;
290 * Get a random string
295 function getRandomString() {
296 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
299 function &getTitle() { return $this->mTitle
; }
300 function getOptions() { return $this->mOptions
; }
303 * Replaces all occurrences of <$tag>content</$tag> in the text
304 * with a random marker and returns the new text. the output parameter
305 * $content will be an associative array filled with data on the form
306 * $unique_marker => content.
308 * If $content is already set, the additional entries will be appended
309 * If $tag is set to STRIP_COMMENTS, the function will extract
310 * <!-- HTML comments -->
315 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
316 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
331 if( $tag == STRIP_COMMENTS
) {
332 $start = '/<!--()()/';
335 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
336 $end = "/<\\/$tag\\s*>/i";
339 while ( '' != $text ) {
340 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
342 if( count( $p ) < 4 ) {
349 $marker = $rnd . sprintf('%08X', $n++
);
350 $stripped .= $marker;
352 $tags[$marker] = "<$tag$attributes$empty>";
353 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
355 if ( $empty === '/' ) {
356 // Empty element tag, <tag />
357 $content[$marker] = null;
360 $q = preg_split( $end, $inside, 2 );
361 $content[$marker] = $q[0];
362 if( count( $q ) < 2 ) {
363 # No end tag -- let it run out to the end of the text.
374 * Wrapper function for extractTagsAndParams
375 * for cases where $tags and $params isn't needed
376 * i.e. where tags will never have params, like <nowiki>
381 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
382 $dummy_tags = array();
383 $dummy_params = array();
385 return Parser
::extractTagsAndParams( $tag, $text, $content,
386 $dummy_tags, $dummy_params, $uniq_prefix );
390 * Strips and renders nowiki, pre, math, hiero
391 * If $render is set, performs necessary rendering operations on plugins
392 * Returns the text, and fills an array with data needed in unstrip()
393 * If the $state is already a valid strip state, it adds to the state
395 * @param bool $stripcomments when set, HTML comments <!-- like this -->
396 * will be stripped in addition to other tags. This is important
397 * for section editing, where these comments cause confusion when
398 * counting the sections in the wikisource
402 function strip( $text, &$state, $stripcomments = false ) {
403 $render = ($this->mOutputType
== OT_HTML
);
404 $html_content = array();
405 $nowiki_content = array();
406 $math_content = array();
407 $pre_content = array();
408 $comment_content = array();
409 $ext_content = array();
411 $ext_params = array();
412 $gallery_content = array();
414 # Replace any instances of the placeholders
415 $uniq_prefix = $this->mUniqPrefix
;
416 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
421 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
422 foreach( $html_content as $marker => $content ) {
424 # Raw and unchecked for validity.
425 $html_content[$marker] = $content;
427 $html_content[$marker] = '<html>'.$content.'</html>';
433 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
434 foreach( $nowiki_content as $marker => $content ) {
436 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
438 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
443 if( $this->mOptions
->getUseTeX() ) {
444 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
445 foreach( $math_content as $marker => $content ){
447 $math_content[$marker] = renderMath( $content );
449 $math_content[$marker] = '<math>'.$content.'</math>';
455 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
456 foreach( $pre_content as $marker => $content ){
458 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
460 $pre_content[$marker] = '<pre>'.$content.'</pre>';
465 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
466 foreach( $gallery_content as $marker => $content ) {
467 require_once( 'ImageGallery.php' );
469 $gallery_content[$marker] = $this->renderImageGallery( $content );
471 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
477 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
478 foreach( $comment_content as $marker => $content ){
479 $comment_content[$marker] = '<!--'.$content.'-->';
484 foreach ( $this->mTagHooks
as $tag => $callback ) {
485 $ext_content[$tag] = array();
486 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
487 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
488 foreach( $ext_content[$tag] as $marker => $content ) {
489 $full_tag = $ext_tags[$tag][$marker];
490 $params = $ext_params[$tag][$marker];
492 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
494 if ( is_null( $content ) ) {
496 $ext_content[$tag][$marker] = $full_tag;
498 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
504 # Merge state with the pre-existing state, if there is one
506 $state['html'] = $state['html'] +
$html_content;
507 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
508 $state['math'] = $state['math'] +
$math_content;
509 $state['pre'] = $state['pre'] +
$pre_content;
510 $state['gallery'] = $state['gallery'] +
$gallery_content;
511 $state['comment'] = $state['comment'] +
$comment_content;
513 foreach( $ext_content as $tag => $array ) {
514 if ( array_key_exists( $tag, $state ) ) {
515 $state[$tag] = $state[$tag] +
$array;
520 'html' => $html_content,
521 'nowiki' => $nowiki_content,
522 'math' => $math_content,
523 'pre' => $pre_content,
524 'gallery' => $gallery_content,
525 'comment' => $comment_content,
532 * restores pre, math, and hiero removed by strip()
534 * always call unstripNoWiki() after this one
537 function unstrip( $text, &$state ) {
538 if ( !is_array( $state ) ) {
542 # Must expand in reverse order, otherwise nested tags will be corrupted
543 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
544 if( $tag != 'nowiki' && $tag != 'html' ) {
545 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
546 $text = str_replace( $uniq, $content, $text );
555 * always call this after unstrip() to preserve the order
559 function unstripNoWiki( $text, &$state ) {
560 if ( !is_array( $state ) ) {
564 # Must expand in reverse order, otherwise nested tags will be corrupted
565 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
566 $text = str_replace( key( $state['nowiki'] ), $content, $text );
571 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
572 $text = str_replace( key( $state['html'] ), $content, $text );
580 * Add an item to the strip state
581 * Returns the unique tag which must be inserted into the stripped text
582 * The tag will be replaced with the original text in unstrip()
586 function insertStripItem( $text, &$state ) {
587 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
594 'comment' => array(),
595 'gallery' => array(),
598 $state['item'][$rnd] = $text;
603 * Interface with html tidy, used if $wgUseTidy = true.
604 * If tidy isn't able to correct the markup, the original will be
605 * returned in all its glory with a warning comment appended.
607 * Either the external tidy program or the in-process tidy extension
608 * will be used depending on availability. Override the default
609 * $wgTidyInternal setting to disable the internal if it's not working.
611 * @param string $text Hideous HTML input
612 * @return string Corrected HTML output
616 function tidy( $text ) {
617 global $wgTidyInternal;
618 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
619 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
620 '<head><title>test</title></head><body>'.$text.'</body></html>';
621 if( $wgTidyInternal ) {
622 $correctedtext = Parser
::internalTidy( $wrappedtext );
624 $correctedtext = Parser
::externalTidy( $wrappedtext );
626 if( is_null( $correctedtext ) ) {
627 wfDebug( "Tidy error detected!\n" );
628 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
630 return $correctedtext;
634 * Spawn an external HTML tidy process and get corrected markup back from it.
639 function externalTidy( $text ) {
640 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
641 $fname = 'Parser::externalTidy';
642 wfProfileIn( $fname );
647 $descriptorspec = array(
648 0 => array('pipe', 'r'),
649 1 => array('pipe', 'w'),
650 2 => array('file', '/dev/null', 'a')
653 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
654 if (is_resource($process)) {
655 // Theoretically, this style of communication could cause a deadlock
656 // here. If the stdout buffer fills up, then writes to stdin could
657 // block. This doesn't appear to happen with tidy, because tidy only
658 // writes to stdout after it's finished reading from stdin. Search
659 // for tidyParseStdin and tidySaveStdout in console/tidy.c
660 fwrite($pipes[0], $text);
662 while (!feof($pipes[1])) {
663 $cleansource .= fgets($pipes[1], 1024);
666 proc_close($process);
669 wfProfileOut( $fname );
671 if( $cleansource == '' && $text != '') {
672 // Some kind of error happened, so we couldn't get the corrected text.
673 // Just give up; we'll use the source text and append a warning.
681 * Use the HTML tidy PECL extension to use the tidy library in-process,
682 * saving the overhead of spawning a new process. Currently written to
683 * the PHP 4.3.x version of the extension, may not work on PHP 5.
685 * 'pear install tidy' should be able to compile the extension module.
690 function internalTidy( $text ) {
692 $fname = 'Parser::internalTidy';
693 wfProfileIn( $fname );
695 tidy_load_config( $wgTidyConf );
696 tidy_set_encoding( 'utf8' );
697 tidy_parse_string( $text );
699 if( tidy_get_status() == 2 ) {
700 // 2 is magic number for fatal error
701 // http://www.php.net/manual/en/function.tidy-get-status.php
704 $cleansource = tidy_get_output();
706 wfProfileOut( $fname );
711 * parse the wiki syntax used to render tables
715 function doTableStuff ( $t ) {
716 $fname = 'Parser::doTableStuff';
717 wfProfileIn( $fname );
719 $t = explode ( "\n" , $t ) ;
720 $td = array () ; # Is currently a td tag open?
721 $ltd = array () ; # Was it TD or TH?
722 $tr = array () ; # Is currently a tr tag open?
723 $ltr = array () ; # tr attributes
724 $has_opened_tr = array(); # Did this table open a <tr> element?
725 $indent_level = 0; # indent level of the table
726 foreach ( $t AS $k => $x )
729 $fc = substr ( $x , 0 , 1 ) ;
730 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
731 $indent_level = strlen( $matches[1] );
733 $attributes = $this->unstripForHTML( $matches[2] );
735 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
736 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
737 array_push ( $td , false ) ;
738 array_push ( $ltd , '' ) ;
739 array_push ( $tr , false ) ;
740 array_push ( $ltr , '' ) ;
741 array_push ( $has_opened_tr, false );
743 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
744 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
745 $z = "</table>" . substr ( $x , 2);
746 $l = array_pop ( $ltd ) ;
747 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
748 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
749 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
751 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
753 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
754 $x = substr ( $x , 1 ) ;
755 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
757 $l = array_pop ( $ltd ) ;
758 array_pop ( $has_opened_tr );
759 array_push ( $has_opened_tr , true ) ;
760 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
761 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
764 array_push ( $tr , false ) ;
765 array_push ( $td , false ) ;
766 array_push ( $ltd , '' ) ;
767 $attributes = $this->unstripForHTML( $x );
768 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
770 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
772 if ( '|+' == substr ( $x , 0 , 2 ) ) {
774 $x = substr ( $x , 1 ) ;
776 $after = substr ( $x , 1 ) ;
777 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
778 $after = explode ( '||' , $after ) ;
781 # Loop through each table cell
782 foreach ( $after AS $theline )
787 $tra = array_pop ( $ltr ) ;
788 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
789 array_push ( $tr , true ) ;
790 array_push ( $ltr , '' ) ;
791 array_pop ( $has_opened_tr );
792 array_push ( $has_opened_tr , true ) ;
795 $l = array_pop ( $ltd ) ;
796 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
797 if ( $fc == '|' ) $l = 'td' ;
798 else if ( $fc == '!' ) $l = 'th' ;
799 else if ( $fc == '+' ) $l = 'caption' ;
801 array_push ( $ltd , $l ) ;
804 $y = explode ( '|' , $theline , 2 ) ;
805 # Note that a '|' inside an invalid link should not
806 # be mistaken as delimiting cell parameters
807 if ( strpos( $y[0], '[[' ) !== false ) {
808 $y = array ($theline);
810 if ( count ( $y ) == 1 )
811 $y = "{$z}<{$l}>{$y[0]}" ;
813 $attributes = $this->unstripForHTML( $y[0] );
814 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
817 array_push ( $td , true ) ;
822 # Closing open td, tr && table
823 while ( count ( $td ) > 0 )
825 $l = array_pop ( $ltd ) ;
826 if ( array_pop ( $td ) ) $t[] = '</td>' ;
827 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
828 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
832 $t = implode ( "\n" , $t ) ;
833 wfProfileOut( $fname );
838 * Helper function for parse() that transforms wiki markup into
839 * HTML. Only called for $mOutputType == OT_HTML.
843 function internalParse( $text ) {
846 $fname = 'Parser::internalParse';
847 wfProfileIn( $fname );
849 # Remove <noinclude> tags and <includeonly> sections
850 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
851 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
852 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
854 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
855 $text = $this->replaceVariables( $text, $args );
857 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
859 $text = $this->doHeadings( $text );
860 if($this->mOptions
->getUseDynamicDates()) {
861 $df =& DateFormatter
::getInstance();
862 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
864 $text = $this->doAllQuotes( $text );
865 $text = $this->replaceInternalLinks( $text );
866 $text = $this->replaceExternalLinks( $text );
868 # replaceInternalLinks may sometimes leave behind
869 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
870 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
872 $text = $this->doMagicLinks( $text );
873 $text = $this->doTableStuff( $text );
874 $text = $this->formatHeadings( $text, $isMain );
876 wfProfileOut( $fname );
881 * Replace special strings like "ISBN xxx" and "RFC xxx" with
882 * magic external links.
886 function &doMagicLinks( &$text ) {
887 $text = $this->magicISBN( $text );
888 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
889 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
894 * Parse headers and return html
898 function doHeadings( $text ) {
899 $fname = 'Parser::doHeadings';
900 wfProfileIn( $fname );
901 for ( $i = 6; $i >= 1; --$i ) {
902 $h = str_repeat( '=', $i );
903 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
904 "<h{$i}>\\1</h{$i}>\\2", $text );
906 wfProfileOut( $fname );
911 * Replace single quotes with HTML markup
913 * @return string the altered text
915 function doAllQuotes( $text ) {
916 $fname = 'Parser::doAllQuotes';
917 wfProfileIn( $fname );
919 $lines = explode( "\n", $text );
920 foreach ( $lines as $line ) {
921 $outtext .= $this->doQuotes ( $line ) . "\n";
923 $outtext = substr($outtext, 0,-1);
924 wfProfileOut( $fname );
929 * Helper function for doAllQuotes()
932 function doQuotes( $text ) {
933 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
934 if ( count( $arr ) == 1 )
938 # First, do some preliminary work. This may shift some apostrophes from
939 # being mark-up to being text. It also counts the number of occurrences
940 # of bold and italics mark-ups.
944 foreach ( $arr as $r )
946 if ( ( $i %
2 ) == 1 )
948 # If there are ever four apostrophes, assume the first is supposed to
949 # be text, and the remaining three constitute mark-up for bold text.
950 if ( strlen( $arr[$i] ) == 4 )
955 # If there are more than 5 apostrophes in a row, assume they're all
956 # text except for the last 5.
957 else if ( strlen( $arr[$i] ) > 5 )
959 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
962 # Count the number of occurrences of bold and italics mark-ups.
963 # We are not counting sequences of five apostrophes.
964 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
965 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
966 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
971 # If there is an odd number of both bold and italics, it is likely
972 # that one of the bold ones was meant to be an apostrophe followed
973 # by italics. Which one we cannot know for certain, but it is more
974 # likely to be one that has a single-letter word before it.
975 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
978 $firstsingleletterword = -1;
979 $firstmultiletterword = -1;
981 foreach ( $arr as $r )
983 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
985 $x1 = substr ($arr[$i-1], -1);
986 $x2 = substr ($arr[$i-1], -2, 1);
988 if ($firstspace == -1) $firstspace = $i;
989 } else if ($x2 == ' ') {
990 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
992 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
998 # If there is a single-letter word, use it!
999 if ($firstsingleletterword > -1)
1001 $arr [ $firstsingleletterword ] = "''";
1002 $arr [ $firstsingleletterword-1 ] .= "'";
1004 # If not, but there's a multi-letter word, use that one.
1005 else if ($firstmultiletterword > -1)
1007 $arr [ $firstmultiletterword ] = "''";
1008 $arr [ $firstmultiletterword-1 ] .= "'";
1010 # ... otherwise use the first one that has neither.
1011 # (notice that it is possible for all three to be -1 if, for example,
1012 # there is only one pentuple-apostrophe in the line)
1013 else if ($firstspace > -1)
1015 $arr [ $firstspace ] = "''";
1016 $arr [ $firstspace-1 ] .= "'";
1020 # Now let's actually convert our apostrophic mush to HTML!
1025 foreach ($arr as $r)
1029 if ($state == 'both')
1036 if (strlen ($r) == 2)
1039 { $output .= '</i>'; $state = ''; }
1040 else if ($state == 'bi')
1041 { $output .= '</i>'; $state = 'b'; }
1042 else if ($state == 'ib')
1043 { $output .= '</b></i><b>'; $state = 'b'; }
1044 else if ($state == 'both')
1045 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1046 else # $state can be 'b' or ''
1047 { $output .= '<i>'; $state .= 'i'; }
1049 else if (strlen ($r) == 3)
1052 { $output .= '</b>'; $state = ''; }
1053 else if ($state == 'bi')
1054 { $output .= '</i></b><i>'; $state = 'i'; }
1055 else if ($state == 'ib')
1056 { $output .= '</b>'; $state = 'i'; }
1057 else if ($state == 'both')
1058 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1059 else # $state can be 'i' or ''
1060 { $output .= '<b>'; $state .= 'b'; }
1062 else if (strlen ($r) == 5)
1065 { $output .= '</b><i>'; $state = 'i'; }
1066 else if ($state == 'i')
1067 { $output .= '</i><b>'; $state = 'b'; }
1068 else if ($state == 'bi')
1069 { $output .= '</i></b>'; $state = ''; }
1070 else if ($state == 'ib')
1071 { $output .= '</b></i>'; $state = ''; }
1072 else if ($state == 'both')
1073 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1074 else # ($state == '')
1075 { $buffer = ''; $state = 'both'; }
1080 # Now close all remaining tags. Notice that the order is important.
1081 if ($state == 'b' ||
$state == 'ib')
1083 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1087 if ($state == 'both')
1088 $output .= '<b><i>'.$buffer.'</i></b>';
1094 * Replace external links
1096 * Note: this is all very hackish and the order of execution matters a lot.
1097 * Make sure to run maintenance/parserTests.php if you change this code.
1101 function replaceExternalLinks( $text ) {
1103 $fname = 'Parser::replaceExternalLinks';
1104 wfProfileIn( $fname );
1106 $sk =& $this->mOptions
->getSkin();
1108 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1110 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1113 while ( $i<count( $bits ) ) {
1115 $protocol = $bits[$i++
];
1116 $text = $bits[$i++
];
1117 $trail = $bits[$i++
];
1119 # The characters '<' and '>' (which were escaped by
1120 # removeHTMLtags()) should not be included in
1121 # URLs, per RFC 2396.
1122 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1123 $text = substr($url, $m2[0][1]) . ' ' . $text;
1124 $url = substr($url, 0, $m2[0][1]);
1127 # If the link text is an image URL, replace it with an <img> tag
1128 # This happened by accident in the original parser, but some people used it extensively
1129 $img = $this->maybeMakeExternalImage( $text );
1130 if ( $img !== false ) {
1136 # Set linktype for CSS - if URL==text, link is essentially free
1137 $linktype = ($text == $url) ?
'free' : 'text';
1139 # No link text, e.g. [http://domain.tld/some.link]
1140 if ( $text == '' ) {
1141 # Autonumber if allowed
1142 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1143 $text = '[' . ++
$this->mAutonumber
. ']';
1144 $linktype = 'autonumber';
1146 # Otherwise just use the URL
1147 $text = htmlspecialchars( $url );
1151 # Have link text, e.g. [http://domain.tld/some.link text]s
1153 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1156 $text = $wgContLang->markNoConversion($text);
1158 # Replace & from obsolete syntax with &.
1159 # All HTML entities will be escaped by makeExternalLink()
1160 $url = str_replace( '&', '&', $url );
1162 # Process the trail (i.e. everything after this link up until start of the next link),
1163 # replacing any non-bracketed links
1164 $trail = $this->replaceFreeExternalLinks( $trail );
1166 # Use the encoded URL
1167 # This means that users can paste URLs directly into the text
1168 # Funny characters like ö aren't valid in URLs anyway
1169 # This was changed in August 2004
1170 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1172 # Register link in the output object.
1173 # Replace unnecessary URL escape codes with the referenced character
1174 # This prevents spammers from hiding links from the filters
1175 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1176 $this->mOutput
->addExternalLink( $pasteurized );
1179 wfProfileOut( $fname );
1184 * Replace anything that looks like a URL with a link
1187 function replaceFreeExternalLinks( $text ) {
1189 $fname = 'Parser::replaceFreeExternalLinks';
1190 wfProfileIn( $fname );
1192 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1193 $s = array_shift( $bits );
1196 $sk =& $this->mOptions
->getSkin();
1198 while ( $i < count( $bits ) ){
1199 $protocol = $bits[$i++
];
1200 $remainder = $bits[$i++
];
1202 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1203 # Found some characters after the protocol that look promising
1204 $url = $protocol . $m[1];
1207 # The characters '<' and '>' (which were escaped by
1208 # removeHTMLtags()) should not be included in
1209 # URLs, per RFC 2396.
1210 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1211 $trail = substr($url, $m2[0][1]) . $trail;
1212 $url = substr($url, 0, $m2[0][1]);
1215 # Move trailing punctuation to $trail
1217 # If there is no left bracket, then consider right brackets fair game too
1218 if ( strpos( $url, '(' ) === false ) {
1222 $numSepChars = strspn( strrev( $url ), $sep );
1223 if ( $numSepChars ) {
1224 $trail = substr( $url, -$numSepChars ) . $trail;
1225 $url = substr( $url, 0, -$numSepChars );
1228 # Replace & from obsolete syntax with &.
1229 # All HTML entities will be escaped by makeExternalLink()
1230 # or maybeMakeExternalImage()
1231 $url = str_replace( '&', '&', $url );
1233 # Is this an external image?
1234 $text = $this->maybeMakeExternalImage( $url );
1235 if ( $text === false ) {
1236 # Not an image, make a link
1237 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1238 # Register it in the output object...
1239 # Replace unnecessary URL escape codes with their equivalent characters
1240 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1241 $this->mOutput
->addExternalLink( $pasteurized );
1243 $s .= $text . $trail;
1245 $s .= $protocol . $remainder;
1248 wfProfileOut( $fname );
1253 * Replace unusual URL escape codes with their equivalent characters
1257 * @fixme This can merge genuinely required bits in the path or query string,
1258 * breaking legit URLs. A proper fix would treat the various parts of
1259 * the URL differently; as a workaround, just use the output for
1260 * statistical records, not for actual linking/output.
1262 function replaceUnusualEscapes( $url ) {
1263 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1264 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1268 * Callback function used in replaceUnusualEscapes().
1269 * Replaces unusual URL escape codes with their equivalent character
1273 function replaceUnusualEscapesCallback( $matches ) {
1274 $char = urldecode( $matches[0] );
1275 $ord = ord( $char );
1276 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1277 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1278 // No, shouldn't be escaped
1281 // Yes, leave it escaped
1287 * make an image if it's allowed, either through the global
1288 * option or through the exception
1291 function maybeMakeExternalImage( $url ) {
1292 $sk =& $this->mOptions
->getSkin();
1293 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1294 $imagesexception = !empty($imagesfrom);
1296 if ( $this->mOptions
->getAllowExternalImages()
1297 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1298 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1300 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1307 * Process [[ ]] wikilinks
1311 function replaceInternalLinks( $s ) {
1313 static $fname = 'Parser::replaceInternalLinks' ;
1315 wfProfileIn( $fname );
1317 wfProfileIn( $fname.'-setup' );
1319 # the % is needed to support urlencoded titles as well
1320 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1322 $sk =& $this->mOptions
->getSkin();
1324 #split the entire text string on occurences of [[
1325 $a = explode( '[[', ' ' . $s );
1326 #get the first element (all text up to first [[), and remove the space we added
1327 $s = array_shift( $a );
1328 $s = substr( $s, 1 );
1330 # Match a link having the form [[namespace:link|alternate]]trail
1332 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1333 # Match cases where there is no "]]", which might still be images
1334 static $e1_img = FALSE;
1335 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1336 # Match the end of a line for a word that's not followed by whitespace,
1337 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1338 $e2 = wfMsgForContent( 'linkprefix' );
1340 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1342 if( is_null( $this->mTitle
) ) {
1343 wfDebugDieBacktrace( 'nooo' );
1345 $nottalk = !$this->mTitle
->isTalkPage();
1347 if ( $useLinkPrefixExtension ) {
1348 if ( preg_match( $e2, $s, $m ) ) {
1349 $first_prefix = $m[2];
1351 $first_prefix = false;
1357 $selflink = $this->mTitle
->getPrefixedText();
1358 wfProfileOut( $fname.'-setup' );
1360 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1361 $useSubpages = $this->areSubpagesAllowed();
1363 # Loop for each link
1364 for ($k = 0; isset( $a[$k] ); $k++
) {
1366 if ( $useLinkPrefixExtension ) {
1367 wfProfileIn( $fname.'-prefixhandling' );
1368 if ( preg_match( $e2, $s, $m ) ) {
1376 $prefix = $first_prefix;
1377 $first_prefix = false;
1379 wfProfileOut( $fname.'-prefixhandling' );
1382 $might_be_img = false;
1384 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1386 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1387 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1388 # the real problem is with the $e1 regex
1391 # Still some problems for cases where the ] is meant to be outside punctuation,
1392 # and no image is in sight. See bug 2095.
1394 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1395 $text .= ']'; # so that replaceExternalLinks($text) works later
1398 # fix up urlencoded title texts
1399 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1401 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1402 $might_be_img = true;
1404 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1406 } else { # Invalid form; output directly
1407 $s .= $prefix . '[[' . $line ;
1411 # Don't allow internal links to pages containing
1412 # PROTO: where PROTO is a valid URL protocol; these
1413 # should be external links.
1414 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1415 $s .= $prefix . '[[' . $line ;
1419 # Make subpage if necessary
1420 if( $useSubpages ) {
1421 $link = $this->maybeDoSubpageLink( $m[1], $text );
1426 $noforce = (substr($m[1], 0, 1) != ':');
1428 # Strip off leading ':'
1429 $link = substr($link, 1);
1432 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1434 $s .= $prefix . '[[' . $line;
1438 #check other language variants of the link
1439 #if the article does not exist
1440 if( $checkVariantLink
1441 && $nt->getArticleID() == 0 ) {
1442 $wgContLang->findVariantLink($link, $nt);
1445 $ns = $nt->getNamespace();
1446 $iw = $nt->getInterWiki();
1448 if ($might_be_img) { # if this is actually an invalid link
1449 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1451 while (isset ($a[$k+
1]) ) {
1452 #look at the next 'line' to see if we can close it there
1453 $spliced = array_splice( $a, $k +
1, 1 );
1454 $next_line = array_shift( $spliced );
1455 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1456 # the first ]] closes the inner link, the second the image
1458 $text .= '[[' . $m[1];
1461 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1462 #if there's exactly one ]] that's fine, we'll keep looking
1463 $text .= '[[' . $m[0];
1465 #if $next_line is invalid too, we need look no further
1466 $text .= '[[' . $next_line;
1471 # we couldn't find the end of this imageLink, so output it raw
1472 #but don't ignore what might be perfectly normal links in the text we've examined
1473 $text = $this->replaceInternalLinks($text);
1474 $s .= $prefix . '[[' . $link . '|' . $text;
1475 # note: no $trail, because without an end, there *is* no trail
1478 } else { #it's not an image, so output it raw
1479 $s .= $prefix . '[[' . $link . '|' . $text;
1480 # note: no $trail, because without an end, there *is* no trail
1485 $wasblank = ( '' == $text );
1486 if( $wasblank ) $text = $link;
1489 # Link not escaped by : , create the various objects
1493 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1494 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1495 $s = rtrim($s . "\n");
1496 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1500 if ( $ns == NS_IMAGE
) {
1501 wfProfileIn( "$fname-image" );
1502 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1503 # recursively parse links inside the image caption
1504 # actually, this will parse them in any other parameters, too,
1505 # but it might be hard to fix that, and it doesn't matter ATM
1506 $text = $this->replaceExternalLinks($text);
1507 $text = $this->replaceInternalLinks($text);
1509 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1510 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1511 $this->mOutput
->addImage( $nt->getDBkey() );
1513 wfProfileOut( "$fname-image" );
1516 wfProfileOut( "$fname-image" );
1520 if ( $ns == NS_CATEGORY
) {
1521 wfProfileIn( "$fname-category" );
1522 $s = rtrim($s . "\n"); # bug 87
1525 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1526 $sortkey = $this->mTitle
->getText();
1528 $sortkey = $this->mTitle
->getPrefixedText();
1533 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1534 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1535 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1538 * Strip the whitespace Category links produce, see bug 87
1539 * @todo We might want to use trim($tmp, "\n") here.
1541 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1543 wfProfileOut( "$fname-category" );
1548 if( ( $nt->getPrefixedText() === $selflink ) &&
1549 ( $nt->getFragment() === '' ) ) {
1550 # Self-links are handled specially; generally de-link and change to bold.
1551 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1555 # Special and Media are pseudo-namespaces; no pages actually exist in them
1556 if( $ns == NS_MEDIA
) {
1557 $link = $sk->makeMediaLinkObj( $nt, $text );
1558 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1559 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1560 $this->mOutput
->addImage( $nt->getDBkey() );
1562 } elseif( $ns == NS_SPECIAL
) {
1563 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1565 } elseif( $ns == NS_IMAGE
) {
1566 $img = Image
::newFromTitle( $nt );
1567 if( $img->exists() ) {
1568 // Force a blue link if the file exists; may be a remote
1569 // upload on the shared repository, and we want to see its
1570 // auto-generated page.
1571 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1575 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1577 wfProfileOut( $fname );
1582 * Make a link placeholder. The text returned can be later resolved to a real link with
1583 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1584 * parsing of interwiki links, and secondly to allow all extistence checks and
1585 * article length checks (for stub links) to be bundled into a single query.
1588 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1589 if ( ! is_object($nt) ) {
1591 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1593 # Separate the link trail from the rest of the link
1594 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1596 if ( $nt->isExternal() ) {
1597 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1598 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1599 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1601 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1602 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1603 $this->mLinkHolders
['queries'][] = $query;
1604 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1605 $this->mLinkHolders
['titles'][] = $nt;
1607 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1614 * Render a forced-blue link inline; protect against double expansion of
1615 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1616 * Since this little disaster has to split off the trail text to avoid
1617 * breaking URLs in the following text without breaking trails on the
1618 * wiki links, it's been made into a horrible function.
1621 * @param string $text
1622 * @param string $query
1623 * @param string $trail
1624 * @param string $prefix
1625 * @return string HTML-wikitext mix oh yuck
1627 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1628 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1629 $sk =& $this->mOptions
->getSkin();
1630 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1631 return $this->armorLinks( $link ) . $trail;
1635 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1636 * going to go through further parsing steps before inline URL expansion.
1638 * In particular this is important when using action=render, which causes
1639 * full URLs to be included.
1641 * Oh man I hate our multi-layer parser!
1643 * @param string more-or-less HTML
1644 * @return string less-or-more HTML with NOPARSE bits
1646 function armorLinks( $text ) {
1647 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1648 "{$this->mUniqPrefix}NOPARSE$1", $text );
1652 * Return true if subpage links should be expanded on this page.
1655 function areSubpagesAllowed() {
1656 # Some namespaces don't allow subpages
1657 global $wgNamespacesWithSubpages;
1658 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1662 * Handle link to subpage if necessary
1663 * @param string $target the source of the link
1664 * @param string &$text the link text, modified as necessary
1665 * @return string the full name of the link
1668 function maybeDoSubpageLink($target, &$text) {
1671 # :Foobar -- override special treatment of prefix (images, language links)
1672 # /Foobar -- convert to CurrentPage/Foobar
1673 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1674 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1675 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1677 $fname = 'Parser::maybeDoSubpageLink';
1678 wfProfileIn( $fname );
1679 $ret = $target; # default return value is no change
1681 # Some namespaces don't allow subpages,
1682 # so only perform processing if subpages are allowed
1683 if( $this->areSubpagesAllowed() ) {
1684 # Look at the first character
1685 if( $target != '' && $target{0} == '/' ) {
1686 # / at end means we don't want the slash to be shown
1687 if( substr( $target, -1, 1 ) == '/' ) {
1688 $target = substr( $target, 1, -1 );
1691 $noslash = substr( $target, 1 );
1694 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1695 if( '' === $text ) {
1697 } # this might be changed for ugliness reasons
1699 # check for .. subpage backlinks
1701 $nodotdot = $target;
1702 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1704 $nodotdot = substr( $nodotdot, 3 );
1706 if($dotdotcount > 0) {
1707 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1708 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1709 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1710 # / at the end means don't show full path
1711 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1712 $nodotdot = substr( $nodotdot, 0, -1 );
1713 if( '' === $text ) {
1717 $nodotdot = trim( $nodotdot );
1718 if( $nodotdot != '' ) {
1719 $ret .= '/' . $nodotdot;
1726 wfProfileOut( $fname );
1731 * Used by doBlockLevels()
1734 /* private */ function closeParagraph() {
1736 if ( '' != $this->mLastSection
) {
1737 $result = '</' . $this->mLastSection
. ">\n";
1739 $this->mInPre
= false;
1740 $this->mLastSection
= '';
1743 # getCommon() returns the length of the longest common substring
1744 # of both arguments, starting at the beginning of both.
1746 /* private */ function getCommon( $st1, $st2 ) {
1747 $fl = strlen( $st1 );
1748 $shorter = strlen( $st2 );
1749 if ( $fl < $shorter ) { $shorter = $fl; }
1751 for ( $i = 0; $i < $shorter; ++
$i ) {
1752 if ( $st1{$i} != $st2{$i} ) { break; }
1756 # These next three functions open, continue, and close the list
1757 # element appropriate to the prefix character passed into them.
1759 /* private */ function openList( $char ) {
1760 $result = $this->closeParagraph();
1762 if ( '*' == $char ) { $result .= '<ul><li>'; }
1763 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1764 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1765 else if ( ';' == $char ) {
1766 $result .= '<dl><dt>';
1767 $this->mDTopen
= true;
1769 else { $result = '<!-- ERR 1 -->'; }
1774 /* private */ function nextItem( $char ) {
1775 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1776 else if ( ':' == $char ||
';' == $char ) {
1778 if ( $this->mDTopen
) { $close = '</dt>'; }
1779 if ( ';' == $char ) {
1780 $this->mDTopen
= true;
1781 return $close . '<dt>';
1783 $this->mDTopen
= false;
1784 return $close . '<dd>';
1787 return '<!-- ERR 2 -->';
1790 /* private */ function closeList( $char ) {
1791 if ( '*' == $char ) { $text = '</li></ul>'; }
1792 else if ( '#' == $char ) { $text = '</li></ol>'; }
1793 else if ( ':' == $char ) {
1794 if ( $this->mDTopen
) {
1795 $this->mDTopen
= false;
1796 $text = '</dt></dl>';
1798 $text = '</dd></dl>';
1801 else { return '<!-- ERR 3 -->'; }
1807 * Make lists from lines starting with ':', '*', '#', etc.
1810 * @return string the lists rendered as HTML
1812 function doBlockLevels( $text, $linestart ) {
1813 $fname = 'Parser::doBlockLevels';
1814 wfProfileIn( $fname );
1816 # Parsing through the text line by line. The main thing
1817 # happening here is handling of block-level elements p, pre,
1818 # and making lists from lines starting with * # : etc.
1820 $textLines = explode( "\n", $text );
1822 $lastPrefix = $output = '';
1823 $this->mDTopen
= $inBlockElem = false;
1825 $paragraphStack = false;
1827 if ( !$linestart ) {
1828 $output .= array_shift( $textLines );
1830 foreach ( $textLines as $oLine ) {
1831 $lastPrefixLength = strlen( $lastPrefix );
1832 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1833 $preOpenMatch = preg_match('/<pre/i', $oLine );
1834 if ( !$this->mInPre
) {
1835 # Multiple prefixes may abut each other for nested lists.
1836 $prefixLength = strspn( $oLine, '*#:;' );
1837 $pref = substr( $oLine, 0, $prefixLength );
1840 $pref2 = str_replace( ';', ':', $pref );
1841 $t = substr( $oLine, $prefixLength );
1842 $this->mInPre
= !empty($preOpenMatch);
1844 # Don't interpret any other prefixes in preformatted text
1846 $pref = $pref2 = '';
1851 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1852 # Same as the last item, so no need to deal with nesting or opening stuff
1853 $output .= $this->nextItem( substr( $pref, -1 ) );
1854 $paragraphStack = false;
1856 if ( substr( $pref, -1 ) == ';') {
1857 # The one nasty exception: definition lists work like this:
1858 # ; title : definition text
1859 # So we check for : in the remainder text to split up the
1860 # title and definition, without b0rking links.
1862 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1864 $output .= $term . $this->nextItem( ':' );
1867 } elseif( $prefixLength ||
$lastPrefixLength ) {
1868 # Either open or close a level...
1869 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1870 $paragraphStack = false;
1872 while( $commonPrefixLength < $lastPrefixLength ) {
1873 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1874 --$lastPrefixLength;
1876 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1877 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1879 while ( $prefixLength > $commonPrefixLength ) {
1880 $char = substr( $pref, $commonPrefixLength, 1 );
1881 $output .= $this->openList( $char );
1883 if ( ';' == $char ) {
1884 # FIXME: This is dupe of code above
1885 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1887 $output .= $term . $this->nextItem( ':' );
1890 ++
$commonPrefixLength;
1892 $lastPrefix = $pref2;
1894 if( 0 == $prefixLength ) {
1895 wfProfileIn( "$fname-paragraph" );
1896 # No prefix (not in list)--go to paragraph mode
1897 // XXX: use a stack for nestable elements like span, table and div
1898 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1899 $closematch = preg_match(
1900 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1901 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1902 if ( $openmatch or $closematch ) {
1903 $paragraphStack = false;
1904 $output .= $this->closeParagraph();
1905 if ( $preOpenMatch and !$preCloseMatch ) {
1906 $this->mInPre
= true;
1908 if ( $closematch ) {
1909 $inBlockElem = false;
1911 $inBlockElem = true;
1913 } else if ( !$inBlockElem && !$this->mInPre
) {
1914 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1916 if ($this->mLastSection
!= 'pre') {
1917 $paragraphStack = false;
1918 $output .= $this->closeParagraph().'<pre>';
1919 $this->mLastSection
= 'pre';
1921 $t = substr( $t, 1 );
1924 if ( '' == trim($t) ) {
1925 if ( $paragraphStack ) {
1926 $output .= $paragraphStack.'<br />';
1927 $paragraphStack = false;
1928 $this->mLastSection
= 'p';
1930 if ($this->mLastSection
!= 'p' ) {
1931 $output .= $this->closeParagraph();
1932 $this->mLastSection
= '';
1933 $paragraphStack = '<p>';
1935 $paragraphStack = '</p><p>';
1939 if ( $paragraphStack ) {
1940 $output .= $paragraphStack;
1941 $paragraphStack = false;
1942 $this->mLastSection
= 'p';
1943 } else if ($this->mLastSection
!= 'p') {
1944 $output .= $this->closeParagraph().'<p>';
1945 $this->mLastSection
= 'p';
1950 wfProfileOut( "$fname-paragraph" );
1952 // somewhere above we forget to get out of pre block (bug 785)
1953 if($preCloseMatch && $this->mInPre
) {
1954 $this->mInPre
= false;
1956 if ($paragraphStack === false) {
1960 while ( $prefixLength ) {
1961 $output .= $this->closeList( $pref2{$prefixLength-1} );
1964 if ( '' != $this->mLastSection
) {
1965 $output .= '</' . $this->mLastSection
. '>';
1966 $this->mLastSection
= '';
1969 wfProfileOut( $fname );
1974 * Split up a string on ':', ignoring any occurences inside
1975 * <a>..</a> or <span>...</span>
1976 * @param string $str the string to split
1977 * @param string &$before set to everything before the ':'
1978 * @param string &$after set to everything after the ':'
1979 * return string the position of the ':', or false if none found
1981 function findColonNoLinks($str, &$before, &$after) {
1982 # I wonder if we should make this count all tags, not just <a>
1983 # and <span>. That would prevent us from matching a ':' that
1984 # comes in the middle of italics other such formatting....
1986 $fname = 'Parser::findColonNoLinks';
1987 wfProfileIn( $fname );
1990 $colon = strpos($str, ':', $pos);
1992 if ($colon !== false) {
1993 $before = substr($str, 0, $colon);
1994 $after = substr($str, $colon +
1);
1996 # Skip any ':' within <a> or <span> pairs
1997 $a = substr_count($before, '<a');
1998 $s = substr_count($before, '<span');
1999 $ca = substr_count($before, '</a>');
2000 $cs = substr_count($before, '</span>');
2002 if ($a <= $ca and $s <= $cs) {
2003 # Tags are balanced before ':'; ok
2008 } while ($colon !== false);
2009 wfProfileOut( $fname );
2014 * Return value of a magic variable (like PAGENAME)
2018 function getVariableValue( $index ) {
2019 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2022 * Some of these require message or data lookups and can be
2023 * expensive to check many times.
2025 static $varCache = array();
2026 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2027 if ( isset( $varCache[$index] ) )
2028 return $varCache[$index];
2031 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2034 case MAG_CURRENTMONTH
:
2035 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2036 case MAG_CURRENTMONTHNAME
:
2037 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2038 case MAG_CURRENTMONTHNAMEGEN
:
2039 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2040 case MAG_CURRENTMONTHABBREV
:
2041 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2042 case MAG_CURRENTDAY
:
2043 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2044 case MAG_CURRENTDAY2
:
2045 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2047 return $this->mTitle
->getText();
2049 return $this->mTitle
->getPartialURL();
2050 case MAG_FULLPAGENAME
:
2051 return $this->mTitle
->getPrefixedText();
2052 case MAG_FULLPAGENAMEE
:
2053 return $this->mTitle
->getPrefixedURL();
2054 case MAG_SUBPAGENAME
:
2055 return $this->mTitle
->getSubpageText();
2056 case MAG_REVISIONID
:
2057 return $this->mRevisionId
;
2059 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2060 case MAG_NAMESPACEE
:
2061 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2062 case MAG_CURRENTDAYNAME
:
2063 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2064 case MAG_CURRENTYEAR
:
2065 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2066 case MAG_CURRENTTIME
:
2067 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2068 case MAG_CURRENTWEEK
:
2069 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2070 // int to remove the padding
2071 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2072 case MAG_CURRENTDOW
:
2073 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2074 case MAG_NUMBEROFARTICLES
:
2075 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2076 case MAG_NUMBEROFFILES
:
2077 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2082 case MAG_SERVERNAME
:
2083 return $wgServerName;
2084 case MAG_SCRIPTPATH
:
2085 return $wgScriptPath;
2088 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2096 * initialise the magic variables (like CURRENTMONTHNAME)
2100 function initialiseVariables() {
2101 $fname = 'Parser::initialiseVariables';
2102 wfProfileIn( $fname );
2103 global $wgVariableIDs;
2104 $this->mVariables
= array();
2105 foreach ( $wgVariableIDs as $id ) {
2106 $mw =& MagicWord
::get( $id );
2107 $mw->addToArray( $this->mVariables
, $id );
2109 wfProfileOut( $fname );
2113 * parse any parentheses in format ((title|part|part))
2114 * and call callbacks to get a replacement text for any found piece
2116 * @param string $text The text to parse
2117 * @param array $callbacks rules in form:
2118 * '{' => array( # opening parentheses
2119 * 'end' => '}', # closing parentheses
2120 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2121 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2126 function replace_callback ($text, $callbacks) {
2127 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2128 $lastOpeningBrace = -1; # last not closed parentheses
2130 for ($i = 0; $i < strlen($text); $i++
) {
2131 # check for any opening brace
2134 foreach ($callbacks as $key => $value) {
2135 $pos = strpos ($text, $key, $i);
2136 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2142 if ($lastOpeningBrace >= 0) {
2143 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2145 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2150 $pos = strpos ($text, '|', $i);
2152 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2163 # found openning brace, lets add it to parentheses stack
2164 if (null != $rule) {
2165 $piece = array('brace' => $text[$i],
2166 'braceEnd' => $rule['end'],
2171 # count openning brace characters
2172 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2177 $piece['startAt'] = $i+
1;
2178 $piece['partStart'] = $i+
1;
2180 # we need to add to stack only if openning brace count is enough for any given rule
2181 foreach ($rule['cb'] as $cnt => $fn) {
2182 if ($piece['count'] >= $cnt) {
2183 $lastOpeningBrace ++
;
2184 $openingBraceStack[$lastOpeningBrace] = $piece;
2191 else if ($lastOpeningBrace >= 0) {
2192 # first check if it is a closing brace
2193 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2194 # lets check if it is enough characters for closing brace
2196 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2199 # if there are more closing parentheses than opening ones, we parse less
2200 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2201 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2203 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2205 $matchingCallback = null;
2206 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2207 if ($count >= $cnt && $matchingCount < $cnt) {
2208 $matchingCount = $cnt;
2209 $matchingCallback = $fn;
2213 if ($matchingCount == 0) {
2218 # lets set a title or last part (if '|' was found)
2219 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2220 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2222 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2224 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2225 $pieceEnd = $i +
$matchingCount;
2227 if( is_callable( $matchingCallback ) ) {
2229 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2230 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2231 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2232 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2234 # finally we can call a user callback and replace piece of text
2235 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2236 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2237 $i = $pieceStart +
strlen($replaceWith) - 1;
2240 # null value for callback means that parentheses should be parsed, but not replaced
2241 $i +
= $matchingCount - 1;
2244 # reset last openning parentheses, but keep it in case there are unused characters
2245 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2246 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2247 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2250 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2251 $openingBraceStack[$lastOpeningBrace--] = null;
2253 if ($matchingCount < $piece['count']) {
2254 $piece['count'] -= $matchingCount;
2255 $piece['startAt'] -= $matchingCount;
2256 $piece['partStart'] = $piece['startAt'];
2257 # do we still qualify for any callback with remaining count?
2258 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2259 if ($piece['count'] >= $cnt) {
2260 $lastOpeningBrace ++
;
2261 $openingBraceStack[$lastOpeningBrace] = $piece;
2269 # lets set a title if it is a first separator, or next part otherwise
2270 if ($text[$i] == '|') {
2271 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2272 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2273 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2276 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2278 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2287 * Replace magic variables, templates, and template arguments
2288 * with the appropriate text. Templates are substituted recursively,
2289 * taking care to avoid infinite loops.
2291 * Note that the substitution depends on value of $mOutputType:
2292 * OT_WIKI: only {{subst:}} templates
2293 * OT_MSG: only magic variables
2294 * OT_HTML: all templates and magic variables
2296 * @param string $tex The text to transform
2297 * @param array $args Key-value pairs representing template parameters to substitute
2298 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2301 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2302 # Prevent too big inclusions
2303 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2307 $fname = 'Parser::replaceVariables';
2308 wfProfileIn( $fname );
2310 # This function is called recursively. To keep track of arguments we need a stack:
2311 array_push( $this->mArgStack
, $args );
2313 $braceCallbacks = array();
2315 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2317 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2318 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2320 $callbacks = array();
2321 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2322 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2323 $text = $this->replace_callback ($text, $callbacks);
2325 array_pop( $this->mArgStack
);
2327 wfProfileOut( $fname );
2332 * Replace magic variables
2335 function variableSubstitution( $matches ) {
2336 $fname = 'Parser::variableSubstitution';
2337 $varname = $matches[1];
2338 wfProfileIn( $fname );
2339 if ( !$this->mVariables
) {
2340 $this->initialiseVariables();
2343 if ( $this->mOutputType
== OT_WIKI
) {
2344 # Do only magic variables prefixed by SUBST
2345 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2346 if (!$mwSubst->matchStartAndRemove( $varname ))
2348 # Note that if we don't substitute the variable below,
2349 # we don't remove the {{subst:}} magic word, in case
2350 # it is a template rather than a magic variable.
2352 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2353 $id = $this->mVariables
[$varname];
2354 $text = $this->getVariableValue( $id );
2355 $this->mOutput
->mContainsOldMagic
= true;
2357 $text = $matches[0];
2359 wfProfileOut( $fname );
2363 # Split template arguments
2364 function getTemplateArgs( $argsString ) {
2365 if ( $argsString === '' ) {
2369 $args = explode( '|', substr( $argsString, 1 ) );
2371 # If any of the arguments contains a '[[' but no ']]', it needs to be
2372 # merged with the next arg because the '|' character between belongs
2373 # to the link syntax and not the template parameter syntax.
2374 $argc = count($args);
2376 for ( $i = 0; $i < $argc-1; $i++
) {
2377 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2378 $args[$i] .= '|'.$args[$i+
1];
2379 array_splice($args, $i+
1, 1);
2389 * Return the text of a template, after recursively
2390 * replacing any variables or templates within the template.
2392 * @param array $piece The parts of the template
2393 * $piece['text']: matched text
2394 * $piece['title']: the title, i.e. the part before the |
2395 * $piece['parts']: the parameter array
2396 * @return string the text of the template
2399 function braceSubstitution( $piece ) {
2401 $fname = 'Parser::braceSubstitution';
2402 wfProfileIn( $fname );
2405 $found = false; # $text has been filled
2406 $nowiki = false; # wiki markup in $text should be escaped
2407 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2408 $noargs = false; # Don't replace triple-brace arguments in $text
2409 $replaceHeadings = false; # Make the edit section links go to the template not the article
2410 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2411 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2413 # Title object, where $text came from
2418 # $part1 is the bit before the first |, and must contain only title characters
2419 # $args is a list of arguments, starting from index 0, not including $part1
2421 $part1 = $piece['title'];
2422 # If the third subpattern matched anything, it will start with |
2424 if (null == $piece['parts']) {
2425 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2426 if ($replaceWith != $piece['text']) {
2427 $text = $replaceWith;
2434 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2435 $argc = count( $args );
2439 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2440 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2441 # One of two possibilities is true:
2442 # 1) Found SUBST but not in the PST phase
2443 # 2) Didn't find SUBST and in the PST phase
2444 # In either case, return without further processing
2445 $text = $piece['text'];
2452 # MSG, MSGNW, INT and RAW
2455 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2456 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2459 # Remove obsolete MSG:
2460 $mwMsg =& MagicWord
::get( MAG_MSG
);
2461 $mwMsg->matchStartAndRemove( $part1 );
2465 $mwRaw =& MagicWord
::get( MAG_RAW
);
2466 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2467 $forceRawInterwiki = true;
2470 # Check if it is an internal message
2471 $mwInt =& MagicWord
::get( MAG_INT
);
2472 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2473 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2474 $text = $linestart . wfMsgReal( $part1, $args, true );
2482 # Check for NS: (namespace expansion)
2483 $mwNs = MagicWord
::get( MAG_NS
);
2484 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2485 if ( intval( $part1 ) ||
$part1 == "0" ) {
2486 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2489 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2490 if ( !is_null( $index ) ) {
2491 $text = $linestart . $wgContLang->getNsText( $index );
2498 # LCFIRST, UCFIRST, LC and UC
2500 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2501 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2502 $lc =& MagicWord
::get( MAG_LC
);
2503 $uc =& MagicWord
::get( MAG_UC
);
2504 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2505 $text = $linestart . $wgContLang->lcfirst( $part1 );
2507 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2508 $text = $linestart . $wgContLang->ucfirst( $part1 );
2510 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2511 $text = $linestart . $wgContLang->lc( $part1 );
2513 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2514 $text = $linestart . $wgContLang->uc( $part1 );
2519 # LOCALURL and FULLURL
2521 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2522 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2523 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2524 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2527 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2528 $func = 'getLocalURL';
2529 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2530 $func = 'escapeLocalURL';
2531 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2532 $func = 'getFullURL';
2533 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2534 $func = 'escapeFullURL';
2539 if ( $func !== false ) {
2540 $title = Title
::newFromText( $part1 );
2541 if ( !is_null( $title ) ) {
2543 $text = $linestart . $title->$func( $args[0] );
2545 $text = $linestart . $title->$func();
2553 if ( !$found && $argc == 1 ) {
2554 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2555 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2556 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2562 if ( !$found && $argc >= 2 ) {
2563 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2564 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2565 if ($argc==2) {$args[2]=$args[1];}
2566 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2571 # Template table test
2573 # Did we encounter this template already? If yes, it is in the cache
2574 # and we need to check for loops.
2575 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2578 # Infinite loop test
2579 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2583 $text = $linestart .
2584 '{{' . $part1 . '}}' .
2585 '<!-- WARNING: template loop detected -->';
2586 wfDebug( "$fname: template loop broken at '$part1'\n" );
2588 # set $text to cached message.
2589 $text = $linestart . $this->mTemplates
[$piece['title']];
2593 # Load from database
2594 $lastPathLevel = $this->mTemplatePath
;
2597 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2598 if ($subpage !== '') {
2599 $ns = $this->mTitle
->getNamespace();
2601 $title = Title
::newFromText( $part1, $ns );
2603 if ( !is_null( $title ) ) {
2604 if ( !$title->isExternal() ) {
2605 # Check for excessive inclusion
2606 $dbk = $title->getPrefixedDBkey();
2607 if ( $this->incrementIncludeCount( $dbk ) ) {
2608 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2609 # Capture special page output
2610 $text = SpecialPage
::capturePath( $title );
2611 if ( is_string( $text ) ) {
2616 $this->disableCache();
2619 $articleContent = $this->fetchTemplate( $title );
2620 if ( $articleContent !== false ) {
2622 $text = $articleContent;
2623 $replaceHeadings = true;
2628 # If the title is valid but undisplayable, make a link to it
2629 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2630 $text = '[['.$title->getPrefixedText().']]';
2633 } elseif ( $title->isTrans() ) {
2634 // Interwiki transclusion
2635 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2636 $text = $this->interwikiTransclude( $title, 'render' );
2640 $text = $this->interwikiTransclude( $title, 'raw' );
2641 $replaceHeadings = true;
2646 # Template cache array insertion
2647 # Use the original $piece['title'] not the mangled $part1, so that
2648 # modifiers such as RAW: produce separate cache entries
2650 $this->mTemplates
[$piece['title']] = $text;
2651 $text = $linestart . $text;
2656 # Recursive parsing, escaping and link table handling
2657 # Only for HTML output
2658 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2659 $text = wfEscapeWikiText( $text );
2660 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2662 # Clean up argument array
2663 $assocArgs = array();
2665 foreach( $args as $arg ) {
2666 $eqpos = strpos( $arg, '=' );
2667 if ( $eqpos === false ) {
2668 $assocArgs[$index++
] = $arg;
2670 $name = trim( substr( $arg, 0, $eqpos ) );
2671 $value = trim( substr( $arg, $eqpos+
1 ) );
2672 if ( $value === false ) {
2675 if ( $name !== false ) {
2676 $assocArgs[$name] = $value;
2681 # Add a new element to the templace recursion path
2682 $this->mTemplatePath
[$part1] = 1;
2686 # If there are any <onlyinclude> tags, only include them
2687 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2688 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2690 foreach ($m[1] as $piece)
2693 # Remove <noinclude> sections and <includeonly> tags
2694 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2695 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2697 if( $this->mOutputType
== OT_HTML
) {
2698 # Strip <nowiki>, <pre>, etc.
2699 $text = $this->strip( $text, $this->mStripState
);
2700 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2702 $text = $this->replaceVariables( $text, $assocArgs );
2704 # If the template begins with a table or block-level
2705 # element, it should be treated as beginning a new line.
2706 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2707 $text = "\n" . $text;
2709 } elseif ( !$noargs ) {
2710 # $noparse and !$noargs
2711 # Just replace the arguments, not any double-brace items
2712 # This is used for rendered interwiki transclusion
2713 $text = $this->replaceVariables( $text, $assocArgs, true );
2716 # Prune lower levels off the recursion check path
2717 $this->mTemplatePath
= $lastPathLevel;
2720 wfProfileOut( $fname );
2721 return $piece['text'];
2724 # Replace raw HTML by a placeholder
2725 # Add a blank line preceding, to prevent it from mucking up
2726 # immediately preceding headings
2727 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2729 # replace ==section headers==
2730 # XXX this needs to go away once we have a better parser.
2731 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2732 if( !is_null( $title ) )
2733 $encodedname = base64_encode($title->getPrefixedDBkey());
2735 $encodedname = base64_encode("");
2736 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2737 PREG_SPLIT_DELIM_CAPTURE
);
2740 for( $i = 0; $i < count($m); $i +
= 2 ) {
2742 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2744 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2748 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2749 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2750 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2758 # Prune lower levels off the recursion check path
2759 $this->mTemplatePath
= $lastPathLevel;
2762 wfProfileOut( $fname );
2763 return $piece['text'];
2765 wfProfileOut( $fname );
2771 * Fetch the unparsed text of a template and register a reference to it.
2773 function fetchTemplate( $title ) {
2775 // Loop to fetch the article, with up to 1 redirect
2776 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2777 $rev = Revision
::newFromTitle( $title );
2778 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2782 $text = $rev->getText();
2783 if ( $text === false ) {
2787 $title = Title
::newFromRedirect( $text );
2793 * Transclude an interwiki link.
2795 function interwikiTransclude( $title, $action ) {
2796 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2798 if (!$wgEnableScaryTranscluding)
2799 return wfMsg('scarytranscludedisabled');
2801 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2802 // But we'll handle it generally anyway
2803 if ( $title->getNamespace() ) {
2804 // Use the canonical namespace, which should work anywhere
2805 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2807 $articleName = $title->getDBkey();
2810 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2811 $url .= "?action=$action";
2812 if (strlen($url) > 255)
2813 return wfMsg('scarytranscludetoolong');
2814 return $this->fetchScaryTemplateMaybeFromCache($url);
2817 function fetchScaryTemplateMaybeFromCache($url) {
2818 global $wgTranscludeCacheExpiry;
2819 $dbr =& wfGetDB(DB_SLAVE
);
2820 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2821 array('tc_url' => $url));
2823 $time = $obj->tc_time
;
2824 $text = $obj->tc_contents
;
2825 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2830 $text = wfGetHTTP($url);
2832 return wfMsg('scarytranscludefailed', $url);
2834 $dbw =& wfGetDB(DB_MASTER
);
2835 $dbw->replace('transcache', array('tc_url'), array(
2837 'tc_time' => time(),
2838 'tc_contents' => $text));
2844 * Triple brace replacement -- used for template arguments
2847 function argSubstitution( $matches ) {
2848 $arg = trim( $matches['title'] );
2849 $text = $matches['text'];
2850 $inputArgs = end( $this->mArgStack
);
2852 if ( array_key_exists( $arg, $inputArgs ) ) {
2853 $text = $inputArgs[$arg];
2854 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2855 $text = $matches['parts'][0];
2862 * Returns true if the function is allowed to include this entity
2865 function incrementIncludeCount( $dbk ) {
2866 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2867 $this->mIncludeCount
[$dbk] = 0;
2869 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2877 * This function accomplishes several tasks:
2878 * 1) Auto-number headings if that option is enabled
2879 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2880 * 3) Add a Table of contents on the top for users who have enabled the option
2881 * 4) Auto-anchor headings
2883 * It loops through all headlines, collects the necessary data, then splits up the
2884 * string and re-inserts the newly formatted headlines.
2886 * @param string $text
2887 * @param boolean $isMain
2890 function formatHeadings( $text, $isMain=true ) {
2891 global $wgMaxTocLevel, $wgContLang;
2893 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2895 $forceTocHere = false;
2896 if( !$this->mTitle
->userCanEdit() ) {
2899 $showEditLink = $this->mOptions
->getEditSection();
2902 # Inhibit editsection links if requested in the page
2903 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2904 if( $esw->matchAndRemove( $text ) ) {
2907 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2909 $mw =& MagicWord
::get( MAG_NOTOC
);
2910 if( $mw->matchAndRemove( $text ) ) {
2914 # Get all headlines for numbering them and adding funky stuff like [edit]
2915 # links - this is for later, but we need the number of headlines right now
2916 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2918 # if there are fewer than 4 headlines in the article, do not show TOC
2919 if( $numMatches < 4 ) {
2923 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2924 # override above conditions and always show TOC at that place
2926 $mw =& MagicWord
::get( MAG_TOC
);
2927 if($mw->match( $text ) ) {
2929 $forceTocHere = true;
2931 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2932 # override above conditions and always show TOC above first header
2933 $mw =& MagicWord
::get( MAG_FORCETOC
);
2934 if ($mw->matchAndRemove( $text ) ) {
2939 # Never ever show TOC if no headers
2940 if( $numMatches < 1 ) {
2944 # We need this to perform operations on the HTML
2945 $sk =& $this->mOptions
->getSkin();
2949 $sectionCount = 0; # headlineCount excluding template sections
2951 # Ugh .. the TOC should have neat indentation levels which can be
2952 # passed to the skin functions. These are determined here
2956 $sublevelCount = array();
2957 $levelCount = array();
2964 foreach( $matches[3] as $headline ) {
2966 $templatetitle = '';
2967 $templatesection = 0;
2970 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2972 $templatetitle = base64_decode($mat[1]);
2973 $templatesection = 1 +
(int)base64_decode($mat[2]);
2974 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2978 $prevlevel = $level;
2979 $prevtoclevel = $toclevel;
2981 $level = $matches[1][$headlineCount];
2983 if( $doNumberHeadings ||
$doShowToc ) {
2985 if ( $level > $prevlevel ) {
2986 # Increase TOC level
2988 $sublevelCount[$toclevel] = 0;
2989 $toc .= $sk->tocIndent();
2991 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2992 # Decrease TOC level, find level to jump to
2994 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2995 # Can only go down to level 1
2998 for ($i = $toclevel; $i > 0; $i--) {
2999 if ( $levelCount[$i] == $level ) {
3000 # Found last matching level
3004 elseif ( $levelCount[$i] < $level ) {
3005 # Found first matching level below current level
3012 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3015 # No change in level, end TOC line
3016 $toc .= $sk->tocLineEnd();
3019 $levelCount[$toclevel] = $level;
3021 # count number of headlines for each level
3022 @$sublevelCount[$toclevel]++
;
3024 for( $i = 1; $i <= $toclevel; $i++
) {
3025 if( !empty( $sublevelCount[$i] ) ) {
3029 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3035 # The canonized header is a version of the header text safe to use for links
3036 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3037 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3038 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3040 # Remove link placeholders by the link text.
3041 # <!--LINK number-->
3043 # link text with suffix
3044 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3045 "\$this->mLinkHolders['texts'][\$1]",
3046 $canonized_headline );
3047 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3048 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3049 $canonized_headline );
3052 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3053 $tocline = trim( $canonized_headline );
3054 # Save headline for section edit hint before it's escaped
3055 $headline_hint = trim( $canonized_headline );
3056 $canonized_headline = Sanitizer
::escapeId( $tocline );
3057 $refers[$headlineCount] = $canonized_headline;
3059 # count how many in assoc. array so we can track dupes in anchors
3060 @$refers[$canonized_headline]++
;
3061 $refcount[$headlineCount]=$refers[$canonized_headline];
3063 # Don't number the heading if it is the only one (looks silly)
3064 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3065 # the two are different if the line contains a link
3066 $headline=$numbering . ' ' . $headline;
3069 # Create the anchor for linking from the TOC to the section
3070 $anchor = $canonized_headline;
3071 if($refcount[$headlineCount] > 1 ) {
3072 $anchor .= '_' . $refcount[$headlineCount];
3074 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3075 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3077 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3078 if ( empty( $head[$headlineCount] ) ) {
3079 $head[$headlineCount] = '';
3082 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3084 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3087 # give headline the correct <h#> tag
3088 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3096 $toc .= $sk->tocUnindent( $toclevel - 1 );
3097 $toc = $sk->tocList( $toc );
3100 # split up and insert constructed headlines
3102 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3105 foreach( $blocks as $block ) {
3106 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3107 # This is the [edit] link that appears for the top block of text when
3108 # section editing is enabled
3110 # Disabled because it broke block formatting
3111 # For example, a bullet point in the top line
3112 # $full .= $sk->editSectionLink(0);
3115 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3116 # Top anchor now in skin
3120 if( !empty( $head[$i] ) ) {
3126 $mw =& MagicWord
::get( MAG_TOC
);
3127 return $mw->replace( $toc, $full );
3134 * Return an HTML link for the "ISBN 123456" text
3137 function magicISBN( $text ) {
3138 $fname = 'Parser::magicISBN';
3139 wfProfileIn( $fname );
3141 $a = split( 'ISBN ', ' '.$text );
3142 if ( count ( $a ) < 2 ) {
3143 wfProfileOut( $fname );
3146 $text = substr( array_shift( $a ), 1);
3147 $valid = '0123456789-Xx';
3149 foreach ( $a as $x ) {
3150 $isbn = $blank = '' ;
3151 while ( ' ' == $x{0} ) {
3153 $x = substr( $x, 1 );
3155 if ( $x == '' ) { # blank isbn
3156 $text .= "ISBN $blank";
3159 while ( strstr( $valid, $x{0} ) != false ) {
3161 $x = substr( $x, 1 );
3163 $num = str_replace( '-', '', $isbn );
3164 $num = str_replace( ' ', '', $num );
3165 $num = str_replace( 'x', 'X', $num );
3168 $text .= "ISBN $blank$x";
3170 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3171 $text .= '<a href="' .
3172 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3173 "\" class=\"internal\">ISBN $isbn</a>";
3177 wfProfileOut( $fname );
3182 * Return an HTML link for the "RFC 1234" text
3185 * @param string $text Text to be processed
3186 * @param string $keyword Magic keyword to use (default RFC)
3187 * @param string $urlmsg Interface message to use (default rfcurl)
3190 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3192 $valid = '0123456789';
3195 $a = split( $keyword, ' '.$text );
3196 if ( count ( $a ) < 2 ) {
3199 $text = substr( array_shift( $a ), 1);
3201 /* Check if keyword is preceed by [[.
3202 * This test is made here cause of the array_shift above
3203 * that prevent the test to be done in the foreach.
3205 if ( substr( $text, -2 ) == '[[' ) {
3209 foreach ( $a as $x ) {
3210 /* token might be empty if we have RFC RFC 1234 */
3218 /** remove and save whitespaces in $blank */
3219 while ( $x{0} == ' ' ) {
3221 $x = substr( $x, 1 );
3224 /** remove and save the rfc number in $id */
3225 while ( strstr( $valid, $x{0} ) != false ) {
3227 $x = substr( $x, 1 );
3231 /* call back stripped spaces*/
3232 $text .= $keyword.$blank.$x;
3233 } elseif( $internal ) {
3235 $text .= $keyword.$id.$x;
3237 /* build the external link*/
3238 $url = wfMsg( $urlmsg, $id);
3239 $sk =& $this->mOptions
->getSkin();
3240 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3241 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3244 /* Check if the next RFC keyword is preceed by [[ */
3245 $internal = ( substr($x,-2) == '[[' );
3251 * Transform wiki markup when saving a page by doing \r\n -> \n
3252 * conversion, substitting signatures, {{subst:}} templates, etc.
3254 * @param string $text the text to transform
3255 * @param Title &$title the Title object for the current article
3256 * @param User &$user the User object describing the current user
3257 * @param ParserOptions $options parsing options
3258 * @param bool $clearState whether to clear the parser state first
3259 * @return string the altered wiki markup
3262 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3263 $this->mOptions
= $options;
3264 $this->mTitle
=& $title;
3265 $this->mOutputType
= OT_WIKI
;
3267 if ( $clearState ) {
3268 $this->clearState();
3271 $stripState = false;
3275 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3276 $text = $this->strip( $text, $stripState, true );
3277 $text = $this->pstPass2( $text, $user );
3278 $text = $this->unstrip( $text, $stripState );
3279 $text = $this->unstripNoWiki( $text, $stripState );
3284 * Pre-save transform helper function
3287 function pstPass2( $text, &$user ) {
3288 global $wgContLang, $wgLocaltimezone;
3290 /* Note: This is the timestamp saved as hardcoded wikitext to
3291 * the database, we use $wgContLang here in order to give
3292 * everyone the same signiture and use the default one rather
3293 * than the one selected in each users preferences.
3295 if ( isset( $wgLocaltimezone ) ) {
3296 $oldtz = getenv( 'TZ' );
3297 putenv( 'TZ='.$wgLocaltimezone );
3299 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3300 ' (' . date( 'T' ) . ')';
3301 if ( isset( $wgLocaltimezone ) ) {
3302 putenv( 'TZ='.$oldtz );
3305 # Variable replacement
3306 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3307 $text = $this->replaceVariables( $text );
3310 $sigText = $this->getUserSig( $user );
3311 $text = strtr( $text, array(
3313 '~~~~' => "$sigText $d",
3317 # Context links: [[|name]] and [[name (context)|]]
3319 global $wgLegalTitleChars;
3320 $tc = "[$wgLegalTitleChars]";
3321 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3323 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3324 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3326 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3327 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3328 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3329 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3331 $t = $this->mTitle
->getText();
3332 if ( preg_match( $conpat, $t, $m ) ) {
3335 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3336 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3337 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3339 if ( '' == $context ) {
3340 $text = preg_replace( $p2, '[[\\1]]', $text );
3342 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3345 # Trim trailing whitespace
3346 # MAG_END (__END__) tag allows for trailing
3347 # whitespace to be deliberately included
3348 $text = rtrim( $text );
3349 $mw =& MagicWord
::get( MAG_END
);
3350 $mw->matchAndRemove( $text );
3356 * Fetch the user's signature text, if any, and normalize to
3357 * validated, ready-to-insert wikitext.
3363 function getUserSig( &$user ) {
3364 $username = $user->getName();
3365 $nickname = $user->getOption( 'nickname' );
3366 $nickname = $nickname === '' ?
$username : $nickname;
3368 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3369 # Sig. might contain markup; validate this
3370 if( $this->validateSig( $nickname ) !== false ) {
3371 # Validated; clean up (if needed) and return it
3372 return( $this->cleanSig( $nickname ) );
3374 # Failed to validate; fall back to the default
3375 $nickname = $username;
3376 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3380 # If we're still here, make it a link to the user page
3381 $userpage = $user->getUserPage();
3382 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3386 * Check that the user's signature contains no bad XML
3388 * @param string $text
3389 * @return mixed An expanded string, or false if invalid.
3391 function validateSig( $text ) {
3392 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3396 * Clean up signature text
3398 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3399 * 2) Substitute all transclusions
3401 * @param string $text
3402 * @return string Signature text
3404 function cleanSig( $text ) {
3405 $substWord = MagicWord
::get( MAG_SUBST
);
3406 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3407 $substText = '{{' . $substWord->getSynonym( 0 );
3409 $text = preg_replace( $substRegex, $substText, $text );
3410 $text = preg_replace( '/~{3,5}/', '', $text );
3411 $text = $this->replaceVariables( $text );
3417 * Set up some variables which are usually set up in parse()
3418 * so that an external function can call some class members with confidence
3421 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3422 $this->mTitle
=& $title;
3423 $this->mOptions
= $options;
3424 $this->mOutputType
= $outputType;
3425 if ( $clearState ) {
3426 $this->clearState();
3431 * Transform a MediaWiki message by replacing magic variables.
3433 * @param string $text the text to transform
3434 * @param ParserOptions $options options
3435 * @return string the text with variables substituted
3438 function transformMsg( $text, $options ) {
3440 static $executing = false;
3442 $fname = "Parser::transformMsg";
3444 # Guard against infinite recursion
3450 wfProfileIn($fname);
3452 $this->mTitle
= $wgTitle;
3453 $this->mOptions
= $options;
3454 $this->mOutputType
= OT_MSG
;
3455 $this->clearState();
3456 $text = $this->replaceVariables( $text );
3459 wfProfileOut($fname);
3464 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3465 * The callback should have the following form:
3466 * function myParserHook( $text, $params, &$parser ) { ... }
3468 * Transform and return $text. Use $parser for any required context, e.g. use
3469 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3473 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3474 * @param mixed $callback The callback function (and object) to use for the tag
3476 * @return The old value of the mTagHooks array associated with the hook
3478 function setHook( $tag, $callback ) {
3479 $oldVal = @$this->mTagHooks
[$tag];
3480 $this->mTagHooks
[$tag] = $callback;
3486 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3487 * Placeholders created in Skin::makeLinkObj()
3488 * Returns an array of links found, indexed by PDBK:
3492 * $options is a bit field, RLH_FOR_UPDATE to select for update
3494 function replaceLinkHolders( &$text, $options = 0 ) {
3496 global $wgOutputReplace;
3498 $fname = 'Parser::replaceLinkHolders';
3499 wfProfileIn( $fname );
3503 $sk =& $this->mOptions
->getSkin();
3504 $linkCache =& LinkCache
::singleton();
3506 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3507 wfProfileIn( $fname.'-check' );
3508 $dbr =& wfGetDB( DB_SLAVE
);
3509 $page = $dbr->tableName( 'page' );
3510 $threshold = $wgUser->getOption('stubthreshold');
3513 asort( $this->mLinkHolders
['namespaces'] );
3517 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3519 $title = $this->mLinkHolders
['titles'][$key];
3521 # Skip invalid entries.
3522 # Result will be ugly, but prevents crash.
3523 if ( is_null( $title ) ) {
3526 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3528 # Check if it's a static known link, e.g. interwiki
3529 if ( $title->isAlwaysKnown() ) {
3530 $colours[$pdbk] = 1;
3531 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3532 $colours[$pdbk] = 1;
3533 $this->mOutput
->addLink( $title, $id );
3534 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3535 $colours[$pdbk] = 0;
3537 # Not in the link cache, add it to the query
3538 if ( !isset( $current ) ) {
3540 $query = "SELECT page_id, page_namespace, page_title";
3541 if ( $threshold > 0 ) {
3542 $query .= ', page_len, page_is_redirect';
3544 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3545 } elseif ( $current != $ns ) {
3547 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3552 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3557 if ( $options & RLH_FOR_UPDATE
) {
3558 $query .= ' FOR UPDATE';
3561 $res = $dbr->query( $query, $fname );
3563 # Fetch data and form into an associative array
3564 # non-existent = broken
3567 while ( $s = $dbr->fetchObject($res) ) {
3568 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3569 $pdbk = $title->getPrefixedDBkey();
3570 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3571 $this->mOutput
->addLink( $title, $s->page_id
);
3573 if ( $threshold > 0 ) {
3574 $size = $s->page_len
;
3575 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3576 $colours[$pdbk] = 1;
3578 $colours[$pdbk] = 2;
3581 $colours[$pdbk] = 1;
3585 wfProfileOut( $fname.'-check' );
3587 # Construct search and replace arrays
3588 wfProfileIn( $fname.'-construct' );
3589 $wgOutputReplace = array();
3590 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3591 $pdbk = $pdbks[$key];
3592 $searchkey = "<!--LINK $key-->";
3593 $title = $this->mLinkHolders
['titles'][$key];
3594 if ( empty( $colours[$pdbk] ) ) {
3595 $linkCache->addBadLinkObj( $title );
3596 $colours[$pdbk] = 0;
3597 $this->mOutput
->addLink( $title, 0 );
3598 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3599 $this->mLinkHolders
['texts'][$key],
3600 $this->mLinkHolders
['queries'][$key] );
3601 } elseif ( $colours[$pdbk] == 1 ) {
3602 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3603 $this->mLinkHolders
['texts'][$key],
3604 $this->mLinkHolders
['queries'][$key] );
3605 } elseif ( $colours[$pdbk] == 2 ) {
3606 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3607 $this->mLinkHolders
['texts'][$key],
3608 $this->mLinkHolders
['queries'][$key] );
3611 wfProfileOut( $fname.'-construct' );
3614 wfProfileIn( $fname.'-replace' );
3616 $text = preg_replace_callback(
3617 '/(<!--LINK .*?-->)/',
3618 "wfOutputReplaceMatches",
3621 wfProfileOut( $fname.'-replace' );
3624 # Now process interwiki link holders
3625 # This is quite a bit simpler than internal links
3626 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3627 wfProfileIn( $fname.'-interwiki' );
3628 # Make interwiki link HTML
3629 $wgOutputReplace = array();
3630 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3631 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3632 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3635 $text = preg_replace_callback(
3636 '/<!--IWLINK (.*?)-->/',
3637 "wfOutputReplaceMatches",
3639 wfProfileOut( $fname.'-interwiki' );
3642 wfProfileOut( $fname );
3647 * Replace <!--LINK--> link placeholders with plain text of links
3648 * (not HTML-formatted).
3649 * @param string $text
3652 function replaceLinkHoldersText( $text ) {
3653 $fname = 'Parser::replaceLinkHoldersText';
3654 wfProfileIn( $fname );
3656 $text = preg_replace_callback(
3657 '/<!--(LINK|IWLINK) (.*?)-->/',
3658 array( &$this, 'replaceLinkHoldersTextCallback' ),
3661 wfProfileOut( $fname );
3666 * @param array $matches
3670 function replaceLinkHoldersTextCallback( $matches ) {
3671 $type = $matches[1];
3673 if( $type == 'LINK' ) {
3674 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3675 return $this->mLinkHolders
['texts'][$key];
3677 } elseif( $type == 'IWLINK' ) {
3678 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3679 return $this->mInterwikiLinkHolders
['texts'][$key];
3686 * Renders an image gallery from a text with one line per image.
3687 * text labels may be given by using |-style alternative text. E.g.
3688 * Image:one.jpg|The number "1"
3689 * Image:tree.jpg|A tree
3690 * given as text will return the HTML of a gallery with two images,
3691 * labeled 'The number "1"' and
3694 function renderImageGallery( $text ) {
3696 $parserOptions = new ParserOptions
;
3697 $localParser = new Parser();
3699 $ig = new ImageGallery();
3700 $ig->setShowBytes( false );
3701 $ig->setShowFilename( false );
3702 $lines = explode( "\n", $text );
3704 foreach ( $lines as $line ) {
3705 # match lines like these:
3706 # Image:someimage.jpg|This is some image
3707 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3709 if ( count( $matches ) == 0 ) {
3712 $nt =& Title
::newFromText( $matches[1] );
3713 if( is_null( $nt ) ) {
3714 # Bogus title. Ignore these so we don't bomb out later.
3717 if ( isset( $matches[3] ) ) {
3718 $label = $matches[3];
3723 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3724 $html = $pout->getText();
3726 $ig->add( new Image( $nt ), $html );
3727 $this->mOutput
->addImage( $nt->getDBkey() );
3729 return $ig->toHTML();
3733 * Parse image options text and use it to make an image
3735 function makeImage( &$nt, $options ) {
3736 global $wgUseImageResize;
3740 # Check if the options text is of the form "options|alt text"
3742 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3743 # * left no resizing, just left align. label is used for alt= only
3744 # * right same, but right aligned
3745 # * none same, but not aligned
3746 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3747 # * center center the image
3748 # * framed Keep original image size, no magnify-button.
3750 $part = explode( '|', $options);
3752 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3753 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3754 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3755 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3756 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3757 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3758 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3759 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3762 $width = $height = $framed = $thumb = false;
3763 $manual_thumb = '' ;
3765 foreach( $part as $key => $val ) {
3766 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3768 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3769 # use manually specified thumbnail
3771 $manual_thumb = $match;
3772 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3773 # remember to set an alignment, don't render immediately
3775 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3776 # remember to set an alignment, don't render immediately
3778 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3779 # remember to set an alignment, don't render immediately
3781 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3782 # remember to set an alignment, don't render immediately
3784 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3785 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3786 # $match is the image width in pixels
3787 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3788 $width = intval( $m[1] );
3789 $height = intval( $m[2] );
3791 $width = intval($match);
3793 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3799 # Strip bad stuff out of the alt text
3800 $alt = $this->replaceLinkHoldersText( $caption );
3801 $alt = Sanitizer
::stripAllTags( $alt );
3803 # Linker does the rest
3804 $sk =& $this->mOptions
->getSkin();
3805 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3809 * Set a flag in the output object indicating that the content is dynamic and
3810 * shouldn't be cached.
3812 function disableCache() {
3813 $this->mOutput
->mCacheTime
= -1;
3817 * Callback from the Sanitizer for expanding items found in HTML attribute
3818 * values, so they can be safely tested and escaped.
3819 * @param string $text
3820 * @param array $args
3824 function attributeStripCallback( &$text, $args ) {
3825 $text = $this->replaceVariables( $text, $args );
3826 $text = $this->unstripForHTML( $text );
3830 function unstripForHTML( $text ) {
3831 $text = $this->unstrip( $text, $this->mStripState
);
3832 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3840 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3841 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3842 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3848 function getTags() { return array_keys( $this->mTagHooks
); }
3854 * @package MediaWiki
3858 var $mText, # The output text
3859 $mLanguageLinks, # List of the full text of language links, in the order they appear
3860 $mCategories, # Map of category names to sort keys
3861 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3862 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
3863 $mVersion, # Compatibility check
3864 $mTitleText, # title text of the chosen language variant
3865 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3866 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3867 $mImages, # DB keys of the images used, in the array key only
3868 $mExternalLinks; # External link URLs, in the key only
3870 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3871 $containsOldMagic = false, $titletext = '' )
3873 $this->mText
= $text;
3874 $this->mLanguageLinks
= $languageLinks;
3875 $this->mCategories
= $categoryLinks;
3876 $this->mContainsOldMagic
= $containsOldMagic;
3877 $this->mCacheTime
= '';
3878 $this->mVersion
= MW_PARSER_VERSION
;
3879 $this->mTitleText
= $titletext;
3880 $this->mLinks
= array();
3881 $this->mTemplates
= array();
3882 $this->mImages
= array();
3883 $this->mExternalLinks
= array();
3886 function getText() { return $this->mText
; }
3887 function getLanguageLinks() { return $this->mLanguageLinks
; }
3888 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3889 function &getCategories() { return $this->mCategories
; }
3890 function getCacheTime() { return $this->mCacheTime
; }
3891 function getTitleText() { return $this->mTitleText
; }
3892 function &getLinks() { return $this->mLinks
; }
3893 function &getTemplates() { return $this->mTemplates
; }
3894 function &getImages() { return $this->mImages
; }
3895 function &getExternalLinks() { return $this->mExternalLinks
; }
3897 function containsOldMagic() { return $this->mContainsOldMagic
; }
3898 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3899 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3900 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3901 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3902 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3903 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3905 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3906 function addImage( $name ) { $this->mImages
[$name] = 1; }
3907 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3908 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3910 function addLink( $title, $id ) {
3911 $ns = $title->getNamespace();
3912 $dbk = $title->getDBkey();
3913 if ( !isset( $this->mLinks
[$ns] ) ) {
3914 $this->mLinks
[$ns] = array();
3916 $this->mLinks
[$ns][$dbk] = $id;
3919 function addTemplate( $title, $id ) {
3920 $ns = $title->getNamespace();
3921 $dbk = $title->getDBkey();
3922 if ( !isset( $this->mTemplates
[$ns] ) ) {
3923 $this->mTemplates
[$ns] = array();
3925 $this->mTemplates
[$ns][$dbk] = $id;
3932 function merge( $other ) {
3933 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3934 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3935 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3939 * Return true if this cached output object predates the global or
3940 * per-article cache invalidation timestamps, or if it comes from
3941 * an incompatible older version.
3943 * @param string $touched the affected article's last touched timestamp
3947 function expired( $touched ) {
3948 global $wgCacheEpoch;
3949 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
3950 $this->getCacheTime() < $touched ||
3951 $this->getCacheTime() <= $wgCacheEpoch ||
3952 !isset( $this->mVersion
) ||
3953 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
3958 * Set options of the Parser
3960 * @package MediaWiki
3964 # All variables are private
3965 var $mUseTeX; # Use texvc to expand <math> tags
3966 var $mUseDynamicDates; # Use DateFormatter to format dates
3967 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3968 var $mAllowExternalImages; # Allow external images inline
3969 var $mAllowExternalImagesFrom; # If not, any exception?
3970 var $mSkin; # Reference to the preferred skin
3971 var $mDateFormat; # Date format index
3972 var $mEditSection; # Create "edit section" links
3973 var $mNumberHeadings; # Automatically number headings
3974 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3975 var $mTidy; # Ask for tidy cleanup
3977 function getUseTeX() { return $this->mUseTeX
; }
3978 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
3979 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
3980 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
3981 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
3982 function &getSkin() { return $this->mSkin
; }
3983 function getDateFormat() { return $this->mDateFormat
; }
3984 function getEditSection() { return $this->mEditSection
; }
3985 function getNumberHeadings() { return $this->mNumberHeadings
; }
3986 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
3987 function getTidy() { return $this->mTidy
; }
3989 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
3990 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
3991 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
3992 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
3993 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
3994 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
3995 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
3996 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
3997 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
3998 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
3999 function setSkin( &$x ) { $this->mSkin
=& $x; }
4001 function ParserOptions() {
4003 $this->initialiseFromUser( $wgUser );
4007 * Get parser options
4010 function newFromUser( &$user ) {
4011 $popts = new ParserOptions
;
4012 $popts->initialiseFromUser( $user );
4016 /** Get user options */
4017 function initialiseFromUser( &$userInput ) {
4018 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4019 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4020 $fname = 'ParserOptions::initialiseFromUser';
4021 wfProfileIn( $fname );
4022 if ( !$userInput ) {
4024 $user->setLoaded( true );
4026 $user =& $userInput;
4029 $this->mUseTeX
= $wgUseTeX;
4030 $this->mUseDynamicDates
= $wgUseDynamicDates;
4031 $this->mInterwikiMagic
= $wgInterwikiMagic;
4032 $this->mAllowExternalImages
= $wgAllowExternalImages;
4033 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4034 wfProfileIn( $fname.'-skin' );
4035 $this->mSkin
=& $user->getSkin();
4036 wfProfileOut( $fname.'-skin' );
4037 $this->mDateFormat
= $user->getOption( 'date' );
4038 $this->mEditSection
= true;
4039 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4040 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4041 $this->mTidy
= false;
4042 wfProfileOut( $fname );
4047 * Callback function used by Parser::replaceLinkHolders()
4048 * to substitute link placeholders.
4050 function &wfOutputReplaceMatches( $matches ) {
4051 global $wgOutputReplace;
4052 return $wgOutputReplace[$matches[1]];
4056 * Return the total number of articles
4058 function wfNumberOfArticles() {
4059 global $wgNumberOfArticles;
4062 return $wgNumberOfArticles;
4066 * Return the number of files
4068 function wfNumberOfFiles() {
4069 $fname = 'Parser::wfNumberOfFiles';
4071 wfProfileIn( $fname );
4072 $dbr =& wfGetDB( DB_SLAVE
);
4073 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4074 wfProfileOut( $fname );
4080 * Get various statistics from the database
4083 function wfLoadSiteStats() {
4084 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4085 $fname = 'wfLoadSiteStats';
4087 if ( -1 != $wgNumberOfArticles ) return;
4088 $dbr =& wfGetDB( DB_SLAVE
);
4089 $s = $dbr->selectRow( 'site_stats',
4090 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4091 array( 'ss_row_id' => 1 ), $fname
4094 if ( $s === false ) {
4097 $wgTotalViews = $s->ss_total_views
;
4098 $wgTotalEdits = $s->ss_total_edits
;
4099 $wgNumberOfArticles = $s->ss_good_articles
;
4105 * Basically replacing " > and < with HTML entities ( ", >, <)
4107 * @param string $in Text that might contain HTML tags
4108 * @return string Escaped string
4110 function wfEscapeHTMLTagsOnly( $in ) {
4112 array( '"', '>', '<' ),
4113 array( '"', '>', '<' ),