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>';
476 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
477 foreach( $comment_content as $marker => $content ){
478 $comment_content[$marker] = '<!--'.$content.'-->';
482 foreach ( $this->mTagHooks
as $tag => $callback ) {
483 $ext_content[$tag] = array();
484 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
485 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
486 foreach( $ext_content[$tag] as $marker => $content ) {
487 $full_tag = $ext_tags[$tag][$marker];
488 $params = $ext_params[$tag][$marker];
490 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
492 if ( is_null( $content ) ) {
494 $ext_content[$tag][$marker] = $full_tag;
496 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
502 # Unstrip comments unless explicitly told otherwise.
503 # (The comments are always stripped prior to this point, so as to
504 # not invoke any extension tags / parser hooks contained within
506 if ( !$stripcomments ) {
507 $tempstate = array( 'comment' => $comment_content );
508 $text = $this->unstrip( $text, $tempstate );
509 $comment_content = array();
512 # Merge state with the pre-existing state, if there is one
514 $state['html'] = $state['html'] +
$html_content;
515 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
516 $state['math'] = $state['math'] +
$math_content;
517 $state['pre'] = $state['pre'] +
$pre_content;
518 $state['gallery'] = $state['gallery'] +
$gallery_content;
519 $state['comment'] = $state['comment'] +
$comment_content;
521 foreach( $ext_content as $tag => $array ) {
522 if ( array_key_exists( $tag, $state ) ) {
523 $state[$tag] = $state[$tag] +
$array;
528 'html' => $html_content,
529 'nowiki' => $nowiki_content,
530 'math' => $math_content,
531 'pre' => $pre_content,
532 'gallery' => $gallery_content,
533 'comment' => $comment_content,
540 * restores pre, math, and hiero removed by strip()
542 * always call unstripNoWiki() after this one
545 function unstrip( $text, &$state ) {
546 if ( !is_array( $state ) ) {
550 # Must expand in reverse order, otherwise nested tags will be corrupted
551 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
552 if( $tag != 'nowiki' && $tag != 'html' ) {
553 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
554 $text = str_replace( $uniq, $content, $text );
563 * always call this after unstrip() to preserve the order
567 function unstripNoWiki( $text, &$state ) {
568 if ( !is_array( $state ) ) {
572 # Must expand in reverse order, otherwise nested tags will be corrupted
573 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
574 $text = str_replace( key( $state['nowiki'] ), $content, $text );
579 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
580 $text = str_replace( key( $state['html'] ), $content, $text );
588 * Add an item to the strip state
589 * Returns the unique tag which must be inserted into the stripped text
590 * The tag will be replaced with the original text in unstrip()
594 function insertStripItem( $text, &$state ) {
595 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
602 'comment' => array(),
603 'gallery' => array(),
606 $state['item'][$rnd] = $text;
611 * Interface with html tidy, used if $wgUseTidy = true.
612 * If tidy isn't able to correct the markup, the original will be
613 * returned in all its glory with a warning comment appended.
615 * Either the external tidy program or the in-process tidy extension
616 * will be used depending on availability. Override the default
617 * $wgTidyInternal setting to disable the internal if it's not working.
619 * @param string $text Hideous HTML input
620 * @return string Corrected HTML output
624 function tidy( $text ) {
625 global $wgTidyInternal;
626 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
627 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
628 '<head><title>test</title></head><body>'.$text.'</body></html>';
629 if( $wgTidyInternal ) {
630 $correctedtext = Parser
::internalTidy( $wrappedtext );
632 $correctedtext = Parser
::externalTidy( $wrappedtext );
634 if( is_null( $correctedtext ) ) {
635 wfDebug( "Tidy error detected!\n" );
636 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
638 return $correctedtext;
642 * Spawn an external HTML tidy process and get corrected markup back from it.
647 function externalTidy( $text ) {
648 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
649 $fname = 'Parser::externalTidy';
650 wfProfileIn( $fname );
655 $descriptorspec = array(
656 0 => array('pipe', 'r'),
657 1 => array('pipe', 'w'),
658 2 => array('file', '/dev/null', 'a')
661 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
662 if (is_resource($process)) {
663 // Theoretically, this style of communication could cause a deadlock
664 // here. If the stdout buffer fills up, then writes to stdin could
665 // block. This doesn't appear to happen with tidy, because tidy only
666 // writes to stdout after it's finished reading from stdin. Search
667 // for tidyParseStdin and tidySaveStdout in console/tidy.c
668 fwrite($pipes[0], $text);
670 while (!feof($pipes[1])) {
671 $cleansource .= fgets($pipes[1], 1024);
674 proc_close($process);
677 wfProfileOut( $fname );
679 if( $cleansource == '' && $text != '') {
680 // Some kind of error happened, so we couldn't get the corrected text.
681 // Just give up; we'll use the source text and append a warning.
689 * Use the HTML tidy PECL extension to use the tidy library in-process,
690 * saving the overhead of spawning a new process. Currently written to
691 * the PHP 4.3.x version of the extension, may not work on PHP 5.
693 * 'pear install tidy' should be able to compile the extension module.
698 function internalTidy( $text ) {
700 $fname = 'Parser::internalTidy';
701 wfProfileIn( $fname );
703 tidy_load_config( $wgTidyConf );
704 tidy_set_encoding( 'utf8' );
705 tidy_parse_string( $text );
707 if( tidy_get_status() == 2 ) {
708 // 2 is magic number for fatal error
709 // http://www.php.net/manual/en/function.tidy-get-status.php
712 $cleansource = tidy_get_output();
714 wfProfileOut( $fname );
719 * parse the wiki syntax used to render tables
723 function doTableStuff ( $t ) {
724 $fname = 'Parser::doTableStuff';
725 wfProfileIn( $fname );
727 $t = explode ( "\n" , $t ) ;
728 $td = array () ; # Is currently a td tag open?
729 $ltd = array () ; # Was it TD or TH?
730 $tr = array () ; # Is currently a tr tag open?
731 $ltr = array () ; # tr attributes
732 $has_opened_tr = array(); # Did this table open a <tr> element?
733 $indent_level = 0; # indent level of the table
734 foreach ( $t AS $k => $x )
737 $fc = substr ( $x , 0 , 1 ) ;
738 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
739 $indent_level = strlen( $matches[1] );
741 $attributes = $this->unstripForHTML( $matches[2] );
743 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
744 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
745 array_push ( $td , false ) ;
746 array_push ( $ltd , '' ) ;
747 array_push ( $tr , false ) ;
748 array_push ( $ltr , '' ) ;
749 array_push ( $has_opened_tr, false );
751 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
752 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
753 $z = "</table>" . substr ( $x , 2);
754 $l = array_pop ( $ltd ) ;
755 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
756 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
757 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
759 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
761 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
762 $x = substr ( $x , 1 ) ;
763 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
765 $l = array_pop ( $ltd ) ;
766 array_pop ( $has_opened_tr );
767 array_push ( $has_opened_tr , true ) ;
768 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
769 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
772 array_push ( $tr , false ) ;
773 array_push ( $td , false ) ;
774 array_push ( $ltd , '' ) ;
775 $attributes = $this->unstripForHTML( $x );
776 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
778 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
780 if ( '|+' == substr ( $x , 0 , 2 ) ) {
782 $x = substr ( $x , 1 ) ;
784 $after = substr ( $x , 1 ) ;
785 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
786 $after = explode ( '||' , $after ) ;
789 # Loop through each table cell
790 foreach ( $after AS $theline )
795 $tra = array_pop ( $ltr ) ;
796 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
797 array_push ( $tr , true ) ;
798 array_push ( $ltr , '' ) ;
799 array_pop ( $has_opened_tr );
800 array_push ( $has_opened_tr , true ) ;
803 $l = array_pop ( $ltd ) ;
804 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
805 if ( $fc == '|' ) $l = 'td' ;
806 else if ( $fc == '!' ) $l = 'th' ;
807 else if ( $fc == '+' ) $l = 'caption' ;
809 array_push ( $ltd , $l ) ;
812 $y = explode ( '|' , $theline , 2 ) ;
813 # Note that a '|' inside an invalid link should not
814 # be mistaken as delimiting cell parameters
815 if ( strpos( $y[0], '[[' ) !== false ) {
816 $y = array ($theline);
818 if ( count ( $y ) == 1 )
819 $y = "{$z}<{$l}>{$y[0]}" ;
821 $attributes = $this->unstripForHTML( $y[0] );
822 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
825 array_push ( $td , true ) ;
830 # Closing open td, tr && table
831 while ( count ( $td ) > 0 )
833 $l = array_pop ( $ltd ) ;
834 if ( array_pop ( $td ) ) $t[] = '</td>' ;
835 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
836 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
840 $t = implode ( "\n" , $t ) ;
841 # special case: don't return empty table
842 if($t == "<table>\n<tr><td></td></tr>\n</table>")
844 wfProfileOut( $fname );
849 * Helper function for parse() that transforms wiki markup into
850 * HTML. Only called for $mOutputType == OT_HTML.
854 function internalParse( $text ) {
857 $fname = 'Parser::internalParse';
858 wfProfileIn( $fname );
860 # Remove <noinclude> tags and <includeonly> sections
861 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
862 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
863 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
865 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
866 $text = $this->replaceVariables( $text, $args );
868 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
870 $text = $this->doHeadings( $text );
871 if($this->mOptions
->getUseDynamicDates()) {
872 $df =& DateFormatter
::getInstance();
873 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
875 $text = $this->doAllQuotes( $text );
876 $text = $this->replaceInternalLinks( $text );
877 $text = $this->replaceExternalLinks( $text );
879 # replaceInternalLinks may sometimes leave behind
880 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
881 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
883 $text = $this->doMagicLinks( $text );
884 $text = $this->doTableStuff( $text );
885 $text = $this->formatHeadings( $text, $isMain );
887 wfProfileOut( $fname );
892 * Replace special strings like "ISBN xxx" and "RFC xxx" with
893 * magic external links.
897 function &doMagicLinks( &$text ) {
898 $text = $this->magicISBN( $text );
899 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
900 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
905 * Parse headers and return html
909 function doHeadings( $text ) {
910 $fname = 'Parser::doHeadings';
911 wfProfileIn( $fname );
912 for ( $i = 6; $i >= 1; --$i ) {
913 $h = str_repeat( '=', $i );
914 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
915 "<h{$i}>\\1</h{$i}>\\2", $text );
917 wfProfileOut( $fname );
922 * Replace single quotes with HTML markup
924 * @return string the altered text
926 function doAllQuotes( $text ) {
927 $fname = 'Parser::doAllQuotes';
928 wfProfileIn( $fname );
930 $lines = explode( "\n", $text );
931 foreach ( $lines as $line ) {
932 $outtext .= $this->doQuotes ( $line ) . "\n";
934 $outtext = substr($outtext, 0,-1);
935 wfProfileOut( $fname );
940 * Helper function for doAllQuotes()
943 function doQuotes( $text ) {
944 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
945 if ( count( $arr ) == 1 )
949 # First, do some preliminary work. This may shift some apostrophes from
950 # being mark-up to being text. It also counts the number of occurrences
951 # of bold and italics mark-ups.
955 foreach ( $arr as $r )
957 if ( ( $i %
2 ) == 1 )
959 # If there are ever four apostrophes, assume the first is supposed to
960 # be text, and the remaining three constitute mark-up for bold text.
961 if ( strlen( $arr[$i] ) == 4 )
966 # If there are more than 5 apostrophes in a row, assume they're all
967 # text except for the last 5.
968 else if ( strlen( $arr[$i] ) > 5 )
970 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
973 # Count the number of occurrences of bold and italics mark-ups.
974 # We are not counting sequences of five apostrophes.
975 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
976 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
977 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
982 # If there is an odd number of both bold and italics, it is likely
983 # that one of the bold ones was meant to be an apostrophe followed
984 # by italics. Which one we cannot know for certain, but it is more
985 # likely to be one that has a single-letter word before it.
986 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
989 $firstsingleletterword = -1;
990 $firstmultiletterword = -1;
992 foreach ( $arr as $r )
994 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
996 $x1 = substr ($arr[$i-1], -1);
997 $x2 = substr ($arr[$i-1], -2, 1);
999 if ($firstspace == -1) $firstspace = $i;
1000 } else if ($x2 == ' ') {
1001 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1003 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1009 # If there is a single-letter word, use it!
1010 if ($firstsingleletterword > -1)
1012 $arr [ $firstsingleletterword ] = "''";
1013 $arr [ $firstsingleletterword-1 ] .= "'";
1015 # If not, but there's a multi-letter word, use that one.
1016 else if ($firstmultiletterword > -1)
1018 $arr [ $firstmultiletterword ] = "''";
1019 $arr [ $firstmultiletterword-1 ] .= "'";
1021 # ... otherwise use the first one that has neither.
1022 # (notice that it is possible for all three to be -1 if, for example,
1023 # there is only one pentuple-apostrophe in the line)
1024 else if ($firstspace > -1)
1026 $arr [ $firstspace ] = "''";
1027 $arr [ $firstspace-1 ] .= "'";
1031 # Now let's actually convert our apostrophic mush to HTML!
1036 foreach ($arr as $r)
1040 if ($state == 'both')
1047 if (strlen ($r) == 2)
1050 { $output .= '</i>'; $state = ''; }
1051 else if ($state == 'bi')
1052 { $output .= '</i>'; $state = 'b'; }
1053 else if ($state == 'ib')
1054 { $output .= '</b></i><b>'; $state = 'b'; }
1055 else if ($state == 'both')
1056 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1057 else # $state can be 'b' or ''
1058 { $output .= '<i>'; $state .= 'i'; }
1060 else if (strlen ($r) == 3)
1063 { $output .= '</b>'; $state = ''; }
1064 else if ($state == 'bi')
1065 { $output .= '</i></b><i>'; $state = 'i'; }
1066 else if ($state == 'ib')
1067 { $output .= '</b>'; $state = 'i'; }
1068 else if ($state == 'both')
1069 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1070 else # $state can be 'i' or ''
1071 { $output .= '<b>'; $state .= 'b'; }
1073 else if (strlen ($r) == 5)
1076 { $output .= '</b><i>'; $state = 'i'; }
1077 else if ($state == 'i')
1078 { $output .= '</i><b>'; $state = 'b'; }
1079 else if ($state == 'bi')
1080 { $output .= '</i></b>'; $state = ''; }
1081 else if ($state == 'ib')
1082 { $output .= '</b></i>'; $state = ''; }
1083 else if ($state == 'both')
1084 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1085 else # ($state == '')
1086 { $buffer = ''; $state = 'both'; }
1091 # Now close all remaining tags. Notice that the order is important.
1092 if ($state == 'b' ||
$state == 'ib')
1094 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1098 if ($state == 'both')
1099 $output .= '<b><i>'.$buffer.'</i></b>';
1105 * Replace external links
1107 * Note: this is all very hackish and the order of execution matters a lot.
1108 * Make sure to run maintenance/parserTests.php if you change this code.
1112 function replaceExternalLinks( $text ) {
1114 $fname = 'Parser::replaceExternalLinks';
1115 wfProfileIn( $fname );
1117 $sk =& $this->mOptions
->getSkin();
1119 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1121 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1124 while ( $i<count( $bits ) ) {
1126 $protocol = $bits[$i++
];
1127 $text = $bits[$i++
];
1128 $trail = $bits[$i++
];
1130 # The characters '<' and '>' (which were escaped by
1131 # removeHTMLtags()) should not be included in
1132 # URLs, per RFC 2396.
1133 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1134 $text = substr($url, $m2[0][1]) . ' ' . $text;
1135 $url = substr($url, 0, $m2[0][1]);
1138 # If the link text is an image URL, replace it with an <img> tag
1139 # This happened by accident in the original parser, but some people used it extensively
1140 $img = $this->maybeMakeExternalImage( $text );
1141 if ( $img !== false ) {
1147 # Set linktype for CSS - if URL==text, link is essentially free
1148 $linktype = ($text == $url) ?
'free' : 'text';
1150 # No link text, e.g. [http://domain.tld/some.link]
1151 if ( $text == '' ) {
1152 # Autonumber if allowed
1153 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1154 $text = '[' . ++
$this->mAutonumber
. ']';
1155 $linktype = 'autonumber';
1157 # Otherwise just use the URL
1158 $text = htmlspecialchars( $url );
1162 # Have link text, e.g. [http://domain.tld/some.link text]s
1164 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1167 $text = $wgContLang->markNoConversion($text);
1169 # Replace & from obsolete syntax with &.
1170 # All HTML entities will be escaped by makeExternalLink()
1171 $url = str_replace( '&', '&', $url );
1173 # Process the trail (i.e. everything after this link up until start of the next link),
1174 # replacing any non-bracketed links
1175 $trail = $this->replaceFreeExternalLinks( $trail );
1177 # Use the encoded URL
1178 # This means that users can paste URLs directly into the text
1179 # Funny characters like ö aren't valid in URLs anyway
1180 # This was changed in August 2004
1181 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1183 # Register link in the output object.
1184 # Replace unnecessary URL escape codes with the referenced character
1185 # This prevents spammers from hiding links from the filters
1186 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1187 $this->mOutput
->addExternalLink( $pasteurized );
1190 wfProfileOut( $fname );
1195 * Replace anything that looks like a URL with a link
1198 function replaceFreeExternalLinks( $text ) {
1200 $fname = 'Parser::replaceFreeExternalLinks';
1201 wfProfileIn( $fname );
1203 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1204 $s = array_shift( $bits );
1207 $sk =& $this->mOptions
->getSkin();
1209 while ( $i < count( $bits ) ){
1210 $protocol = $bits[$i++
];
1211 $remainder = $bits[$i++
];
1213 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1214 # Found some characters after the protocol that look promising
1215 $url = $protocol . $m[1];
1218 # special case: handle urls as url args:
1219 # http://www.example.com/foo?=http://www.example.com/bar
1220 if(strlen($trail) == 0 &&
1222 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1223 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1226 $url .= $bits[$i] . $bits[$i +
1]; # protocol, url as arg to previous link
1231 # The characters '<' and '>' (which were escaped by
1232 # removeHTMLtags()) should not be included in
1233 # URLs, per RFC 2396.
1234 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1235 $trail = substr($url, $m2[0][1]) . $trail;
1236 $url = substr($url, 0, $m2[0][1]);
1239 # Move trailing punctuation to $trail
1241 # If there is no left bracket, then consider right brackets fair game too
1242 if ( strpos( $url, '(' ) === false ) {
1246 $numSepChars = strspn( strrev( $url ), $sep );
1247 if ( $numSepChars ) {
1248 $trail = substr( $url, -$numSepChars ) . $trail;
1249 $url = substr( $url, 0, -$numSepChars );
1252 # Replace & from obsolete syntax with &.
1253 # All HTML entities will be escaped by makeExternalLink()
1254 # or maybeMakeExternalImage()
1255 $url = str_replace( '&', '&', $url );
1257 # Is this an external image?
1258 $text = $this->maybeMakeExternalImage( $url );
1259 if ( $text === false ) {
1260 # Not an image, make a link
1261 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1262 # Register it in the output object...
1263 # Replace unnecessary URL escape codes with their equivalent characters
1264 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1265 $this->mOutput
->addExternalLink( $pasteurized );
1267 $s .= $text . $trail;
1269 $s .= $protocol . $remainder;
1272 wfProfileOut( $fname );
1277 * Replace unusual URL escape codes with their equivalent characters
1281 * @fixme This can merge genuinely required bits in the path or query string,
1282 * breaking legit URLs. A proper fix would treat the various parts of
1283 * the URL differently; as a workaround, just use the output for
1284 * statistical records, not for actual linking/output.
1286 function replaceUnusualEscapes( $url ) {
1287 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1288 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1292 * Callback function used in replaceUnusualEscapes().
1293 * Replaces unusual URL escape codes with their equivalent character
1297 function replaceUnusualEscapesCallback( $matches ) {
1298 $char = urldecode( $matches[0] );
1299 $ord = ord( $char );
1300 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1301 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1302 // No, shouldn't be escaped
1305 // Yes, leave it escaped
1311 * make an image if it's allowed, either through the global
1312 * option or through the exception
1315 function maybeMakeExternalImage( $url ) {
1316 $sk =& $this->mOptions
->getSkin();
1317 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1318 $imagesexception = !empty($imagesfrom);
1320 if ( $this->mOptions
->getAllowExternalImages()
1321 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1322 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1324 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1331 * Process [[ ]] wikilinks
1335 function replaceInternalLinks( $s ) {
1337 static $fname = 'Parser::replaceInternalLinks' ;
1339 wfProfileIn( $fname );
1341 wfProfileIn( $fname.'-setup' );
1343 # the % is needed to support urlencoded titles as well
1344 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1346 $sk =& $this->mOptions
->getSkin();
1348 #split the entire text string on occurences of [[
1349 $a = explode( '[[', ' ' . $s );
1350 #get the first element (all text up to first [[), and remove the space we added
1351 $s = array_shift( $a );
1352 $s = substr( $s, 1 );
1354 # Match a link having the form [[namespace:link|alternate]]trail
1356 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1357 # Match cases where there is no "]]", which might still be images
1358 static $e1_img = FALSE;
1359 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1360 # Match the end of a line for a word that's not followed by whitespace,
1361 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1362 $e2 = wfMsgForContent( 'linkprefix' );
1364 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1366 if( is_null( $this->mTitle
) ) {
1367 wfDebugDieBacktrace( 'nooo' );
1369 $nottalk = !$this->mTitle
->isTalkPage();
1371 if ( $useLinkPrefixExtension ) {
1372 if ( preg_match( $e2, $s, $m ) ) {
1373 $first_prefix = $m[2];
1375 $first_prefix = false;
1381 $selflink = $this->mTitle
->getPrefixedText();
1382 wfProfileOut( $fname.'-setup' );
1384 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1385 $useSubpages = $this->areSubpagesAllowed();
1387 # Loop for each link
1388 for ($k = 0; isset( $a[$k] ); $k++
) {
1390 if ( $useLinkPrefixExtension ) {
1391 wfProfileIn( $fname.'-prefixhandling' );
1392 if ( preg_match( $e2, $s, $m ) ) {
1400 $prefix = $first_prefix;
1401 $first_prefix = false;
1403 wfProfileOut( $fname.'-prefixhandling' );
1406 $might_be_img = false;
1408 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1410 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1411 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1412 # the real problem is with the $e1 regex
1415 # Still some problems for cases where the ] is meant to be outside punctuation,
1416 # and no image is in sight. See bug 2095.
1419 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1420 strpos($text, '[') !== false
1423 $text .= ']'; # so that replaceExternalLinks($text) works later
1426 # fix up urlencoded title texts
1427 if(preg_match('/%/', $m[1] ))
1428 # Should anchors '#' also be rejected?
1429 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1431 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1432 $might_be_img = true;
1434 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1436 } else { # Invalid form; output directly
1437 $s .= $prefix . '[[' . $line ;
1441 # Don't allow internal links to pages containing
1442 # PROTO: where PROTO is a valid URL protocol; these
1443 # should be external links.
1444 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1445 $s .= $prefix . '[[' . $line ;
1449 # Make subpage if necessary
1450 if( $useSubpages ) {
1451 $link = $this->maybeDoSubpageLink( $m[1], $text );
1456 $noforce = (substr($m[1], 0, 1) != ':');
1458 # Strip off leading ':'
1459 $link = substr($link, 1);
1462 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1464 $s .= $prefix . '[[' . $line;
1468 #check other language variants of the link
1469 #if the article does not exist
1470 if( $checkVariantLink
1471 && $nt->getArticleID() == 0 ) {
1472 $wgContLang->findVariantLink($link, $nt);
1475 $ns = $nt->getNamespace();
1476 $iw = $nt->getInterWiki();
1478 if ($might_be_img) { # if this is actually an invalid link
1479 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1481 while (isset ($a[$k+
1]) ) {
1482 #look at the next 'line' to see if we can close it there
1483 $spliced = array_splice( $a, $k +
1, 1 );
1484 $next_line = array_shift( $spliced );
1485 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1486 # the first ]] closes the inner link, the second the image
1488 $text .= '[[' . $m[1];
1491 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1492 #if there's exactly one ]] that's fine, we'll keep looking
1493 $text .= '[[' . $m[0];
1495 #if $next_line is invalid too, we need look no further
1496 $text .= '[[' . $next_line;
1501 # we couldn't find the end of this imageLink, so output it raw
1502 #but don't ignore what might be perfectly normal links in the text we've examined
1503 $text = $this->replaceInternalLinks($text);
1504 $s .= $prefix . '[[' . $link . '|' . $text;
1505 # note: no $trail, because without an end, there *is* no trail
1508 } else { #it's not an image, so output it raw
1509 $s .= $prefix . '[[' . $link . '|' . $text;
1510 # note: no $trail, because without an end, there *is* no trail
1515 $wasblank = ( '' == $text );
1516 if( $wasblank ) $text = $link;
1519 # Link not escaped by : , create the various objects
1523 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1524 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1525 $s = rtrim($s . "\n");
1526 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1530 if ( $ns == NS_IMAGE
) {
1531 wfProfileIn( "$fname-image" );
1532 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1533 # recursively parse links inside the image caption
1534 # actually, this will parse them in any other parameters, too,
1535 # but it might be hard to fix that, and it doesn't matter ATM
1536 $text = $this->replaceExternalLinks($text);
1537 $text = $this->replaceInternalLinks($text);
1539 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1540 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1541 $this->mOutput
->addImage( $nt->getDBkey() );
1543 wfProfileOut( "$fname-image" );
1546 wfProfileOut( "$fname-image" );
1550 if ( $ns == NS_CATEGORY
) {
1551 wfProfileIn( "$fname-category" );
1552 $s = rtrim($s . "\n"); # bug 87
1555 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1556 $sortkey = $this->mTitle
->getText();
1558 $sortkey = $this->mTitle
->getPrefixedText();
1563 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1564 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1565 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1568 * Strip the whitespace Category links produce, see bug 87
1569 * @todo We might want to use trim($tmp, "\n") here.
1571 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1573 wfProfileOut( "$fname-category" );
1578 if( ( $nt->getPrefixedText() === $selflink ) &&
1579 ( $nt->getFragment() === '' ) ) {
1580 # Self-links are handled specially; generally de-link and change to bold.
1581 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1585 # Special and Media are pseudo-namespaces; no pages actually exist in them
1586 if( $ns == NS_MEDIA
) {
1587 $link = $sk->makeMediaLinkObj( $nt, $text );
1588 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1589 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1590 $this->mOutput
->addImage( $nt->getDBkey() );
1592 } elseif( $ns == NS_SPECIAL
) {
1593 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1595 } elseif( $ns == NS_IMAGE
) {
1596 $img = Image
::newFromTitle( $nt );
1597 if( $img->exists() ) {
1598 // Force a blue link if the file exists; may be a remote
1599 // upload on the shared repository, and we want to see its
1600 // auto-generated page.
1601 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1605 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1607 wfProfileOut( $fname );
1612 * Make a link placeholder. The text returned can be later resolved to a real link with
1613 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1614 * parsing of interwiki links, and secondly to allow all extistence checks and
1615 * article length checks (for stub links) to be bundled into a single query.
1618 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1619 if ( ! is_object($nt) ) {
1621 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1623 # Separate the link trail from the rest of the link
1624 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1626 if ( $nt->isExternal() ) {
1627 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1628 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1629 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1631 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1632 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1633 $this->mLinkHolders
['queries'][] = $query;
1634 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1635 $this->mLinkHolders
['titles'][] = $nt;
1637 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1644 * Render a forced-blue link inline; protect against double expansion of
1645 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1646 * Since this little disaster has to split off the trail text to avoid
1647 * breaking URLs in the following text without breaking trails on the
1648 * wiki links, it's been made into a horrible function.
1651 * @param string $text
1652 * @param string $query
1653 * @param string $trail
1654 * @param string $prefix
1655 * @return string HTML-wikitext mix oh yuck
1657 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1658 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1659 $sk =& $this->mOptions
->getSkin();
1660 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1661 return $this->armorLinks( $link ) . $trail;
1665 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1666 * going to go through further parsing steps before inline URL expansion.
1668 * In particular this is important when using action=render, which causes
1669 * full URLs to be included.
1671 * Oh man I hate our multi-layer parser!
1673 * @param string more-or-less HTML
1674 * @return string less-or-more HTML with NOPARSE bits
1676 function armorLinks( $text ) {
1677 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1678 "{$this->mUniqPrefix}NOPARSE$1", $text );
1682 * Return true if subpage links should be expanded on this page.
1685 function areSubpagesAllowed() {
1686 # Some namespaces don't allow subpages
1687 global $wgNamespacesWithSubpages;
1688 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1692 * Handle link to subpage if necessary
1693 * @param string $target the source of the link
1694 * @param string &$text the link text, modified as necessary
1695 * @return string the full name of the link
1698 function maybeDoSubpageLink($target, &$text) {
1701 # :Foobar -- override special treatment of prefix (images, language links)
1702 # /Foobar -- convert to CurrentPage/Foobar
1703 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1704 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1705 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1707 $fname = 'Parser::maybeDoSubpageLink';
1708 wfProfileIn( $fname );
1709 $ret = $target; # default return value is no change
1711 # Some namespaces don't allow subpages,
1712 # so only perform processing if subpages are allowed
1713 if( $this->areSubpagesAllowed() ) {
1714 # Look at the first character
1715 if( $target != '' && $target{0} == '/' ) {
1716 # / at end means we don't want the slash to be shown
1717 if( substr( $target, -1, 1 ) == '/' ) {
1718 $target = substr( $target, 1, -1 );
1721 $noslash = substr( $target, 1 );
1724 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1725 if( '' === $text ) {
1727 } # this might be changed for ugliness reasons
1729 # check for .. subpage backlinks
1731 $nodotdot = $target;
1732 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1734 $nodotdot = substr( $nodotdot, 3 );
1736 if($dotdotcount > 0) {
1737 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1738 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1739 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1740 # / at the end means don't show full path
1741 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1742 $nodotdot = substr( $nodotdot, 0, -1 );
1743 if( '' === $text ) {
1747 $nodotdot = trim( $nodotdot );
1748 if( $nodotdot != '' ) {
1749 $ret .= '/' . $nodotdot;
1756 wfProfileOut( $fname );
1761 * Used by doBlockLevels()
1764 /* private */ function closeParagraph() {
1766 if ( '' != $this->mLastSection
) {
1767 $result = '</' . $this->mLastSection
. ">\n";
1769 $this->mInPre
= false;
1770 $this->mLastSection
= '';
1773 # getCommon() returns the length of the longest common substring
1774 # of both arguments, starting at the beginning of both.
1776 /* private */ function getCommon( $st1, $st2 ) {
1777 $fl = strlen( $st1 );
1778 $shorter = strlen( $st2 );
1779 if ( $fl < $shorter ) { $shorter = $fl; }
1781 for ( $i = 0; $i < $shorter; ++
$i ) {
1782 if ( $st1{$i} != $st2{$i} ) { break; }
1786 # These next three functions open, continue, and close the list
1787 # element appropriate to the prefix character passed into them.
1789 /* private */ function openList( $char ) {
1790 $result = $this->closeParagraph();
1792 if ( '*' == $char ) { $result .= '<ul><li>'; }
1793 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1794 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1795 else if ( ';' == $char ) {
1796 $result .= '<dl><dt>';
1797 $this->mDTopen
= true;
1799 else { $result = '<!-- ERR 1 -->'; }
1804 /* private */ function nextItem( $char ) {
1805 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1806 else if ( ':' == $char ||
';' == $char ) {
1808 if ( $this->mDTopen
) { $close = '</dt>'; }
1809 if ( ';' == $char ) {
1810 $this->mDTopen
= true;
1811 return $close . '<dt>';
1813 $this->mDTopen
= false;
1814 return $close . '<dd>';
1817 return '<!-- ERR 2 -->';
1820 /* private */ function closeList( $char ) {
1821 if ( '*' == $char ) { $text = '</li></ul>'; }
1822 else if ( '#' == $char ) { $text = '</li></ol>'; }
1823 else if ( ':' == $char ) {
1824 if ( $this->mDTopen
) {
1825 $this->mDTopen
= false;
1826 $text = '</dt></dl>';
1828 $text = '</dd></dl>';
1831 else { return '<!-- ERR 3 -->'; }
1837 * Make lists from lines starting with ':', '*', '#', etc.
1840 * @return string the lists rendered as HTML
1842 function doBlockLevels( $text, $linestart ) {
1843 $fname = 'Parser::doBlockLevels';
1844 wfProfileIn( $fname );
1846 # Parsing through the text line by line. The main thing
1847 # happening here is handling of block-level elements p, pre,
1848 # and making lists from lines starting with * # : etc.
1850 $textLines = explode( "\n", $text );
1852 $lastPrefix = $output = '';
1853 $this->mDTopen
= $inBlockElem = false;
1855 $paragraphStack = false;
1857 if ( !$linestart ) {
1858 $output .= array_shift( $textLines );
1860 foreach ( $textLines as $oLine ) {
1861 $lastPrefixLength = strlen( $lastPrefix );
1862 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1863 $preOpenMatch = preg_match('/<pre/i', $oLine );
1864 if ( !$this->mInPre
) {
1865 # Multiple prefixes may abut each other for nested lists.
1866 $prefixLength = strspn( $oLine, '*#:;' );
1867 $pref = substr( $oLine, 0, $prefixLength );
1870 $pref2 = str_replace( ';', ':', $pref );
1871 $t = substr( $oLine, $prefixLength );
1872 $this->mInPre
= !empty($preOpenMatch);
1874 # Don't interpret any other prefixes in preformatted text
1876 $pref = $pref2 = '';
1881 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1882 # Same as the last item, so no need to deal with nesting or opening stuff
1883 $output .= $this->nextItem( substr( $pref, -1 ) );
1884 $paragraphStack = false;
1886 if ( substr( $pref, -1 ) == ';') {
1887 # The one nasty exception: definition lists work like this:
1888 # ; title : definition text
1889 # So we check for : in the remainder text to split up the
1890 # title and definition, without b0rking links.
1892 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1894 $output .= $term . $this->nextItem( ':' );
1897 } elseif( $prefixLength ||
$lastPrefixLength ) {
1898 # Either open or close a level...
1899 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1900 $paragraphStack = false;
1902 while( $commonPrefixLength < $lastPrefixLength ) {
1903 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1904 --$lastPrefixLength;
1906 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1907 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1909 while ( $prefixLength > $commonPrefixLength ) {
1910 $char = substr( $pref, $commonPrefixLength, 1 );
1911 $output .= $this->openList( $char );
1913 if ( ';' == $char ) {
1914 # FIXME: This is dupe of code above
1915 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1917 $output .= $term . $this->nextItem( ':' );
1920 ++
$commonPrefixLength;
1922 $lastPrefix = $pref2;
1924 if( 0 == $prefixLength ) {
1925 wfProfileIn( "$fname-paragraph" );
1926 # No prefix (not in list)--go to paragraph mode
1927 // XXX: use a stack for nestable elements like span, table and div
1928 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1929 $closematch = preg_match(
1930 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1931 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1932 if ( $openmatch or $closematch ) {
1933 $paragraphStack = false;
1934 $output .= $this->closeParagraph();
1935 if ( $preOpenMatch and !$preCloseMatch ) {
1936 $this->mInPre
= true;
1938 if ( $closematch ) {
1939 $inBlockElem = false;
1941 $inBlockElem = true;
1943 } else if ( !$inBlockElem && !$this->mInPre
) {
1944 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1946 if ($this->mLastSection
!= 'pre') {
1947 $paragraphStack = false;
1948 $output .= $this->closeParagraph().'<pre>';
1949 $this->mLastSection
= 'pre';
1951 $t = substr( $t, 1 );
1954 if ( '' == trim($t) ) {
1955 if ( $paragraphStack ) {
1956 $output .= $paragraphStack.'<br />';
1957 $paragraphStack = false;
1958 $this->mLastSection
= 'p';
1960 if ($this->mLastSection
!= 'p' ) {
1961 $output .= $this->closeParagraph();
1962 $this->mLastSection
= '';
1963 $paragraphStack = '<p>';
1965 $paragraphStack = '</p><p>';
1969 if ( $paragraphStack ) {
1970 $output .= $paragraphStack;
1971 $paragraphStack = false;
1972 $this->mLastSection
= 'p';
1973 } else if ($this->mLastSection
!= 'p') {
1974 $output .= $this->closeParagraph().'<p>';
1975 $this->mLastSection
= 'p';
1980 wfProfileOut( "$fname-paragraph" );
1982 // somewhere above we forget to get out of pre block (bug 785)
1983 if($preCloseMatch && $this->mInPre
) {
1984 $this->mInPre
= false;
1986 if ($paragraphStack === false) {
1990 while ( $prefixLength ) {
1991 $output .= $this->closeList( $pref2{$prefixLength-1} );
1994 if ( '' != $this->mLastSection
) {
1995 $output .= '</' . $this->mLastSection
. '>';
1996 $this->mLastSection
= '';
1999 wfProfileOut( $fname );
2004 * Split up a string on ':', ignoring any occurences inside
2005 * <a>..</a> or <span>...</span>
2006 * @param string $str the string to split
2007 * @param string &$before set to everything before the ':'
2008 * @param string &$after set to everything after the ':'
2009 * return string the position of the ':', or false if none found
2011 function findColonNoLinks($str, &$before, &$after) {
2012 # I wonder if we should make this count all tags, not just <a>
2013 # and <span>. That would prevent us from matching a ':' that
2014 # comes in the middle of italics other such formatting....
2016 $fname = 'Parser::findColonNoLinks';
2017 wfProfileIn( $fname );
2020 $colon = strpos($str, ':', $pos);
2022 if ($colon !== false) {
2023 $before = substr($str, 0, $colon);
2024 $after = substr($str, $colon +
1);
2026 # Skip any ':' within <a> or <span> pairs
2027 $a = substr_count($before, '<a');
2028 $s = substr_count($before, '<span');
2029 $ca = substr_count($before, '</a>');
2030 $cs = substr_count($before, '</span>');
2032 if ($a <= $ca and $s <= $cs) {
2033 # Tags are balanced before ':'; ok
2038 } while ($colon !== false);
2039 wfProfileOut( $fname );
2044 * Return value of a magic variable (like PAGENAME)
2048 function getVariableValue( $index ) {
2049 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2052 * Some of these require message or data lookups and can be
2053 * expensive to check many times.
2055 static $varCache = array();
2056 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2057 if ( isset( $varCache[$index] ) )
2058 return $varCache[$index];
2061 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2064 case MAG_CURRENTMONTH
:
2065 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2066 case MAG_CURRENTMONTHNAME
:
2067 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2068 case MAG_CURRENTMONTHNAMEGEN
:
2069 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2070 case MAG_CURRENTMONTHABBREV
:
2071 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2072 case MAG_CURRENTDAY
:
2073 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2074 case MAG_CURRENTDAY2
:
2075 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2077 return $this->mTitle
->getText();
2079 return $this->mTitle
->getPartialURL();
2080 case MAG_FULLPAGENAME
:
2081 return $this->mTitle
->getPrefixedText();
2082 case MAG_FULLPAGENAMEE
:
2083 return $this->mTitle
->getPrefixedURL();
2084 case MAG_SUBPAGENAME
:
2085 return $this->mTitle
->getSubpageText();
2086 case MAG_SUBPAGENAMEE
:
2087 return $this->mTitle
->getSubpageUrlForm();
2088 case MAG_REVISIONID
:
2089 return $this->mRevisionId
;
2091 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2092 case MAG_NAMESPACEE
:
2093 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2094 case MAG_CURRENTDAYNAME
:
2095 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2096 case MAG_CURRENTYEAR
:
2097 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2098 case MAG_CURRENTTIME
:
2099 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2100 case MAG_CURRENTWEEK
:
2101 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2102 // int to remove the padding
2103 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2104 case MAG_CURRENTDOW
:
2105 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2106 case MAG_NUMBEROFARTICLES
:
2107 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2108 case MAG_NUMBEROFFILES
:
2109 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2114 case MAG_SERVERNAME
:
2115 return $wgServerName;
2116 case MAG_SCRIPTPATH
:
2117 return $wgScriptPath;
2120 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2128 * initialise the magic variables (like CURRENTMONTHNAME)
2132 function initialiseVariables() {
2133 $fname = 'Parser::initialiseVariables';
2134 wfProfileIn( $fname );
2135 global $wgVariableIDs;
2136 $this->mVariables
= array();
2137 foreach ( $wgVariableIDs as $id ) {
2138 $mw =& MagicWord
::get( $id );
2139 $mw->addToArray( $this->mVariables
, $id );
2141 wfProfileOut( $fname );
2145 * parse any parentheses in format ((title|part|part))
2146 * and call callbacks to get a replacement text for any found piece
2148 * @param string $text The text to parse
2149 * @param array $callbacks rules in form:
2150 * '{' => array( # opening parentheses
2151 * 'end' => '}', # closing parentheses
2152 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2153 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2158 function replace_callback ($text, $callbacks) {
2159 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2160 $lastOpeningBrace = -1; # last not closed parentheses
2162 for ($i = 0; $i < strlen($text); $i++
) {
2163 # check for any opening brace
2166 foreach ($callbacks as $key => $value) {
2167 $pos = strpos ($text, $key, $i);
2168 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2174 if ($lastOpeningBrace >= 0) {
2175 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2177 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2182 $pos = strpos ($text, '|', $i);
2184 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2195 # found openning brace, lets add it to parentheses stack
2196 if (null != $rule) {
2197 $piece = array('brace' => $text[$i],
2198 'braceEnd' => $rule['end'],
2203 # count openning brace characters
2204 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2209 $piece['startAt'] = $i+
1;
2210 $piece['partStart'] = $i+
1;
2212 # we need to add to stack only if openning brace count is enough for any given rule
2213 foreach ($rule['cb'] as $cnt => $fn) {
2214 if ($piece['count'] >= $cnt) {
2215 $lastOpeningBrace ++
;
2216 $openingBraceStack[$lastOpeningBrace] = $piece;
2223 else if ($lastOpeningBrace >= 0) {
2224 # first check if it is a closing brace
2225 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2226 # lets check if it is enough characters for closing brace
2228 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2231 # if there are more closing parentheses than opening ones, we parse less
2232 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2233 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2235 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2237 $matchingCallback = null;
2238 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2239 if ($count >= $cnt && $matchingCount < $cnt) {
2240 $matchingCount = $cnt;
2241 $matchingCallback = $fn;
2245 if ($matchingCount == 0) {
2250 # lets set a title or last part (if '|' was found)
2251 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2252 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2254 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2256 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2257 $pieceEnd = $i +
$matchingCount;
2259 if( is_callable( $matchingCallback ) ) {
2261 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2262 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2263 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2264 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2266 # finally we can call a user callback and replace piece of text
2267 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2268 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2269 $i = $pieceStart +
strlen($replaceWith) - 1;
2272 # null value for callback means that parentheses should be parsed, but not replaced
2273 $i +
= $matchingCount - 1;
2276 # reset last openning parentheses, but keep it in case there are unused characters
2277 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2278 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2279 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2282 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2283 $openingBraceStack[$lastOpeningBrace--] = null;
2285 if ($matchingCount < $piece['count']) {
2286 $piece['count'] -= $matchingCount;
2287 $piece['startAt'] -= $matchingCount;
2288 $piece['partStart'] = $piece['startAt'];
2289 # do we still qualify for any callback with remaining count?
2290 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2291 if ($piece['count'] >= $cnt) {
2292 $lastOpeningBrace ++
;
2293 $openingBraceStack[$lastOpeningBrace] = $piece;
2301 # lets set a title if it is a first separator, or next part otherwise
2302 if ($text[$i] == '|') {
2303 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2304 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2305 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2308 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2310 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2319 * Replace magic variables, templates, and template arguments
2320 * with the appropriate text. Templates are substituted recursively,
2321 * taking care to avoid infinite loops.
2323 * Note that the substitution depends on value of $mOutputType:
2324 * OT_WIKI: only {{subst:}} templates
2325 * OT_MSG: only magic variables
2326 * OT_HTML: all templates and magic variables
2328 * @param string $tex The text to transform
2329 * @param array $args Key-value pairs representing template parameters to substitute
2330 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2333 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2334 # Prevent too big inclusions
2335 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2339 $fname = 'Parser::replaceVariables';
2340 wfProfileIn( $fname );
2342 # This function is called recursively. To keep track of arguments we need a stack:
2343 array_push( $this->mArgStack
, $args );
2345 $braceCallbacks = array();
2347 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2349 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2350 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2352 $callbacks = array();
2353 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2354 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2355 $text = $this->replace_callback ($text, $callbacks);
2357 array_pop( $this->mArgStack
);
2359 wfProfileOut( $fname );
2364 * Replace magic variables
2367 function variableSubstitution( $matches ) {
2368 $fname = 'Parser::variableSubstitution';
2369 $varname = $matches[1];
2370 wfProfileIn( $fname );
2371 if ( !$this->mVariables
) {
2372 $this->initialiseVariables();
2375 if ( $this->mOutputType
== OT_WIKI
) {
2376 # Do only magic variables prefixed by SUBST
2377 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2378 if (!$mwSubst->matchStartAndRemove( $varname ))
2380 # Note that if we don't substitute the variable below,
2381 # we don't remove the {{subst:}} magic word, in case
2382 # it is a template rather than a magic variable.
2384 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2385 $id = $this->mVariables
[$varname];
2386 $text = $this->getVariableValue( $id );
2387 $this->mOutput
->mContainsOldMagic
= true;
2389 $text = $matches[0];
2391 wfProfileOut( $fname );
2395 # Split template arguments
2396 function getTemplateArgs( $argsString ) {
2397 if ( $argsString === '' ) {
2401 $args = explode( '|', substr( $argsString, 1 ) );
2403 # If any of the arguments contains a '[[' but no ']]', it needs to be
2404 # merged with the next arg because the '|' character between belongs
2405 # to the link syntax and not the template parameter syntax.
2406 $argc = count($args);
2408 for ( $i = 0; $i < $argc-1; $i++
) {
2409 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2410 $args[$i] .= '|'.$args[$i+
1];
2411 array_splice($args, $i+
1, 1);
2421 * Return the text of a template, after recursively
2422 * replacing any variables or templates within the template.
2424 * @param array $piece The parts of the template
2425 * $piece['text']: matched text
2426 * $piece['title']: the title, i.e. the part before the |
2427 * $piece['parts']: the parameter array
2428 * @return string the text of the template
2431 function braceSubstitution( $piece ) {
2433 $fname = 'Parser::braceSubstitution';
2434 wfProfileIn( $fname );
2437 $found = false; # $text has been filled
2438 $nowiki = false; # wiki markup in $text should be escaped
2439 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2440 $noargs = false; # Don't replace triple-brace arguments in $text
2441 $replaceHeadings = false; # Make the edit section links go to the template not the article
2442 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2443 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2445 # Title object, where $text came from
2450 # $part1 is the bit before the first |, and must contain only title characters
2451 # $args is a list of arguments, starting from index 0, not including $part1
2453 $part1 = $piece['title'];
2454 # If the third subpattern matched anything, it will start with |
2456 if (null == $piece['parts']) {
2457 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2458 if ($replaceWith != $piece['text']) {
2459 $text = $replaceWith;
2466 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2467 $argc = count( $args );
2471 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2472 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2473 # One of two possibilities is true:
2474 # 1) Found SUBST but not in the PST phase
2475 # 2) Didn't find SUBST and in the PST phase
2476 # In either case, return without further processing
2477 $text = $piece['text'];
2484 # MSG, MSGNW, INT and RAW
2487 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2488 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2491 # Remove obsolete MSG:
2492 $mwMsg =& MagicWord
::get( MAG_MSG
);
2493 $mwMsg->matchStartAndRemove( $part1 );
2497 $mwRaw =& MagicWord
::get( MAG_RAW
);
2498 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2499 $forceRawInterwiki = true;
2502 # Check if it is an internal message
2503 $mwInt =& MagicWord
::get( MAG_INT
);
2504 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2505 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2506 $text = $linestart . wfMsgReal( $part1, $args, true );
2514 # Check for NS: (namespace expansion)
2515 $mwNs = MagicWord
::get( MAG_NS
);
2516 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2517 if ( intval( $part1 ) ||
$part1 == "0" ) {
2518 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2521 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2522 if ( !is_null( $index ) ) {
2523 $text = $linestart . $wgContLang->getNsText( $index );
2530 # LCFIRST, UCFIRST, LC and UC
2532 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2533 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2534 $lc =& MagicWord
::get( MAG_LC
);
2535 $uc =& MagicWord
::get( MAG_UC
);
2536 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2537 $text = $linestart . $wgContLang->lcfirst( $part1 );
2539 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2540 $text = $linestart . $wgContLang->ucfirst( $part1 );
2542 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2543 $text = $linestart . $wgContLang->lc( $part1 );
2545 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2546 $text = $linestart . $wgContLang->uc( $part1 );
2551 # LOCALURL and FULLURL
2553 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2554 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2555 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2556 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2559 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2560 $func = 'getLocalURL';
2561 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2562 $func = 'escapeLocalURL';
2563 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2564 $func = 'getFullURL';
2565 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2566 $func = 'escapeFullURL';
2571 if ( $func !== false ) {
2572 $title = Title
::newFromText( $part1 );
2573 if ( !is_null( $title ) ) {
2575 $text = $linestart . $title->$func( $args[0] );
2577 $text = $linestart . $title->$func();
2585 if ( !$found && $argc == 1 ) {
2586 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2587 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2588 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2594 if ( !$found && $argc >= 2 ) {
2595 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2596 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2597 if ($argc==2) {$args[2]=$args[1];}
2598 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2603 # Template table test
2605 # Did we encounter this template already? If yes, it is in the cache
2606 # and we need to check for loops.
2607 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2610 # Infinite loop test
2611 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2615 $text = $linestart .
2616 '{{' . $part1 . '}}' .
2617 '<!-- WARNING: template loop detected -->';
2618 wfDebug( "$fname: template loop broken at '$part1'\n" );
2620 # set $text to cached message.
2621 $text = $linestart . $this->mTemplates
[$piece['title']];
2625 # Load from database
2626 $lastPathLevel = $this->mTemplatePath
;
2629 # declaring $subpage directly in the function call
2630 # does not work correctly with references and breaks
2631 # {{/subpage}}-style inclusions
2633 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2634 if ($subpage !== '') {
2635 $ns = $this->mTitle
->getNamespace();
2637 $title = Title
::newFromText( $part1, $ns );
2639 if ( !is_null( $title ) ) {
2640 if ( !$title->isExternal() ) {
2641 # Check for excessive inclusion
2642 $dbk = $title->getPrefixedDBkey();
2643 if ( $this->incrementIncludeCount( $dbk ) ) {
2644 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2645 # Capture special page output
2646 $text = SpecialPage
::capturePath( $title );
2647 if ( is_string( $text ) ) {
2652 $this->disableCache();
2655 $articleContent = $this->fetchTemplate( $title );
2656 if ( $articleContent !== false ) {
2658 $text = $articleContent;
2659 $replaceHeadings = true;
2664 # If the title is valid but undisplayable, make a link to it
2665 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2666 $text = '[['.$title->getPrefixedText().']]';
2669 } elseif ( $title->isTrans() ) {
2670 // Interwiki transclusion
2671 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2672 $text = $this->interwikiTransclude( $title, 'render' );
2676 $text = $this->interwikiTransclude( $title, 'raw' );
2677 $replaceHeadings = true;
2682 # Template cache array insertion
2683 # Use the original $piece['title'] not the mangled $part1, so that
2684 # modifiers such as RAW: produce separate cache entries
2686 $this->mTemplates
[$piece['title']] = $text;
2687 $text = $linestart . $text;
2692 # Recursive parsing, escaping and link table handling
2693 # Only for HTML output
2694 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2695 $text = wfEscapeWikiText( $text );
2696 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2698 # Clean up argument array
2699 $assocArgs = array();
2701 foreach( $args as $arg ) {
2702 $eqpos = strpos( $arg, '=' );
2703 if ( $eqpos === false ) {
2704 $assocArgs[$index++
] = $arg;
2706 $name = trim( substr( $arg, 0, $eqpos ) );
2707 $value = trim( substr( $arg, $eqpos+
1 ) );
2708 if ( $value === false ) {
2711 if ( $name !== false ) {
2712 $assocArgs[$name] = $value;
2717 # Add a new element to the templace recursion path
2718 $this->mTemplatePath
[$part1] = 1;
2722 # If there are any <onlyinclude> tags, only include them
2723 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2724 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2726 foreach ($m[1] as $piece)
2729 # Remove <noinclude> sections and <includeonly> tags
2730 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2731 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2733 if( $this->mOutputType
== OT_HTML
) {
2734 # Strip <nowiki>, <pre>, etc.
2735 $text = $this->strip( $text, $this->mStripState
);
2736 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2738 $text = $this->replaceVariables( $text, $assocArgs );
2740 # If the template begins with a table or block-level
2741 # element, it should be treated as beginning a new line.
2742 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2743 $text = "\n" . $text;
2745 } elseif ( !$noargs ) {
2746 # $noparse and !$noargs
2747 # Just replace the arguments, not any double-brace items
2748 # This is used for rendered interwiki transclusion
2749 $text = $this->replaceVariables( $text, $assocArgs, true );
2752 # Prune lower levels off the recursion check path
2753 $this->mTemplatePath
= $lastPathLevel;
2756 wfProfileOut( $fname );
2757 return $piece['text'];
2760 # Replace raw HTML by a placeholder
2761 # Add a blank line preceding, to prevent it from mucking up
2762 # immediately preceding headings
2763 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2765 # replace ==section headers==
2766 # XXX this needs to go away once we have a better parser.
2767 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2768 if( !is_null( $title ) )
2769 $encodedname = base64_encode($title->getPrefixedDBkey());
2771 $encodedname = base64_encode("");
2772 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2773 PREG_SPLIT_DELIM_CAPTURE
);
2776 for( $i = 0; $i < count($m); $i +
= 2 ) {
2778 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2780 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2784 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2785 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2786 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2794 # Prune lower levels off the recursion check path
2795 $this->mTemplatePath
= $lastPathLevel;
2798 wfProfileOut( $fname );
2799 return $piece['text'];
2801 wfProfileOut( $fname );
2807 * Fetch the unparsed text of a template and register a reference to it.
2809 function fetchTemplate( $title ) {
2811 // Loop to fetch the article, with up to 1 redirect
2812 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2813 $rev = Revision
::newFromTitle( $title );
2814 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2818 $text = $rev->getText();
2819 if ( $text === false ) {
2823 $title = Title
::newFromRedirect( $text );
2829 * Transclude an interwiki link.
2831 function interwikiTransclude( $title, $action ) {
2832 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2834 if (!$wgEnableScaryTranscluding)
2835 return wfMsg('scarytranscludedisabled');
2837 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2838 // But we'll handle it generally anyway
2839 if ( $title->getNamespace() ) {
2840 // Use the canonical namespace, which should work anywhere
2841 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2843 $articleName = $title->getDBkey();
2846 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2847 $url .= "?action=$action";
2848 if (strlen($url) > 255)
2849 return wfMsg('scarytranscludetoolong');
2850 return $this->fetchScaryTemplateMaybeFromCache($url);
2853 function fetchScaryTemplateMaybeFromCache($url) {
2854 global $wgTranscludeCacheExpiry;
2855 $dbr =& wfGetDB(DB_SLAVE
);
2856 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2857 array('tc_url' => $url));
2859 $time = $obj->tc_time
;
2860 $text = $obj->tc_contents
;
2861 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2866 $text = wfGetHTTP($url);
2868 return wfMsg('scarytranscludefailed', $url);
2870 $dbw =& wfGetDB(DB_MASTER
);
2871 $dbw->replace('transcache', array('tc_url'), array(
2873 'tc_time' => time(),
2874 'tc_contents' => $text));
2880 * Triple brace replacement -- used for template arguments
2883 function argSubstitution( $matches ) {
2884 $arg = trim( $matches['title'] );
2885 $text = $matches['text'];
2886 $inputArgs = end( $this->mArgStack
);
2888 if ( array_key_exists( $arg, $inputArgs ) ) {
2889 $text = $inputArgs[$arg];
2890 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2891 $text = $matches['parts'][0];
2898 * Returns true if the function is allowed to include this entity
2901 function incrementIncludeCount( $dbk ) {
2902 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2903 $this->mIncludeCount
[$dbk] = 0;
2905 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2913 * This function accomplishes several tasks:
2914 * 1) Auto-number headings if that option is enabled
2915 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2916 * 3) Add a Table of contents on the top for users who have enabled the option
2917 * 4) Auto-anchor headings
2919 * It loops through all headlines, collects the necessary data, then splits up the
2920 * string and re-inserts the newly formatted headlines.
2922 * @param string $text
2923 * @param boolean $isMain
2926 function formatHeadings( $text, $isMain=true ) {
2927 global $wgMaxTocLevel, $wgContLang;
2929 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2931 $forceTocHere = false;
2932 if( !$this->mTitle
->userCanEdit() ) {
2935 $showEditLink = $this->mOptions
->getEditSection();
2938 # Inhibit editsection links if requested in the page
2939 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2940 if( $esw->matchAndRemove( $text ) ) {
2943 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2945 $mw =& MagicWord
::get( MAG_NOTOC
);
2946 if( $mw->matchAndRemove( $text ) ) {
2950 # Get all headlines for numbering them and adding funky stuff like [edit]
2951 # links - this is for later, but we need the number of headlines right now
2952 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2954 # if there are fewer than 4 headlines in the article, do not show TOC
2955 if( $numMatches < 4 ) {
2959 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2960 # override above conditions and always show TOC at that place
2962 $mw =& MagicWord
::get( MAG_TOC
);
2963 if($mw->match( $text ) ) {
2965 $forceTocHere = true;
2967 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2968 # override above conditions and always show TOC above first header
2969 $mw =& MagicWord
::get( MAG_FORCETOC
);
2970 if ($mw->matchAndRemove( $text ) ) {
2975 # Never ever show TOC if no headers
2976 if( $numMatches < 1 ) {
2980 # We need this to perform operations on the HTML
2981 $sk =& $this->mOptions
->getSkin();
2985 $sectionCount = 0; # headlineCount excluding template sections
2987 # Ugh .. the TOC should have neat indentation levels which can be
2988 # passed to the skin functions. These are determined here
2992 $sublevelCount = array();
2993 $levelCount = array();
3000 foreach( $matches[3] as $headline ) {
3002 $templatetitle = '';
3003 $templatesection = 0;
3006 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3008 $templatetitle = base64_decode($mat[1]);
3009 $templatesection = 1 +
(int)base64_decode($mat[2]);
3010 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3014 $prevlevel = $level;
3015 $prevtoclevel = $toclevel;
3017 $level = $matches[1][$headlineCount];
3019 if( $doNumberHeadings ||
$doShowToc ) {
3021 if ( $level > $prevlevel ) {
3022 # Increase TOC level
3024 $sublevelCount[$toclevel] = 0;
3025 $toc .= $sk->tocIndent();
3027 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3028 # Decrease TOC level, find level to jump to
3030 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3031 # Can only go down to level 1
3034 for ($i = $toclevel; $i > 0; $i--) {
3035 if ( $levelCount[$i] == $level ) {
3036 # Found last matching level
3040 elseif ( $levelCount[$i] < $level ) {
3041 # Found first matching level below current level
3048 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3051 # No change in level, end TOC line
3052 $toc .= $sk->tocLineEnd();
3055 $levelCount[$toclevel] = $level;
3057 # count number of headlines for each level
3058 @$sublevelCount[$toclevel]++
;
3060 for( $i = 1; $i <= $toclevel; $i++
) {
3061 if( !empty( $sublevelCount[$i] ) ) {
3065 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3071 # The canonized header is a version of the header text safe to use for links
3072 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3073 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3074 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3076 # Remove link placeholders by the link text.
3077 # <!--LINK number-->
3079 # link text with suffix
3080 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3081 "\$this->mLinkHolders['texts'][\$1]",
3082 $canonized_headline );
3083 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3084 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3085 $canonized_headline );
3088 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3089 $tocline = trim( $canonized_headline );
3090 # Save headline for section edit hint before it's escaped
3091 $headline_hint = trim( $canonized_headline );
3092 $canonized_headline = Sanitizer
::escapeId( $tocline );
3093 $refers[$headlineCount] = $canonized_headline;
3095 # count how many in assoc. array so we can track dupes in anchors
3096 @$refers[$canonized_headline]++
;
3097 $refcount[$headlineCount]=$refers[$canonized_headline];
3099 # Don't number the heading if it is the only one (looks silly)
3100 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3101 # the two are different if the line contains a link
3102 $headline=$numbering . ' ' . $headline;
3105 # Create the anchor for linking from the TOC to the section
3106 $anchor = $canonized_headline;
3107 if($refcount[$headlineCount] > 1 ) {
3108 $anchor .= '_' . $refcount[$headlineCount];
3110 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3111 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3113 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3114 if ( empty( $head[$headlineCount] ) ) {
3115 $head[$headlineCount] = '';
3118 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3120 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3123 # give headline the correct <h#> tag
3124 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3132 $toc .= $sk->tocUnindent( $toclevel - 1 );
3133 $toc = $sk->tocList( $toc );
3136 # split up and insert constructed headlines
3138 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3141 foreach( $blocks as $block ) {
3142 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3143 # This is the [edit] link that appears for the top block of text when
3144 # section editing is enabled
3146 # Disabled because it broke block formatting
3147 # For example, a bullet point in the top line
3148 # $full .= $sk->editSectionLink(0);
3151 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3152 # Top anchor now in skin
3156 if( !empty( $head[$i] ) ) {
3162 $mw =& MagicWord
::get( MAG_TOC
);
3163 return $mw->replace( $toc, $full );
3170 * Return an HTML link for the "ISBN 123456" text
3173 function magicISBN( $text ) {
3174 $fname = 'Parser::magicISBN';
3175 wfProfileIn( $fname );
3177 $a = split( 'ISBN ', ' '.$text );
3178 if ( count ( $a ) < 2 ) {
3179 wfProfileOut( $fname );
3182 $text = substr( array_shift( $a ), 1);
3183 $valid = '0123456789-Xx';
3185 foreach ( $a as $x ) {
3186 # hack: don't replace inside thumbnail title/alt
3188 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3193 $isbn = $blank = '' ;
3194 while ( ' ' == $x{0} ) {
3196 $x = substr( $x, 1 );
3198 if ( $x == '' ) { # blank isbn
3199 $text .= "ISBN $blank";
3202 while ( strstr( $valid, $x{0} ) != false ) {
3204 $x = substr( $x, 1 );
3206 $num = str_replace( '-', '', $isbn );
3207 $num = str_replace( ' ', '', $num );
3208 $num = str_replace( 'x', 'X', $num );
3211 $text .= "ISBN $blank$x";
3213 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3214 $text .= '<a href="' .
3215 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3216 "\" class=\"internal\">ISBN $isbn</a>";
3220 wfProfileOut( $fname );
3225 * Return an HTML link for the "RFC 1234" text
3228 * @param string $text Text to be processed
3229 * @param string $keyword Magic keyword to use (default RFC)
3230 * @param string $urlmsg Interface message to use (default rfcurl)
3233 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3235 $valid = '0123456789';
3238 $a = split( $keyword, ' '.$text );
3239 if ( count ( $a ) < 2 ) {
3242 $text = substr( array_shift( $a ), 1);
3244 /* Check if keyword is preceed by [[.
3245 * This test is made here cause of the array_shift above
3246 * that prevent the test to be done in the foreach.
3248 if ( substr( $text, -2 ) == '[[' ) {
3252 foreach ( $a as $x ) {
3253 /* token might be empty if we have RFC RFC 1234 */
3259 # hack: don't replace inside thumbnail title/alt
3261 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3262 $text .= $keyword . $x;
3268 /** remove and save whitespaces in $blank */
3269 while ( $x{0} == ' ' ) {
3271 $x = substr( $x, 1 );
3274 /** remove and save the rfc number in $id */
3275 while ( strstr( $valid, $x{0} ) != false ) {
3277 $x = substr( $x, 1 );
3281 /* call back stripped spaces*/
3282 $text .= $keyword.$blank.$x;
3283 } elseif( $internal ) {
3285 $text .= $keyword.$id.$x;
3287 /* build the external link*/
3288 $url = wfMsg( $urlmsg, $id);
3289 $sk =& $this->mOptions
->getSkin();
3290 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3291 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3294 /* Check if the next RFC keyword is preceed by [[ */
3295 $internal = ( substr($x,-2) == '[[' );
3301 * Transform wiki markup when saving a page by doing \r\n -> \n
3302 * conversion, substitting signatures, {{subst:}} templates, etc.
3304 * @param string $text the text to transform
3305 * @param Title &$title the Title object for the current article
3306 * @param User &$user the User object describing the current user
3307 * @param ParserOptions $options parsing options
3308 * @param bool $clearState whether to clear the parser state first
3309 * @return string the altered wiki markup
3312 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3313 $this->mOptions
= $options;
3314 $this->mTitle
=& $title;
3315 $this->mOutputType
= OT_WIKI
;
3317 if ( $clearState ) {
3318 $this->clearState();
3321 $stripState = false;
3325 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3326 $text = $this->strip( $text, $stripState, true );
3327 $text = $this->pstPass2( $text, $user );
3328 $text = $this->unstrip( $text, $stripState );
3329 $text = $this->unstripNoWiki( $text, $stripState );
3334 * Pre-save transform helper function
3337 function pstPass2( $text, &$user ) {
3338 global $wgContLang, $wgLocaltimezone;
3340 /* Note: This is the timestamp saved as hardcoded wikitext to
3341 * the database, we use $wgContLang here in order to give
3342 * everyone the same signiture and use the default one rather
3343 * than the one selected in each users preferences.
3345 if ( isset( $wgLocaltimezone ) ) {
3346 $oldtz = getenv( 'TZ' );
3347 putenv( 'TZ='.$wgLocaltimezone );
3349 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3350 ' (' . date( 'T' ) . ')';
3351 if ( isset( $wgLocaltimezone ) ) {
3352 putenv( 'TZ='.$oldtz );
3355 # Variable replacement
3356 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3357 $text = $this->replaceVariables( $text );
3360 $sigText = $this->getUserSig( $user );
3361 $text = strtr( $text, array(
3363 '~~~~' => "$sigText $d",
3367 # Context links: [[|name]] and [[name (context)|]]
3369 global $wgLegalTitleChars;
3370 $tc = "[$wgLegalTitleChars]";
3371 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3373 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3374 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3376 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3377 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3378 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3379 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3381 $t = $this->mTitle
->getText();
3382 if ( preg_match( $conpat, $t, $m ) ) {
3385 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3386 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3387 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3389 if ( '' == $context ) {
3390 $text = preg_replace( $p2, '[[\\1]]', $text );
3392 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3395 # Trim trailing whitespace
3396 # MAG_END (__END__) tag allows for trailing
3397 # whitespace to be deliberately included
3398 $text = rtrim( $text );
3399 $mw =& MagicWord
::get( MAG_END
);
3400 $mw->matchAndRemove( $text );
3406 * Fetch the user's signature text, if any, and normalize to
3407 * validated, ready-to-insert wikitext.
3413 function getUserSig( &$user ) {
3414 $username = $user->getName();
3415 $nickname = $user->getOption( 'nickname' );
3416 $nickname = $nickname === '' ?
$username : $nickname;
3418 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3419 # Sig. might contain markup; validate this
3420 if( $this->validateSig( $nickname ) !== false ) {
3421 # Validated; clean up (if needed) and return it
3422 return( $this->cleanSig( $nickname ) );
3424 # Failed to validate; fall back to the default
3425 $nickname = $username;
3426 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3430 # If we're still here, make it a link to the user page
3431 $userpage = $user->getUserPage();
3432 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3436 * Check that the user's signature contains no bad XML
3438 * @param string $text
3439 * @return mixed An expanded string, or false if invalid.
3441 function validateSig( $text ) {
3442 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3446 * Clean up signature text
3448 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3449 * 2) Substitute all transclusions
3451 * @param string $text
3452 * @return string Signature text
3454 function cleanSig( $text ) {
3455 $substWord = MagicWord
::get( MAG_SUBST
);
3456 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3457 $substText = '{{' . $substWord->getSynonym( 0 );
3459 $text = preg_replace( $substRegex, $substText, $text );
3460 $text = preg_replace( '/~{3,5}/', '', $text );
3461 $text = $this->replaceVariables( $text );
3467 * Set up some variables which are usually set up in parse()
3468 * so that an external function can call some class members with confidence
3471 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3472 $this->mTitle
=& $title;
3473 $this->mOptions
= $options;
3474 $this->mOutputType
= $outputType;
3475 if ( $clearState ) {
3476 $this->clearState();
3481 * Transform a MediaWiki message by replacing magic variables.
3483 * @param string $text the text to transform
3484 * @param ParserOptions $options options
3485 * @return string the text with variables substituted
3488 function transformMsg( $text, $options ) {
3490 static $executing = false;
3492 $fname = "Parser::transformMsg";
3494 # Guard against infinite recursion
3500 wfProfileIn($fname);
3502 $this->mTitle
= $wgTitle;
3503 $this->mOptions
= $options;
3504 $this->mOutputType
= OT_MSG
;
3505 $this->clearState();
3506 $text = $this->replaceVariables( $text );
3509 wfProfileOut($fname);
3514 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3515 * The callback should have the following form:
3516 * function myParserHook( $text, $params, &$parser ) { ... }
3518 * Transform and return $text. Use $parser for any required context, e.g. use
3519 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3523 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3524 * @param mixed $callback The callback function (and object) to use for the tag
3526 * @return The old value of the mTagHooks array associated with the hook
3528 function setHook( $tag, $callback ) {
3529 $oldVal = @$this->mTagHooks
[$tag];
3530 $this->mTagHooks
[$tag] = $callback;
3536 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3537 * Placeholders created in Skin::makeLinkObj()
3538 * Returns an array of links found, indexed by PDBK:
3542 * $options is a bit field, RLH_FOR_UPDATE to select for update
3544 function replaceLinkHolders( &$text, $options = 0 ) {
3546 global $wgOutputReplace;
3548 $fname = 'Parser::replaceLinkHolders';
3549 wfProfileIn( $fname );
3553 $sk =& $this->mOptions
->getSkin();
3554 $linkCache =& LinkCache
::singleton();
3556 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3557 wfProfileIn( $fname.'-check' );
3558 $dbr =& wfGetDB( DB_SLAVE
);
3559 $page = $dbr->tableName( 'page' );
3560 $threshold = $wgUser->getOption('stubthreshold');
3563 asort( $this->mLinkHolders
['namespaces'] );
3567 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3569 $title = $this->mLinkHolders
['titles'][$key];
3571 # Skip invalid entries.
3572 # Result will be ugly, but prevents crash.
3573 if ( is_null( $title ) ) {
3576 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3578 # Check if it's a static known link, e.g. interwiki
3579 if ( $title->isAlwaysKnown() ) {
3580 $colours[$pdbk] = 1;
3581 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3582 $colours[$pdbk] = 1;
3583 $this->mOutput
->addLink( $title, $id );
3584 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3585 $colours[$pdbk] = 0;
3587 # Not in the link cache, add it to the query
3588 if ( !isset( $current ) ) {
3590 $query = "SELECT page_id, page_namespace, page_title";
3591 if ( $threshold > 0 ) {
3592 $query .= ', page_len, page_is_redirect';
3594 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3595 } elseif ( $current != $ns ) {
3597 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3602 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3607 if ( $options & RLH_FOR_UPDATE
) {
3608 $query .= ' FOR UPDATE';
3611 $res = $dbr->query( $query, $fname );
3613 # Fetch data and form into an associative array
3614 # non-existent = broken
3617 while ( $s = $dbr->fetchObject($res) ) {
3618 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3619 $pdbk = $title->getPrefixedDBkey();
3620 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3621 $this->mOutput
->addLink( $title, $s->page_id
);
3623 if ( $threshold > 0 ) {
3624 $size = $s->page_len
;
3625 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3626 $colours[$pdbk] = 1;
3628 $colours[$pdbk] = 2;
3631 $colours[$pdbk] = 1;
3635 wfProfileOut( $fname.'-check' );
3637 # Construct search and replace arrays
3638 wfProfileIn( $fname.'-construct' );
3639 $wgOutputReplace = array();
3640 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3641 $pdbk = $pdbks[$key];
3642 $searchkey = "<!--LINK $key-->";
3643 $title = $this->mLinkHolders
['titles'][$key];
3644 if ( empty( $colours[$pdbk] ) ) {
3645 $linkCache->addBadLinkObj( $title );
3646 $colours[$pdbk] = 0;
3647 $this->mOutput
->addLink( $title, 0 );
3648 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3649 $this->mLinkHolders
['texts'][$key],
3650 $this->mLinkHolders
['queries'][$key] );
3651 } elseif ( $colours[$pdbk] == 1 ) {
3652 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3653 $this->mLinkHolders
['texts'][$key],
3654 $this->mLinkHolders
['queries'][$key] );
3655 } elseif ( $colours[$pdbk] == 2 ) {
3656 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3657 $this->mLinkHolders
['texts'][$key],
3658 $this->mLinkHolders
['queries'][$key] );
3661 wfProfileOut( $fname.'-construct' );
3664 wfProfileIn( $fname.'-replace' );
3666 $text = preg_replace_callback(
3667 '/(<!--LINK .*?-->)/',
3668 "wfOutputReplaceMatches",
3671 wfProfileOut( $fname.'-replace' );
3674 # Now process interwiki link holders
3675 # This is quite a bit simpler than internal links
3676 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3677 wfProfileIn( $fname.'-interwiki' );
3678 # Make interwiki link HTML
3679 $wgOutputReplace = array();
3680 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3681 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3682 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3685 $text = preg_replace_callback(
3686 '/<!--IWLINK (.*?)-->/',
3687 "wfOutputReplaceMatches",
3689 wfProfileOut( $fname.'-interwiki' );
3692 wfProfileOut( $fname );
3697 * Replace <!--LINK--> link placeholders with plain text of links
3698 * (not HTML-formatted).
3699 * @param string $text
3702 function replaceLinkHoldersText( $text ) {
3703 $fname = 'Parser::replaceLinkHoldersText';
3704 wfProfileIn( $fname );
3706 $text = preg_replace_callback(
3707 '/<!--(LINK|IWLINK) (.*?)-->/',
3708 array( &$this, 'replaceLinkHoldersTextCallback' ),
3711 wfProfileOut( $fname );
3716 * @param array $matches
3720 function replaceLinkHoldersTextCallback( $matches ) {
3721 $type = $matches[1];
3723 if( $type == 'LINK' ) {
3724 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3725 return $this->mLinkHolders
['texts'][$key];
3727 } elseif( $type == 'IWLINK' ) {
3728 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3729 return $this->mInterwikiLinkHolders
['texts'][$key];
3736 * Renders an image gallery from a text with one line per image.
3737 * text labels may be given by using |-style alternative text. E.g.
3738 * Image:one.jpg|The number "1"
3739 * Image:tree.jpg|A tree
3740 * given as text will return the HTML of a gallery with two images,
3741 * labeled 'The number "1"' and
3744 function renderImageGallery( $text ) {
3746 $parserOptions = new ParserOptions
;
3747 $localParser = new Parser();
3749 $ig = new ImageGallery();
3750 $ig->setShowBytes( false );
3751 $ig->setShowFilename( false );
3752 $lines = explode( "\n", $text );
3754 foreach ( $lines as $line ) {
3755 # match lines like these:
3756 # Image:someimage.jpg|This is some image
3757 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3759 if ( count( $matches ) == 0 ) {
3762 $nt =& Title
::newFromText( $matches[1] );
3763 if( is_null( $nt ) ) {
3764 # Bogus title. Ignore these so we don't bomb out later.
3767 if ( isset( $matches[3] ) ) {
3768 $label = $matches[3];
3773 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3774 $html = $pout->getText();
3776 $ig->add( new Image( $nt ), $html );
3777 $this->mOutput
->addImage( $nt->getDBkey() );
3779 return $ig->toHTML();
3783 * Parse image options text and use it to make an image
3785 function makeImage( &$nt, $options ) {
3786 global $wgUseImageResize;
3790 # Check if the options text is of the form "options|alt text"
3792 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3793 # * left no resizing, just left align. label is used for alt= only
3794 # * right same, but right aligned
3795 # * none same, but not aligned
3796 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3797 # * center center the image
3798 # * framed Keep original image size, no magnify-button.
3800 $part = explode( '|', $options);
3802 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3803 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3804 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3805 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3806 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3807 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3808 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3809 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3812 $width = $height = $framed = $thumb = false;
3813 $manual_thumb = '' ;
3815 foreach( $part as $key => $val ) {
3816 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3818 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3819 # use manually specified thumbnail
3821 $manual_thumb = $match;
3822 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3823 # remember to set an alignment, don't render immediately
3825 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3826 # remember to set an alignment, don't render immediately
3828 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3829 # remember to set an alignment, don't render immediately
3831 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3832 # remember to set an alignment, don't render immediately
3834 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3835 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3836 # $match is the image width in pixels
3837 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3838 $width = intval( $m[1] );
3839 $height = intval( $m[2] );
3841 $width = intval($match);
3843 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3849 # Strip bad stuff out of the alt text
3850 $alt = $this->replaceLinkHoldersText( $caption );
3852 # make sure there are no placeholders in thumbnail attributes
3853 # that are later expanded to html- so expand them now and
3855 $alt = $this->unstrip($alt, $this->mStripState
);
3856 $alt = Sanitizer
::stripAllTags( $alt );
3858 # Linker does the rest
3859 $sk =& $this->mOptions
->getSkin();
3860 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3864 * Set a flag in the output object indicating that the content is dynamic and
3865 * shouldn't be cached.
3867 function disableCache() {
3868 $this->mOutput
->mCacheTime
= -1;
3872 * Callback from the Sanitizer for expanding items found in HTML attribute
3873 * values, so they can be safely tested and escaped.
3874 * @param string $text
3875 * @param array $args
3879 function attributeStripCallback( &$text, $args ) {
3880 $text = $this->replaceVariables( $text, $args );
3881 $text = $this->unstripForHTML( $text );
3885 function unstripForHTML( $text ) {
3886 $text = $this->unstrip( $text, $this->mStripState
);
3887 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3895 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3896 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3897 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3903 function getTags() { return array_keys( $this->mTagHooks
); }
3909 * @package MediaWiki
3913 var $mText, # The output text
3914 $mLanguageLinks, # List of the full text of language links, in the order they appear
3915 $mCategories, # Map of category names to sort keys
3916 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3917 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
3918 $mVersion, # Compatibility check
3919 $mTitleText, # title text of the chosen language variant
3920 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3921 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3922 $mImages, # DB keys of the images used, in the array key only
3923 $mExternalLinks; # External link URLs, in the key only
3925 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3926 $containsOldMagic = false, $titletext = '' )
3928 $this->mText
= $text;
3929 $this->mLanguageLinks
= $languageLinks;
3930 $this->mCategories
= $categoryLinks;
3931 $this->mContainsOldMagic
= $containsOldMagic;
3932 $this->mCacheTime
= '';
3933 $this->mVersion
= MW_PARSER_VERSION
;
3934 $this->mTitleText
= $titletext;
3935 $this->mLinks
= array();
3936 $this->mTemplates
= array();
3937 $this->mImages
= array();
3938 $this->mExternalLinks
= array();
3941 function getText() { return $this->mText
; }
3942 function getLanguageLinks() { return $this->mLanguageLinks
; }
3943 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3944 function &getCategories() { return $this->mCategories
; }
3945 function getCacheTime() { return $this->mCacheTime
; }
3946 function getTitleText() { return $this->mTitleText
; }
3947 function &getLinks() { return $this->mLinks
; }
3948 function &getTemplates() { return $this->mTemplates
; }
3949 function &getImages() { return $this->mImages
; }
3950 function &getExternalLinks() { return $this->mExternalLinks
; }
3952 function containsOldMagic() { return $this->mContainsOldMagic
; }
3953 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3954 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3955 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3956 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3957 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3958 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3960 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3961 function addImage( $name ) { $this->mImages
[$name] = 1; }
3962 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3963 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3965 function addLink( $title, $id ) {
3966 $ns = $title->getNamespace();
3967 $dbk = $title->getDBkey();
3968 if ( !isset( $this->mLinks
[$ns] ) ) {
3969 $this->mLinks
[$ns] = array();
3971 $this->mLinks
[$ns][$dbk] = $id;
3974 function addTemplate( $title, $id ) {
3975 $ns = $title->getNamespace();
3976 $dbk = $title->getDBkey();
3977 if ( !isset( $this->mTemplates
[$ns] ) ) {
3978 $this->mTemplates
[$ns] = array();
3980 $this->mTemplates
[$ns][$dbk] = $id;
3987 function merge( $other ) {
3988 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3989 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3990 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3994 * Return true if this cached output object predates the global or
3995 * per-article cache invalidation timestamps, or if it comes from
3996 * an incompatible older version.
3998 * @param string $touched the affected article's last touched timestamp
4002 function expired( $touched ) {
4003 global $wgCacheEpoch;
4004 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4005 $this->getCacheTime() < $touched ||
4006 $this->getCacheTime() <= $wgCacheEpoch ||
4007 !isset( $this->mVersion
) ||
4008 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4013 * Set options of the Parser
4015 * @package MediaWiki
4019 # All variables are private
4020 var $mUseTeX; # Use texvc to expand <math> tags
4021 var $mUseDynamicDates; # Use DateFormatter to format dates
4022 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4023 var $mAllowExternalImages; # Allow external images inline
4024 var $mAllowExternalImagesFrom; # If not, any exception?
4025 var $mSkin; # Reference to the preferred skin
4026 var $mDateFormat; # Date format index
4027 var $mEditSection; # Create "edit section" links
4028 var $mNumberHeadings; # Automatically number headings
4029 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4030 var $mTidy; # Ask for tidy cleanup
4032 function getUseTeX() { return $this->mUseTeX
; }
4033 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4034 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4035 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4036 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4037 function &getSkin() { return $this->mSkin
; }
4038 function getDateFormat() { return $this->mDateFormat
; }
4039 function getEditSection() { return $this->mEditSection
; }
4040 function getNumberHeadings() { return $this->mNumberHeadings
; }
4041 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4042 function getTidy() { return $this->mTidy
; }
4044 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4045 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4046 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4047 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4048 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4049 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4050 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4051 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4052 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4053 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4054 function setSkin( &$x ) { $this->mSkin
=& $x; }
4056 function ParserOptions() {
4058 $this->initialiseFromUser( $wgUser );
4062 * Get parser options
4065 function newFromUser( &$user ) {
4066 $popts = new ParserOptions
;
4067 $popts->initialiseFromUser( $user );
4071 /** Get user options */
4072 function initialiseFromUser( &$userInput ) {
4073 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4074 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4075 $fname = 'ParserOptions::initialiseFromUser';
4076 wfProfileIn( $fname );
4077 if ( !$userInput ) {
4079 $user->setLoaded( true );
4081 $user =& $userInput;
4084 $this->mUseTeX
= $wgUseTeX;
4085 $this->mUseDynamicDates
= $wgUseDynamicDates;
4086 $this->mInterwikiMagic
= $wgInterwikiMagic;
4087 $this->mAllowExternalImages
= $wgAllowExternalImages;
4088 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4089 wfProfileIn( $fname.'-skin' );
4090 $this->mSkin
=& $user->getSkin();
4091 wfProfileOut( $fname.'-skin' );
4092 $this->mDateFormat
= $user->getOption( 'date' );
4093 $this->mEditSection
= true;
4094 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4095 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4096 $this->mTidy
= false;
4097 wfProfileOut( $fname );
4102 * Callback function used by Parser::replaceLinkHolders()
4103 * to substitute link placeholders.
4105 function &wfOutputReplaceMatches( $matches ) {
4106 global $wgOutputReplace;
4107 return $wgOutputReplace[$matches[1]];
4111 * Return the total number of articles
4113 function wfNumberOfArticles() {
4114 global $wgNumberOfArticles;
4117 return $wgNumberOfArticles;
4121 * Return the number of files
4123 function wfNumberOfFiles() {
4124 $fname = 'wfNumberOfFiles';
4126 wfProfileIn( $fname );
4127 $dbr =& wfGetDB( DB_SLAVE
);
4128 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4129 wfProfileOut( $fname );
4135 * Get various statistics from the database
4138 function wfLoadSiteStats() {
4139 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4140 $fname = 'wfLoadSiteStats';
4142 if ( -1 != $wgNumberOfArticles ) return;
4143 $dbr =& wfGetDB( DB_SLAVE
);
4144 $s = $dbr->selectRow( 'site_stats',
4145 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4146 array( 'ss_row_id' => 1 ), $fname
4149 if ( $s === false ) {
4152 $wgTotalViews = $s->ss_total_views
;
4153 $wgTotalEdits = $s->ss_total_edits
;
4154 $wgNumberOfArticles = $s->ss_good_articles
;
4160 * Basically replacing " > and < with HTML entities ( ", >, <)
4162 * @param string $in Text that might contain HTML tags
4163 * @return string Escaped string
4165 function wfEscapeHTMLTagsOnly( $in ) {
4167 array( '"', '>', '<' ),
4168 array( '"', '>', '<' ),