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 ) ;
787 // Split up multiple cells on the same line.
788 // FIXME: This can result in improper nesting of tags processed
789 // by earlier parser steps, but should avoid splitting up eg
790 // attribute values containing literal "||".
791 $after = wfExplodeMarkup( '||', $after );
795 # Loop through each table cell
796 foreach ( $after AS $theline )
801 $tra = array_pop ( $ltr ) ;
802 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
803 array_push ( $tr , true ) ;
804 array_push ( $ltr , '' ) ;
805 array_pop ( $has_opened_tr );
806 array_push ( $has_opened_tr , true ) ;
809 $l = array_pop ( $ltd ) ;
810 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
811 if ( $fc == '|' ) $l = 'td' ;
812 else if ( $fc == '!' ) $l = 'th' ;
813 else if ( $fc == '+' ) $l = 'caption' ;
815 array_push ( $ltd , $l ) ;
818 $y = explode ( '|' , $theline , 2 ) ;
819 # Note that a '|' inside an invalid link should not
820 # be mistaken as delimiting cell parameters
821 if ( strpos( $y[0], '[[' ) !== false ) {
822 $y = array ($theline);
824 if ( count ( $y ) == 1 )
825 $y = "{$z}<{$l}>{$y[0]}" ;
827 $attributes = $this->unstripForHTML( $y[0] );
828 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
831 array_push ( $td , true ) ;
836 # Closing open td, tr && table
837 while ( count ( $td ) > 0 )
839 $l = array_pop ( $ltd ) ;
840 if ( array_pop ( $td ) ) $t[] = '</td>' ;
841 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
842 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
846 $t = implode ( "\n" , $t ) ;
847 # special case: don't return empty table
848 if($t == "<table>\n<tr><td></td></tr>\n</table>")
850 wfProfileOut( $fname );
855 * Helper function for parse() that transforms wiki markup into
856 * HTML. Only called for $mOutputType == OT_HTML.
860 function internalParse( $text ) {
863 $fname = 'Parser::internalParse';
864 wfProfileIn( $fname );
866 # Remove <noinclude> tags and <includeonly> sections
867 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
868 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
869 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
871 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
872 $text = $this->replaceVariables( $text, $args );
874 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
876 $text = $this->doHeadings( $text );
877 if($this->mOptions
->getUseDynamicDates()) {
878 $df =& DateFormatter
::getInstance();
879 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
881 $text = $this->doAllQuotes( $text );
882 $text = $this->replaceInternalLinks( $text );
883 $text = $this->replaceExternalLinks( $text );
885 # replaceInternalLinks may sometimes leave behind
886 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
887 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
889 $text = $this->doMagicLinks( $text );
890 $text = $this->doTableStuff( $text );
891 $text = $this->formatHeadings( $text, $isMain );
893 wfProfileOut( $fname );
898 * Replace special strings like "ISBN xxx" and "RFC xxx" with
899 * magic external links.
903 function &doMagicLinks( &$text ) {
904 $text = $this->magicISBN( $text );
905 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
906 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
911 * Parse headers and return html
915 function doHeadings( $text ) {
916 $fname = 'Parser::doHeadings';
917 wfProfileIn( $fname );
918 for ( $i = 6; $i >= 1; --$i ) {
919 $h = str_repeat( '=', $i );
920 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
921 "<h{$i}>\\1</h{$i}>\\2", $text );
923 wfProfileOut( $fname );
928 * Replace single quotes with HTML markup
930 * @return string the altered text
932 function doAllQuotes( $text ) {
933 $fname = 'Parser::doAllQuotes';
934 wfProfileIn( $fname );
936 $lines = explode( "\n", $text );
937 foreach ( $lines as $line ) {
938 $outtext .= $this->doQuotes ( $line ) . "\n";
940 $outtext = substr($outtext, 0,-1);
941 wfProfileOut( $fname );
946 * Helper function for doAllQuotes()
949 function doQuotes( $text ) {
950 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
951 if ( count( $arr ) == 1 )
955 # First, do some preliminary work. This may shift some apostrophes from
956 # being mark-up to being text. It also counts the number of occurrences
957 # of bold and italics mark-ups.
961 foreach ( $arr as $r )
963 if ( ( $i %
2 ) == 1 )
965 # If there are ever four apostrophes, assume the first is supposed to
966 # be text, and the remaining three constitute mark-up for bold text.
967 if ( strlen( $arr[$i] ) == 4 )
972 # If there are more than 5 apostrophes in a row, assume they're all
973 # text except for the last 5.
974 else if ( strlen( $arr[$i] ) > 5 )
976 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
979 # Count the number of occurrences of bold and italics mark-ups.
980 # We are not counting sequences of five apostrophes.
981 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
982 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
983 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
988 # If there is an odd number of both bold and italics, it is likely
989 # that one of the bold ones was meant to be an apostrophe followed
990 # by italics. Which one we cannot know for certain, but it is more
991 # likely to be one that has a single-letter word before it.
992 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
995 $firstsingleletterword = -1;
996 $firstmultiletterword = -1;
998 foreach ( $arr as $r )
1000 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1002 $x1 = substr ($arr[$i-1], -1);
1003 $x2 = substr ($arr[$i-1], -2, 1);
1005 if ($firstspace == -1) $firstspace = $i;
1006 } else if ($x2 == ' ') {
1007 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1009 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1015 # If there is a single-letter word, use it!
1016 if ($firstsingleletterword > -1)
1018 $arr [ $firstsingleletterword ] = "''";
1019 $arr [ $firstsingleletterword-1 ] .= "'";
1021 # If not, but there's a multi-letter word, use that one.
1022 else if ($firstmultiletterword > -1)
1024 $arr [ $firstmultiletterword ] = "''";
1025 $arr [ $firstmultiletterword-1 ] .= "'";
1027 # ... otherwise use the first one that has neither.
1028 # (notice that it is possible for all three to be -1 if, for example,
1029 # there is only one pentuple-apostrophe in the line)
1030 else if ($firstspace > -1)
1032 $arr [ $firstspace ] = "''";
1033 $arr [ $firstspace-1 ] .= "'";
1037 # Now let's actually convert our apostrophic mush to HTML!
1042 foreach ($arr as $r)
1046 if ($state == 'both')
1053 if (strlen ($r) == 2)
1056 { $output .= '</i>'; $state = ''; }
1057 else if ($state == 'bi')
1058 { $output .= '</i>'; $state = 'b'; }
1059 else if ($state == 'ib')
1060 { $output .= '</b></i><b>'; $state = 'b'; }
1061 else if ($state == 'both')
1062 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1063 else # $state can be 'b' or ''
1064 { $output .= '<i>'; $state .= 'i'; }
1066 else if (strlen ($r) == 3)
1069 { $output .= '</b>'; $state = ''; }
1070 else if ($state == 'bi')
1071 { $output .= '</i></b><i>'; $state = 'i'; }
1072 else if ($state == 'ib')
1073 { $output .= '</b>'; $state = 'i'; }
1074 else if ($state == 'both')
1075 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1076 else # $state can be 'i' or ''
1077 { $output .= '<b>'; $state .= 'b'; }
1079 else if (strlen ($r) == 5)
1082 { $output .= '</b><i>'; $state = 'i'; }
1083 else if ($state == 'i')
1084 { $output .= '</i><b>'; $state = 'b'; }
1085 else if ($state == 'bi')
1086 { $output .= '</i></b>'; $state = ''; }
1087 else if ($state == 'ib')
1088 { $output .= '</b></i>'; $state = ''; }
1089 else if ($state == 'both')
1090 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1091 else # ($state == '')
1092 { $buffer = ''; $state = 'both'; }
1097 # Now close all remaining tags. Notice that the order is important.
1098 if ($state == 'b' ||
$state == 'ib')
1100 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1104 if ($state == 'both')
1105 $output .= '<b><i>'.$buffer.'</i></b>';
1111 * Replace external links
1113 * Note: this is all very hackish and the order of execution matters a lot.
1114 * Make sure to run maintenance/parserTests.php if you change this code.
1118 function replaceExternalLinks( $text ) {
1120 $fname = 'Parser::replaceExternalLinks';
1121 wfProfileIn( $fname );
1123 $sk =& $this->mOptions
->getSkin();
1125 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1127 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1130 while ( $i<count( $bits ) ) {
1132 $protocol = $bits[$i++
];
1133 $text = $bits[$i++
];
1134 $trail = $bits[$i++
];
1136 # The characters '<' and '>' (which were escaped by
1137 # removeHTMLtags()) should not be included in
1138 # URLs, per RFC 2396.
1139 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1140 $text = substr($url, $m2[0][1]) . ' ' . $text;
1141 $url = substr($url, 0, $m2[0][1]);
1144 # If the link text is an image URL, replace it with an <img> tag
1145 # This happened by accident in the original parser, but some people used it extensively
1146 $img = $this->maybeMakeExternalImage( $text );
1147 if ( $img !== false ) {
1153 # Set linktype for CSS - if URL==text, link is essentially free
1154 $linktype = ($text == $url) ?
'free' : 'text';
1156 # No link text, e.g. [http://domain.tld/some.link]
1157 if ( $text == '' ) {
1158 # Autonumber if allowed
1159 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1160 $text = '[' . ++
$this->mAutonumber
. ']';
1161 $linktype = 'autonumber';
1163 # Otherwise just use the URL
1164 $text = htmlspecialchars( $url );
1168 # Have link text, e.g. [http://domain.tld/some.link text]s
1170 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1173 $text = $wgContLang->markNoConversion($text);
1175 # Replace & from obsolete syntax with &.
1176 # All HTML entities will be escaped by makeExternalLink()
1177 $url = str_replace( '&', '&', $url );
1179 # Process the trail (i.e. everything after this link up until start of the next link),
1180 # replacing any non-bracketed links
1181 $trail = $this->replaceFreeExternalLinks( $trail );
1183 # Use the encoded URL
1184 # This means that users can paste URLs directly into the text
1185 # Funny characters like ö aren't valid in URLs anyway
1186 # This was changed in August 2004
1187 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1189 # Register link in the output object.
1190 # Replace unnecessary URL escape codes with the referenced character
1191 # This prevents spammers from hiding links from the filters
1192 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1193 $this->mOutput
->addExternalLink( $pasteurized );
1196 wfProfileOut( $fname );
1201 * Replace anything that looks like a URL with a link
1204 function replaceFreeExternalLinks( $text ) {
1206 $fname = 'Parser::replaceFreeExternalLinks';
1207 wfProfileIn( $fname );
1209 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1210 $s = array_shift( $bits );
1213 $sk =& $this->mOptions
->getSkin();
1215 while ( $i < count( $bits ) ){
1216 $protocol = $bits[$i++
];
1217 $remainder = $bits[$i++
];
1219 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1220 # Found some characters after the protocol that look promising
1221 $url = $protocol . $m[1];
1224 # special case: handle urls as url args:
1225 # http://www.example.com/foo?=http://www.example.com/bar
1226 if(strlen($trail) == 0 &&
1228 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1229 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1232 $url .= $bits[$i] . $bits[$i +
1]; # protocol, url as arg to previous link
1237 # The characters '<' and '>' (which were escaped by
1238 # removeHTMLtags()) should not be included in
1239 # URLs, per RFC 2396.
1240 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1241 $trail = substr($url, $m2[0][1]) . $trail;
1242 $url = substr($url, 0, $m2[0][1]);
1245 # Move trailing punctuation to $trail
1247 # If there is no left bracket, then consider right brackets fair game too
1248 if ( strpos( $url, '(' ) === false ) {
1252 $numSepChars = strspn( strrev( $url ), $sep );
1253 if ( $numSepChars ) {
1254 $trail = substr( $url, -$numSepChars ) . $trail;
1255 $url = substr( $url, 0, -$numSepChars );
1258 # Replace & from obsolete syntax with &.
1259 # All HTML entities will be escaped by makeExternalLink()
1260 # or maybeMakeExternalImage()
1261 $url = str_replace( '&', '&', $url );
1263 # Is this an external image?
1264 $text = $this->maybeMakeExternalImage( $url );
1265 if ( $text === false ) {
1266 # Not an image, make a link
1267 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1268 # Register it in the output object...
1269 # Replace unnecessary URL escape codes with their equivalent characters
1270 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1271 $this->mOutput
->addExternalLink( $pasteurized );
1273 $s .= $text . $trail;
1275 $s .= $protocol . $remainder;
1278 wfProfileOut( $fname );
1283 * Replace unusual URL escape codes with their equivalent characters
1287 * @fixme This can merge genuinely required bits in the path or query string,
1288 * breaking legit URLs. A proper fix would treat the various parts of
1289 * the URL differently; as a workaround, just use the output for
1290 * statistical records, not for actual linking/output.
1292 function replaceUnusualEscapes( $url ) {
1293 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1294 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1298 * Callback function used in replaceUnusualEscapes().
1299 * Replaces unusual URL escape codes with their equivalent character
1303 function replaceUnusualEscapesCallback( $matches ) {
1304 $char = urldecode( $matches[0] );
1305 $ord = ord( $char );
1306 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1307 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1308 // No, shouldn't be escaped
1311 // Yes, leave it escaped
1317 * make an image if it's allowed, either through the global
1318 * option or through the exception
1321 function maybeMakeExternalImage( $url ) {
1322 $sk =& $this->mOptions
->getSkin();
1323 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1324 $imagesexception = !empty($imagesfrom);
1326 if ( $this->mOptions
->getAllowExternalImages()
1327 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1328 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1330 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1337 * Process [[ ]] wikilinks
1341 function replaceInternalLinks( $s ) {
1343 static $fname = 'Parser::replaceInternalLinks' ;
1345 wfProfileIn( $fname );
1347 wfProfileIn( $fname.'-setup' );
1349 # the % is needed to support urlencoded titles as well
1350 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1352 $sk =& $this->mOptions
->getSkin();
1354 #split the entire text string on occurences of [[
1355 $a = explode( '[[', ' ' . $s );
1356 #get the first element (all text up to first [[), and remove the space we added
1357 $s = array_shift( $a );
1358 $s = substr( $s, 1 );
1360 # Match a link having the form [[namespace:link|alternate]]trail
1362 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1363 # Match cases where there is no "]]", which might still be images
1364 static $e1_img = FALSE;
1365 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1366 # Match the end of a line for a word that's not followed by whitespace,
1367 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1368 $e2 = wfMsgForContent( 'linkprefix' );
1370 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1372 if( is_null( $this->mTitle
) ) {
1373 wfDebugDieBacktrace( 'nooo' );
1375 $nottalk = !$this->mTitle
->isTalkPage();
1377 if ( $useLinkPrefixExtension ) {
1378 if ( preg_match( $e2, $s, $m ) ) {
1379 $first_prefix = $m[2];
1381 $first_prefix = false;
1387 $selflink = $this->mTitle
->getPrefixedText();
1388 wfProfileOut( $fname.'-setup' );
1390 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1391 $useSubpages = $this->areSubpagesAllowed();
1393 # Loop for each link
1394 for ($k = 0; isset( $a[$k] ); $k++
) {
1396 if ( $useLinkPrefixExtension ) {
1397 wfProfileIn( $fname.'-prefixhandling' );
1398 if ( preg_match( $e2, $s, $m ) ) {
1406 $prefix = $first_prefix;
1407 $first_prefix = false;
1409 wfProfileOut( $fname.'-prefixhandling' );
1412 $might_be_img = false;
1414 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1416 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1417 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1418 # the real problem is with the $e1 regex
1421 # Still some problems for cases where the ] is meant to be outside punctuation,
1422 # and no image is in sight. See bug 2095.
1425 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1426 strpos($text, '[') !== false
1429 $text .= ']'; # so that replaceExternalLinks($text) works later
1432 # fix up urlencoded title texts
1433 if(preg_match('/%/', $m[1] ))
1434 # Should anchors '#' also be rejected?
1435 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1437 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1438 $might_be_img = true;
1440 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1442 } else { # Invalid form; output directly
1443 $s .= $prefix . '[[' . $line ;
1447 # Don't allow internal links to pages containing
1448 # PROTO: where PROTO is a valid URL protocol; these
1449 # should be external links.
1450 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1451 $s .= $prefix . '[[' . $line ;
1455 # Make subpage if necessary
1456 if( $useSubpages ) {
1457 $link = $this->maybeDoSubpageLink( $m[1], $text );
1462 $noforce = (substr($m[1], 0, 1) != ':');
1464 # Strip off leading ':'
1465 $link = substr($link, 1);
1468 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1470 $s .= $prefix . '[[' . $line;
1474 #check other language variants of the link
1475 #if the article does not exist
1476 if( $checkVariantLink
1477 && $nt->getArticleID() == 0 ) {
1478 $wgContLang->findVariantLink($link, $nt);
1481 $ns = $nt->getNamespace();
1482 $iw = $nt->getInterWiki();
1484 if ($might_be_img) { # if this is actually an invalid link
1485 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1487 while (isset ($a[$k+
1]) ) {
1488 #look at the next 'line' to see if we can close it there
1489 $spliced = array_splice( $a, $k +
1, 1 );
1490 $next_line = array_shift( $spliced );
1491 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1492 # the first ]] closes the inner link, the second the image
1494 $text .= '[[' . $m[1];
1497 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1498 #if there's exactly one ]] that's fine, we'll keep looking
1499 $text .= '[[' . $m[0];
1501 #if $next_line is invalid too, we need look no further
1502 $text .= '[[' . $next_line;
1507 # we couldn't find the end of this imageLink, so output it raw
1508 #but don't ignore what might be perfectly normal links in the text we've examined
1509 $text = $this->replaceInternalLinks($text);
1510 $s .= $prefix . '[[' . $link . '|' . $text;
1511 # note: no $trail, because without an end, there *is* no trail
1514 } else { #it's not an image, so output it raw
1515 $s .= $prefix . '[[' . $link . '|' . $text;
1516 # note: no $trail, because without an end, there *is* no trail
1521 $wasblank = ( '' == $text );
1522 if( $wasblank ) $text = $link;
1525 # Link not escaped by : , create the various objects
1529 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1530 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1531 $s = rtrim($s . "\n");
1532 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1536 if ( $ns == NS_IMAGE
) {
1537 wfProfileIn( "$fname-image" );
1538 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1539 # recursively parse links inside the image caption
1540 # actually, this will parse them in any other parameters, too,
1541 # but it might be hard to fix that, and it doesn't matter ATM
1542 $text = $this->replaceExternalLinks($text);
1543 $text = $this->replaceInternalLinks($text);
1545 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1546 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1547 $this->mOutput
->addImage( $nt->getDBkey() );
1549 wfProfileOut( "$fname-image" );
1552 wfProfileOut( "$fname-image" );
1556 if ( $ns == NS_CATEGORY
) {
1557 wfProfileIn( "$fname-category" );
1558 $s = rtrim($s . "\n"); # bug 87
1561 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1562 $sortkey = $this->mTitle
->getText();
1564 $sortkey = $this->mTitle
->getPrefixedText();
1569 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1570 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1571 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1574 * Strip the whitespace Category links produce, see bug 87
1575 * @todo We might want to use trim($tmp, "\n") here.
1577 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1579 wfProfileOut( "$fname-category" );
1584 if( ( $nt->getPrefixedText() === $selflink ) &&
1585 ( $nt->getFragment() === '' ) ) {
1586 # Self-links are handled specially; generally de-link and change to bold.
1587 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1591 # Special and Media are pseudo-namespaces; no pages actually exist in them
1592 if( $ns == NS_MEDIA
) {
1593 $link = $sk->makeMediaLinkObj( $nt, $text );
1594 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1595 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1596 $this->mOutput
->addImage( $nt->getDBkey() );
1598 } elseif( $ns == NS_SPECIAL
) {
1599 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1601 } elseif( $ns == NS_IMAGE
) {
1602 $img = Image
::newFromTitle( $nt );
1603 if( $img->exists() ) {
1604 // Force a blue link if the file exists; may be a remote
1605 // upload on the shared repository, and we want to see its
1606 // auto-generated page.
1607 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1611 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1613 wfProfileOut( $fname );
1618 * Make a link placeholder. The text returned can be later resolved to a real link with
1619 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1620 * parsing of interwiki links, and secondly to allow all extistence checks and
1621 * article length checks (for stub links) to be bundled into a single query.
1624 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1625 if ( ! is_object($nt) ) {
1627 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1629 # Separate the link trail from the rest of the link
1630 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1632 if ( $nt->isExternal() ) {
1633 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1634 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1635 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1637 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1638 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1639 $this->mLinkHolders
['queries'][] = $query;
1640 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1641 $this->mLinkHolders
['titles'][] = $nt;
1643 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1650 * Render a forced-blue link inline; protect against double expansion of
1651 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1652 * Since this little disaster has to split off the trail text to avoid
1653 * breaking URLs in the following text without breaking trails on the
1654 * wiki links, it's been made into a horrible function.
1657 * @param string $text
1658 * @param string $query
1659 * @param string $trail
1660 * @param string $prefix
1661 * @return string HTML-wikitext mix oh yuck
1663 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1664 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1665 $sk =& $this->mOptions
->getSkin();
1666 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1667 return $this->armorLinks( $link ) . $trail;
1671 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1672 * going to go through further parsing steps before inline URL expansion.
1674 * In particular this is important when using action=render, which causes
1675 * full URLs to be included.
1677 * Oh man I hate our multi-layer parser!
1679 * @param string more-or-less HTML
1680 * @return string less-or-more HTML with NOPARSE bits
1682 function armorLinks( $text ) {
1683 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1684 "{$this->mUniqPrefix}NOPARSE$1", $text );
1688 * Return true if subpage links should be expanded on this page.
1691 function areSubpagesAllowed() {
1692 # Some namespaces don't allow subpages
1693 global $wgNamespacesWithSubpages;
1694 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1698 * Handle link to subpage if necessary
1699 * @param string $target the source of the link
1700 * @param string &$text the link text, modified as necessary
1701 * @return string the full name of the link
1704 function maybeDoSubpageLink($target, &$text) {
1707 # :Foobar -- override special treatment of prefix (images, language links)
1708 # /Foobar -- convert to CurrentPage/Foobar
1709 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1710 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1711 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1713 $fname = 'Parser::maybeDoSubpageLink';
1714 wfProfileIn( $fname );
1715 $ret = $target; # default return value is no change
1717 # Some namespaces don't allow subpages,
1718 # so only perform processing if subpages are allowed
1719 if( $this->areSubpagesAllowed() ) {
1720 # Look at the first character
1721 if( $target != '' && $target{0} == '/' ) {
1722 # / at end means we don't want the slash to be shown
1723 if( substr( $target, -1, 1 ) == '/' ) {
1724 $target = substr( $target, 1, -1 );
1727 $noslash = substr( $target, 1 );
1730 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1731 if( '' === $text ) {
1733 } # this might be changed for ugliness reasons
1735 # check for .. subpage backlinks
1737 $nodotdot = $target;
1738 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1740 $nodotdot = substr( $nodotdot, 3 );
1742 if($dotdotcount > 0) {
1743 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1744 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1745 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1746 # / at the end means don't show full path
1747 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1748 $nodotdot = substr( $nodotdot, 0, -1 );
1749 if( '' === $text ) {
1753 $nodotdot = trim( $nodotdot );
1754 if( $nodotdot != '' ) {
1755 $ret .= '/' . $nodotdot;
1762 wfProfileOut( $fname );
1767 * Used by doBlockLevels()
1770 /* private */ function closeParagraph() {
1772 if ( '' != $this->mLastSection
) {
1773 $result = '</' . $this->mLastSection
. ">\n";
1775 $this->mInPre
= false;
1776 $this->mLastSection
= '';
1779 # getCommon() returns the length of the longest common substring
1780 # of both arguments, starting at the beginning of both.
1782 /* private */ function getCommon( $st1, $st2 ) {
1783 $fl = strlen( $st1 );
1784 $shorter = strlen( $st2 );
1785 if ( $fl < $shorter ) { $shorter = $fl; }
1787 for ( $i = 0; $i < $shorter; ++
$i ) {
1788 if ( $st1{$i} != $st2{$i} ) { break; }
1792 # These next three functions open, continue, and close the list
1793 # element appropriate to the prefix character passed into them.
1795 /* private */ function openList( $char ) {
1796 $result = $this->closeParagraph();
1798 if ( '*' == $char ) { $result .= '<ul><li>'; }
1799 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1800 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1801 else if ( ';' == $char ) {
1802 $result .= '<dl><dt>';
1803 $this->mDTopen
= true;
1805 else { $result = '<!-- ERR 1 -->'; }
1810 /* private */ function nextItem( $char ) {
1811 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1812 else if ( ':' == $char ||
';' == $char ) {
1814 if ( $this->mDTopen
) { $close = '</dt>'; }
1815 if ( ';' == $char ) {
1816 $this->mDTopen
= true;
1817 return $close . '<dt>';
1819 $this->mDTopen
= false;
1820 return $close . '<dd>';
1823 return '<!-- ERR 2 -->';
1826 /* private */ function closeList( $char ) {
1827 if ( '*' == $char ) { $text = '</li></ul>'; }
1828 else if ( '#' == $char ) { $text = '</li></ol>'; }
1829 else if ( ':' == $char ) {
1830 if ( $this->mDTopen
) {
1831 $this->mDTopen
= false;
1832 $text = '</dt></dl>';
1834 $text = '</dd></dl>';
1837 else { return '<!-- ERR 3 -->'; }
1843 * Make lists from lines starting with ':', '*', '#', etc.
1846 * @return string the lists rendered as HTML
1848 function doBlockLevels( $text, $linestart ) {
1849 $fname = 'Parser::doBlockLevels';
1850 wfProfileIn( $fname );
1852 # Parsing through the text line by line. The main thing
1853 # happening here is handling of block-level elements p, pre,
1854 # and making lists from lines starting with * # : etc.
1856 $textLines = explode( "\n", $text );
1858 $lastPrefix = $output = '';
1859 $this->mDTopen
= $inBlockElem = false;
1861 $paragraphStack = false;
1863 if ( !$linestart ) {
1864 $output .= array_shift( $textLines );
1866 foreach ( $textLines as $oLine ) {
1867 $lastPrefixLength = strlen( $lastPrefix );
1868 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1869 $preOpenMatch = preg_match('/<pre/i', $oLine );
1870 if ( !$this->mInPre
) {
1871 # Multiple prefixes may abut each other for nested lists.
1872 $prefixLength = strspn( $oLine, '*#:;' );
1873 $pref = substr( $oLine, 0, $prefixLength );
1876 $pref2 = str_replace( ';', ':', $pref );
1877 $t = substr( $oLine, $prefixLength );
1878 $this->mInPre
= !empty($preOpenMatch);
1880 # Don't interpret any other prefixes in preformatted text
1882 $pref = $pref2 = '';
1887 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1888 # Same as the last item, so no need to deal with nesting or opening stuff
1889 $output .= $this->nextItem( substr( $pref, -1 ) );
1890 $paragraphStack = false;
1892 if ( substr( $pref, -1 ) == ';') {
1893 # The one nasty exception: definition lists work like this:
1894 # ; title : definition text
1895 # So we check for : in the remainder text to split up the
1896 # title and definition, without b0rking links.
1898 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1900 $output .= $term . $this->nextItem( ':' );
1903 } elseif( $prefixLength ||
$lastPrefixLength ) {
1904 # Either open or close a level...
1905 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1906 $paragraphStack = false;
1908 while( $commonPrefixLength < $lastPrefixLength ) {
1909 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1910 --$lastPrefixLength;
1912 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1913 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1915 while ( $prefixLength > $commonPrefixLength ) {
1916 $char = substr( $pref, $commonPrefixLength, 1 );
1917 $output .= $this->openList( $char );
1919 if ( ';' == $char ) {
1920 # FIXME: This is dupe of code above
1921 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1923 $output .= $term . $this->nextItem( ':' );
1926 ++
$commonPrefixLength;
1928 $lastPrefix = $pref2;
1930 if( 0 == $prefixLength ) {
1931 wfProfileIn( "$fname-paragraph" );
1932 # No prefix (not in list)--go to paragraph mode
1933 // XXX: use a stack for nestable elements like span, table and div
1934 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1935 $closematch = preg_match(
1936 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1937 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1938 if ( $openmatch or $closematch ) {
1939 $paragraphStack = false;
1940 $output .= $this->closeParagraph();
1941 if ( $preOpenMatch and !$preCloseMatch ) {
1942 $this->mInPre
= true;
1944 if ( $closematch ) {
1945 $inBlockElem = false;
1947 $inBlockElem = true;
1949 } else if ( !$inBlockElem && !$this->mInPre
) {
1950 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1952 if ($this->mLastSection
!= 'pre') {
1953 $paragraphStack = false;
1954 $output .= $this->closeParagraph().'<pre>';
1955 $this->mLastSection
= 'pre';
1957 $t = substr( $t, 1 );
1960 if ( '' == trim($t) ) {
1961 if ( $paragraphStack ) {
1962 $output .= $paragraphStack.'<br />';
1963 $paragraphStack = false;
1964 $this->mLastSection
= 'p';
1966 if ($this->mLastSection
!= 'p' ) {
1967 $output .= $this->closeParagraph();
1968 $this->mLastSection
= '';
1969 $paragraphStack = '<p>';
1971 $paragraphStack = '</p><p>';
1975 if ( $paragraphStack ) {
1976 $output .= $paragraphStack;
1977 $paragraphStack = false;
1978 $this->mLastSection
= 'p';
1979 } else if ($this->mLastSection
!= 'p') {
1980 $output .= $this->closeParagraph().'<p>';
1981 $this->mLastSection
= 'p';
1986 wfProfileOut( "$fname-paragraph" );
1988 // somewhere above we forget to get out of pre block (bug 785)
1989 if($preCloseMatch && $this->mInPre
) {
1990 $this->mInPre
= false;
1992 if ($paragraphStack === false) {
1996 while ( $prefixLength ) {
1997 $output .= $this->closeList( $pref2{$prefixLength-1} );
2000 if ( '' != $this->mLastSection
) {
2001 $output .= '</' . $this->mLastSection
. '>';
2002 $this->mLastSection
= '';
2005 wfProfileOut( $fname );
2010 * Split up a string on ':', ignoring any occurences inside
2011 * <a>..</a> or <span>...</span>
2012 * @param string $str the string to split
2013 * @param string &$before set to everything before the ':'
2014 * @param string &$after set to everything after the ':'
2015 * return string the position of the ':', or false if none found
2017 function findColonNoLinks($str, &$before, &$after) {
2018 # I wonder if we should make this count all tags, not just <a>
2019 # and <span>. That would prevent us from matching a ':' that
2020 # comes in the middle of italics other such formatting....
2022 $fname = 'Parser::findColonNoLinks';
2023 wfProfileIn( $fname );
2026 $colon = strpos($str, ':', $pos);
2028 if ($colon !== false) {
2029 $before = substr($str, 0, $colon);
2030 $after = substr($str, $colon +
1);
2032 # Skip any ':' within <a> or <span> pairs
2033 $a = substr_count($before, '<a');
2034 $s = substr_count($before, '<span');
2035 $ca = substr_count($before, '</a>');
2036 $cs = substr_count($before, '</span>');
2038 if ($a <= $ca and $s <= $cs) {
2039 # Tags are balanced before ':'; ok
2044 } while ($colon !== false);
2045 wfProfileOut( $fname );
2050 * Return value of a magic variable (like PAGENAME)
2054 function getVariableValue( $index ) {
2055 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2058 * Some of these require message or data lookups and can be
2059 * expensive to check many times.
2061 static $varCache = array();
2062 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2063 if ( isset( $varCache[$index] ) )
2064 return $varCache[$index];
2067 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2070 case MAG_CURRENTMONTH
:
2071 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2072 case MAG_CURRENTMONTHNAME
:
2073 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2074 case MAG_CURRENTMONTHNAMEGEN
:
2075 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2076 case MAG_CURRENTMONTHABBREV
:
2077 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2078 case MAG_CURRENTDAY
:
2079 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2080 case MAG_CURRENTDAY2
:
2081 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2083 return $this->mTitle
->getText();
2085 return $this->mTitle
->getPartialURL();
2086 case MAG_FULLPAGENAME
:
2087 return $this->mTitle
->getPrefixedText();
2088 case MAG_FULLPAGENAMEE
:
2089 return $this->mTitle
->getPrefixedURL();
2090 case MAG_SUBPAGENAME
:
2091 return $this->mTitle
->getSubpageText();
2092 case MAG_SUBPAGENAMEE
:
2093 return $this->mTitle
->getSubpageUrlForm();
2094 case MAG_REVISIONID
:
2095 return $this->mRevisionId
;
2097 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2098 case MAG_NAMESPACEE
:
2099 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2100 case MAG_CURRENTDAYNAME
:
2101 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2102 case MAG_CURRENTYEAR
:
2103 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2104 case MAG_CURRENTTIME
:
2105 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2106 case MAG_CURRENTWEEK
:
2107 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2108 // int to remove the padding
2109 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2110 case MAG_CURRENTDOW
:
2111 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2112 case MAG_NUMBEROFARTICLES
:
2113 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2114 case MAG_NUMBEROFFILES
:
2115 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2120 case MAG_SERVERNAME
:
2121 return $wgServerName;
2122 case MAG_SCRIPTPATH
:
2123 return $wgScriptPath;
2126 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2134 * initialise the magic variables (like CURRENTMONTHNAME)
2138 function initialiseVariables() {
2139 $fname = 'Parser::initialiseVariables';
2140 wfProfileIn( $fname );
2141 global $wgVariableIDs;
2142 $this->mVariables
= array();
2143 foreach ( $wgVariableIDs as $id ) {
2144 $mw =& MagicWord
::get( $id );
2145 $mw->addToArray( $this->mVariables
, $id );
2147 wfProfileOut( $fname );
2151 * parse any parentheses in format ((title|part|part))
2152 * and call callbacks to get a replacement text for any found piece
2154 * @param string $text The text to parse
2155 * @param array $callbacks rules in form:
2156 * '{' => array( # opening parentheses
2157 * 'end' => '}', # closing parentheses
2158 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2159 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2164 function replace_callback ($text, $callbacks) {
2165 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2166 $lastOpeningBrace = -1; # last not closed parentheses
2168 for ($i = 0; $i < strlen($text); $i++
) {
2169 # check for any opening brace
2172 foreach ($callbacks as $key => $value) {
2173 $pos = strpos ($text, $key, $i);
2174 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2180 if ($lastOpeningBrace >= 0) {
2181 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2183 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2188 $pos = strpos ($text, '|', $i);
2190 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2201 # found openning brace, lets add it to parentheses stack
2202 if (null != $rule) {
2203 $piece = array('brace' => $text[$i],
2204 'braceEnd' => $rule['end'],
2209 # count openning brace characters
2210 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2215 $piece['startAt'] = $i+
1;
2216 $piece['partStart'] = $i+
1;
2218 # we need to add to stack only if openning brace count is enough for any given rule
2219 foreach ($rule['cb'] as $cnt => $fn) {
2220 if ($piece['count'] >= $cnt) {
2221 $lastOpeningBrace ++
;
2222 $openingBraceStack[$lastOpeningBrace] = $piece;
2229 else if ($lastOpeningBrace >= 0) {
2230 # first check if it is a closing brace
2231 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2232 # lets check if it is enough characters for closing brace
2234 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2237 # if there are more closing parentheses than opening ones, we parse less
2238 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2239 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2241 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2243 $matchingCallback = null;
2244 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2245 if ($count >= $cnt && $matchingCount < $cnt) {
2246 $matchingCount = $cnt;
2247 $matchingCallback = $fn;
2251 if ($matchingCount == 0) {
2256 # lets set a title or last part (if '|' was found)
2257 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2258 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2260 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2262 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2263 $pieceEnd = $i +
$matchingCount;
2265 if( is_callable( $matchingCallback ) ) {
2267 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2268 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2269 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2270 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2272 # finally we can call a user callback and replace piece of text
2273 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2274 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2275 $i = $pieceStart +
strlen($replaceWith) - 1;
2278 # null value for callback means that parentheses should be parsed, but not replaced
2279 $i +
= $matchingCount - 1;
2282 # reset last openning parentheses, but keep it in case there are unused characters
2283 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2284 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2285 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2288 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2289 $openingBraceStack[$lastOpeningBrace--] = null;
2291 if ($matchingCount < $piece['count']) {
2292 $piece['count'] -= $matchingCount;
2293 $piece['startAt'] -= $matchingCount;
2294 $piece['partStart'] = $piece['startAt'];
2295 # do we still qualify for any callback with remaining count?
2296 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2297 if ($piece['count'] >= $cnt) {
2298 $lastOpeningBrace ++
;
2299 $openingBraceStack[$lastOpeningBrace] = $piece;
2307 # lets set a title if it is a first separator, or next part otherwise
2308 if ($text[$i] == '|') {
2309 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2310 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2311 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2314 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2316 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2325 * Replace magic variables, templates, and template arguments
2326 * with the appropriate text. Templates are substituted recursively,
2327 * taking care to avoid infinite loops.
2329 * Note that the substitution depends on value of $mOutputType:
2330 * OT_WIKI: only {{subst:}} templates
2331 * OT_MSG: only magic variables
2332 * OT_HTML: all templates and magic variables
2334 * @param string $tex The text to transform
2335 * @param array $args Key-value pairs representing template parameters to substitute
2336 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2339 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2340 # Prevent too big inclusions
2341 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2345 $fname = 'Parser::replaceVariables';
2346 wfProfileIn( $fname );
2348 # This function is called recursively. To keep track of arguments we need a stack:
2349 array_push( $this->mArgStack
, $args );
2351 $braceCallbacks = array();
2353 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2355 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2356 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2358 $callbacks = array();
2359 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2360 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2361 $text = $this->replace_callback ($text, $callbacks);
2363 array_pop( $this->mArgStack
);
2365 wfProfileOut( $fname );
2370 * Replace magic variables
2373 function variableSubstitution( $matches ) {
2374 $fname = 'Parser::variableSubstitution';
2375 $varname = $matches[1];
2376 wfProfileIn( $fname );
2377 if ( !$this->mVariables
) {
2378 $this->initialiseVariables();
2381 if ( $this->mOutputType
== OT_WIKI
) {
2382 # Do only magic variables prefixed by SUBST
2383 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2384 if (!$mwSubst->matchStartAndRemove( $varname ))
2386 # Note that if we don't substitute the variable below,
2387 # we don't remove the {{subst:}} magic word, in case
2388 # it is a template rather than a magic variable.
2390 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2391 $id = $this->mVariables
[$varname];
2392 $text = $this->getVariableValue( $id );
2393 $this->mOutput
->mContainsOldMagic
= true;
2395 $text = $matches[0];
2397 wfProfileOut( $fname );
2401 # Split template arguments
2402 function getTemplateArgs( $argsString ) {
2403 if ( $argsString === '' ) {
2407 $args = explode( '|', substr( $argsString, 1 ) );
2409 # If any of the arguments contains a '[[' but no ']]', it needs to be
2410 # merged with the next arg because the '|' character between belongs
2411 # to the link syntax and not the template parameter syntax.
2412 $argc = count($args);
2414 for ( $i = 0; $i < $argc-1; $i++
) {
2415 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2416 $args[$i] .= '|'.$args[$i+
1];
2417 array_splice($args, $i+
1, 1);
2427 * Return the text of a template, after recursively
2428 * replacing any variables or templates within the template.
2430 * @param array $piece The parts of the template
2431 * $piece['text']: matched text
2432 * $piece['title']: the title, i.e. the part before the |
2433 * $piece['parts']: the parameter array
2434 * @return string the text of the template
2437 function braceSubstitution( $piece ) {
2439 $fname = 'Parser::braceSubstitution';
2440 wfProfileIn( $fname );
2443 $found = false; # $text has been filled
2444 $nowiki = false; # wiki markup in $text should be escaped
2445 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2446 $noargs = false; # Don't replace triple-brace arguments in $text
2447 $replaceHeadings = false; # Make the edit section links go to the template not the article
2448 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2449 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2451 # Title object, where $text came from
2456 # $part1 is the bit before the first |, and must contain only title characters
2457 # $args is a list of arguments, starting from index 0, not including $part1
2459 $part1 = $piece['title'];
2460 # If the third subpattern matched anything, it will start with |
2462 if (null == $piece['parts']) {
2463 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2464 if ($replaceWith != $piece['text']) {
2465 $text = $replaceWith;
2472 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2473 $argc = count( $args );
2477 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2478 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2479 # One of two possibilities is true:
2480 # 1) Found SUBST but not in the PST phase
2481 # 2) Didn't find SUBST and in the PST phase
2482 # In either case, return without further processing
2483 $text = $piece['text'];
2490 # MSG, MSGNW, INT and RAW
2493 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2494 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2497 # Remove obsolete MSG:
2498 $mwMsg =& MagicWord
::get( MAG_MSG
);
2499 $mwMsg->matchStartAndRemove( $part1 );
2503 $mwRaw =& MagicWord
::get( MAG_RAW
);
2504 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2505 $forceRawInterwiki = true;
2508 # Check if it is an internal message
2509 $mwInt =& MagicWord
::get( MAG_INT
);
2510 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2511 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2512 $text = $linestart . wfMsgReal( $part1, $args, true );
2520 # Check for NS: (namespace expansion)
2521 $mwNs = MagicWord
::get( MAG_NS
);
2522 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2523 if ( intval( $part1 ) ||
$part1 == "0" ) {
2524 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2527 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2528 if ( !is_null( $index ) ) {
2529 $text = $linestart . $wgContLang->getNsText( $index );
2536 # LCFIRST, UCFIRST, LC and UC
2538 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2539 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2540 $lc =& MagicWord
::get( MAG_LC
);
2541 $uc =& MagicWord
::get( MAG_UC
);
2542 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2543 $text = $linestart . $wgContLang->lcfirst( $part1 );
2545 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2546 $text = $linestart . $wgContLang->ucfirst( $part1 );
2548 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2549 $text = $linestart . $wgContLang->lc( $part1 );
2551 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2552 $text = $linestart . $wgContLang->uc( $part1 );
2557 # LOCALURL and FULLURL
2559 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2560 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2561 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2562 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2565 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2566 $func = 'getLocalURL';
2567 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2568 $func = 'escapeLocalURL';
2569 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2570 $func = 'getFullURL';
2571 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2572 $func = 'escapeFullURL';
2577 if ( $func !== false ) {
2578 $title = Title
::newFromText( $part1 );
2579 if ( !is_null( $title ) ) {
2581 $text = $linestart . $title->$func( $args[0] );
2583 $text = $linestart . $title->$func();
2591 if ( !$found && $argc == 1 ) {
2592 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2593 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2594 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2600 if ( !$found && $argc >= 2 ) {
2601 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2602 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2603 if ($argc==2) {$args[2]=$args[1];}
2604 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2609 # Template table test
2611 # Did we encounter this template already? If yes, it is in the cache
2612 # and we need to check for loops.
2613 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2616 # Infinite loop test
2617 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2621 $text = $linestart .
2622 '{{' . $part1 . '}}' .
2623 '<!-- WARNING: template loop detected -->';
2624 wfDebug( "$fname: template loop broken at '$part1'\n" );
2626 # set $text to cached message.
2627 $text = $linestart . $this->mTemplates
[$piece['title']];
2631 # Load from database
2632 $lastPathLevel = $this->mTemplatePath
;
2635 # declaring $subpage directly in the function call
2636 # does not work correctly with references and breaks
2637 # {{/subpage}}-style inclusions
2639 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2640 if ($subpage !== '') {
2641 $ns = $this->mTitle
->getNamespace();
2643 $title = Title
::newFromText( $part1, $ns );
2645 if ( !is_null( $title ) ) {
2646 if ( !$title->isExternal() ) {
2647 # Check for excessive inclusion
2648 $dbk = $title->getPrefixedDBkey();
2649 if ( $this->incrementIncludeCount( $dbk ) ) {
2650 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2651 # Capture special page output
2652 $text = SpecialPage
::capturePath( $title );
2653 if ( is_string( $text ) ) {
2658 $this->disableCache();
2661 $articleContent = $this->fetchTemplate( $title );
2662 if ( $articleContent !== false ) {
2664 $text = $articleContent;
2665 $replaceHeadings = true;
2670 # If the title is valid but undisplayable, make a link to it
2671 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2672 $text = '[['.$title->getPrefixedText().']]';
2675 } elseif ( $title->isTrans() ) {
2676 // Interwiki transclusion
2677 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2678 $text = $this->interwikiTransclude( $title, 'render' );
2682 $text = $this->interwikiTransclude( $title, 'raw' );
2683 $replaceHeadings = true;
2688 # Template cache array insertion
2689 # Use the original $piece['title'] not the mangled $part1, so that
2690 # modifiers such as RAW: produce separate cache entries
2692 $this->mTemplates
[$piece['title']] = $text;
2693 $text = $linestart . $text;
2698 # Recursive parsing, escaping and link table handling
2699 # Only for HTML output
2700 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2701 $text = wfEscapeWikiText( $text );
2702 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2704 # Clean up argument array
2705 $assocArgs = array();
2707 foreach( $args as $arg ) {
2708 $eqpos = strpos( $arg, '=' );
2709 if ( $eqpos === false ) {
2710 $assocArgs[$index++
] = $arg;
2712 $name = trim( substr( $arg, 0, $eqpos ) );
2713 $value = trim( substr( $arg, $eqpos+
1 ) );
2714 if ( $value === false ) {
2717 if ( $name !== false ) {
2718 $assocArgs[$name] = $value;
2723 # Add a new element to the templace recursion path
2724 $this->mTemplatePath
[$part1] = 1;
2728 # If there are any <onlyinclude> tags, only include them
2729 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2730 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2732 foreach ($m[1] as $piece)
2735 # Remove <noinclude> sections and <includeonly> tags
2736 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2737 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2739 if( $this->mOutputType
== OT_HTML
) {
2740 # Strip <nowiki>, <pre>, etc.
2741 $text = $this->strip( $text, $this->mStripState
);
2742 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2744 $text = $this->replaceVariables( $text, $assocArgs );
2746 # If the template begins with a table or block-level
2747 # element, it should be treated as beginning a new line.
2748 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2749 $text = "\n" . $text;
2751 } elseif ( !$noargs ) {
2752 # $noparse and !$noargs
2753 # Just replace the arguments, not any double-brace items
2754 # This is used for rendered interwiki transclusion
2755 $text = $this->replaceVariables( $text, $assocArgs, true );
2758 # Prune lower levels off the recursion check path
2759 $this->mTemplatePath
= $lastPathLevel;
2762 wfProfileOut( $fname );
2763 return $piece['text'];
2766 # Replace raw HTML by a placeholder
2767 # Add a blank line preceding, to prevent it from mucking up
2768 # immediately preceding headings
2769 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2771 # replace ==section headers==
2772 # XXX this needs to go away once we have a better parser.
2773 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2774 if( !is_null( $title ) )
2775 $encodedname = base64_encode($title->getPrefixedDBkey());
2777 $encodedname = base64_encode("");
2778 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2779 PREG_SPLIT_DELIM_CAPTURE
);
2782 for( $i = 0; $i < count($m); $i +
= 2 ) {
2784 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2786 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2790 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2791 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2792 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2800 # Prune lower levels off the recursion check path
2801 $this->mTemplatePath
= $lastPathLevel;
2804 wfProfileOut( $fname );
2805 return $piece['text'];
2807 wfProfileOut( $fname );
2813 * Fetch the unparsed text of a template and register a reference to it.
2815 function fetchTemplate( $title ) {
2817 // Loop to fetch the article, with up to 1 redirect
2818 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2819 $rev = Revision
::newFromTitle( $title );
2820 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2824 $text = $rev->getText();
2825 if ( $text === false ) {
2829 $title = Title
::newFromRedirect( $text );
2835 * Transclude an interwiki link.
2837 function interwikiTransclude( $title, $action ) {
2838 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2840 if (!$wgEnableScaryTranscluding)
2841 return wfMsg('scarytranscludedisabled');
2843 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2844 // But we'll handle it generally anyway
2845 if ( $title->getNamespace() ) {
2846 // Use the canonical namespace, which should work anywhere
2847 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2849 $articleName = $title->getDBkey();
2852 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2853 $url .= "?action=$action";
2854 if (strlen($url) > 255)
2855 return wfMsg('scarytranscludetoolong');
2856 return $this->fetchScaryTemplateMaybeFromCache($url);
2859 function fetchScaryTemplateMaybeFromCache($url) {
2860 global $wgTranscludeCacheExpiry;
2861 $dbr =& wfGetDB(DB_SLAVE
);
2862 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2863 array('tc_url' => $url));
2865 $time = $obj->tc_time
;
2866 $text = $obj->tc_contents
;
2867 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2872 $text = wfGetHTTP($url);
2874 return wfMsg('scarytranscludefailed', $url);
2876 $dbw =& wfGetDB(DB_MASTER
);
2877 $dbw->replace('transcache', array('tc_url'), array(
2879 'tc_time' => time(),
2880 'tc_contents' => $text));
2886 * Triple brace replacement -- used for template arguments
2889 function argSubstitution( $matches ) {
2890 $arg = trim( $matches['title'] );
2891 $text = $matches['text'];
2892 $inputArgs = end( $this->mArgStack
);
2894 if ( array_key_exists( $arg, $inputArgs ) ) {
2895 $text = $inputArgs[$arg];
2896 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2897 $text = $matches['parts'][0];
2904 * Returns true if the function is allowed to include this entity
2907 function incrementIncludeCount( $dbk ) {
2908 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2909 $this->mIncludeCount
[$dbk] = 0;
2911 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2919 * This function accomplishes several tasks:
2920 * 1) Auto-number headings if that option is enabled
2921 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2922 * 3) Add a Table of contents on the top for users who have enabled the option
2923 * 4) Auto-anchor headings
2925 * It loops through all headlines, collects the necessary data, then splits up the
2926 * string and re-inserts the newly formatted headlines.
2928 * @param string $text
2929 * @param boolean $isMain
2932 function formatHeadings( $text, $isMain=true ) {
2933 global $wgMaxTocLevel, $wgContLang;
2935 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2937 $forceTocHere = false;
2938 if( !$this->mTitle
->userCanEdit() ) {
2941 $showEditLink = $this->mOptions
->getEditSection();
2944 # Inhibit editsection links if requested in the page
2945 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2946 if( $esw->matchAndRemove( $text ) ) {
2949 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2951 $mw =& MagicWord
::get( MAG_NOTOC
);
2952 if( $mw->matchAndRemove( $text ) ) {
2956 # Get all headlines for numbering them and adding funky stuff like [edit]
2957 # links - this is for later, but we need the number of headlines right now
2958 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2960 # if there are fewer than 4 headlines in the article, do not show TOC
2961 if( $numMatches < 4 ) {
2965 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2966 # override above conditions and always show TOC at that place
2968 $mw =& MagicWord
::get( MAG_TOC
);
2969 if($mw->match( $text ) ) {
2971 $forceTocHere = true;
2973 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2974 # override above conditions and always show TOC above first header
2975 $mw =& MagicWord
::get( MAG_FORCETOC
);
2976 if ($mw->matchAndRemove( $text ) ) {
2981 # Never ever show TOC if no headers
2982 if( $numMatches < 1 ) {
2986 # We need this to perform operations on the HTML
2987 $sk =& $this->mOptions
->getSkin();
2991 $sectionCount = 0; # headlineCount excluding template sections
2993 # Ugh .. the TOC should have neat indentation levels which can be
2994 # passed to the skin functions. These are determined here
2998 $sublevelCount = array();
2999 $levelCount = array();
3006 foreach( $matches[3] as $headline ) {
3008 $templatetitle = '';
3009 $templatesection = 0;
3012 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3014 $templatetitle = base64_decode($mat[1]);
3015 $templatesection = 1 +
(int)base64_decode($mat[2]);
3016 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3020 $prevlevel = $level;
3021 $prevtoclevel = $toclevel;
3023 $level = $matches[1][$headlineCount];
3025 if( $doNumberHeadings ||
$doShowToc ) {
3027 if ( $level > $prevlevel ) {
3028 # Increase TOC level
3030 $sublevelCount[$toclevel] = 0;
3031 $toc .= $sk->tocIndent();
3033 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3034 # Decrease TOC level, find level to jump to
3036 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3037 # Can only go down to level 1
3040 for ($i = $toclevel; $i > 0; $i--) {
3041 if ( $levelCount[$i] == $level ) {
3042 # Found last matching level
3046 elseif ( $levelCount[$i] < $level ) {
3047 # Found first matching level below current level
3054 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3057 # No change in level, end TOC line
3058 $toc .= $sk->tocLineEnd();
3061 $levelCount[$toclevel] = $level;
3063 # count number of headlines for each level
3064 @$sublevelCount[$toclevel]++
;
3066 for( $i = 1; $i <= $toclevel; $i++
) {
3067 if( !empty( $sublevelCount[$i] ) ) {
3071 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3077 # The canonized header is a version of the header text safe to use for links
3078 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3079 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3080 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3082 # Remove link placeholders by the link text.
3083 # <!--LINK number-->
3085 # link text with suffix
3086 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3087 "\$this->mLinkHolders['texts'][\$1]",
3088 $canonized_headline );
3089 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3090 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3091 $canonized_headline );
3094 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3095 $tocline = trim( $canonized_headline );
3096 # Save headline for section edit hint before it's escaped
3097 $headline_hint = trim( $canonized_headline );
3098 $canonized_headline = Sanitizer
::escapeId( $tocline );
3099 $refers[$headlineCount] = $canonized_headline;
3101 # count how many in assoc. array so we can track dupes in anchors
3102 @$refers[$canonized_headline]++
;
3103 $refcount[$headlineCount]=$refers[$canonized_headline];
3105 # Don't number the heading if it is the only one (looks silly)
3106 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3107 # the two are different if the line contains a link
3108 $headline=$numbering . ' ' . $headline;
3111 # Create the anchor for linking from the TOC to the section
3112 $anchor = $canonized_headline;
3113 if($refcount[$headlineCount] > 1 ) {
3114 $anchor .= '_' . $refcount[$headlineCount];
3116 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3117 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3119 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3120 if ( empty( $head[$headlineCount] ) ) {
3121 $head[$headlineCount] = '';
3124 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3126 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3129 # give headline the correct <h#> tag
3130 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3138 $toc .= $sk->tocUnindent( $toclevel - 1 );
3139 $toc = $sk->tocList( $toc );
3142 # split up and insert constructed headlines
3144 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3147 foreach( $blocks as $block ) {
3148 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3149 # This is the [edit] link that appears for the top block of text when
3150 # section editing is enabled
3152 # Disabled because it broke block formatting
3153 # For example, a bullet point in the top line
3154 # $full .= $sk->editSectionLink(0);
3157 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3158 # Top anchor now in skin
3162 if( !empty( $head[$i] ) ) {
3168 $mw =& MagicWord
::get( MAG_TOC
);
3169 return $mw->replace( $toc, $full );
3176 * Return an HTML link for the "ISBN 123456" text
3179 function magicISBN( $text ) {
3180 $fname = 'Parser::magicISBN';
3181 wfProfileIn( $fname );
3183 $a = split( 'ISBN ', ' '.$text );
3184 if ( count ( $a ) < 2 ) {
3185 wfProfileOut( $fname );
3188 $text = substr( array_shift( $a ), 1);
3189 $valid = '0123456789-Xx';
3191 foreach ( $a as $x ) {
3192 # hack: don't replace inside thumbnail title/alt
3194 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3199 $isbn = $blank = '' ;
3200 while ( ' ' == $x{0} ) {
3202 $x = substr( $x, 1 );
3204 if ( $x == '' ) { # blank isbn
3205 $text .= "ISBN $blank";
3208 while ( strstr( $valid, $x{0} ) != false ) {
3210 $x = substr( $x, 1 );
3212 $num = str_replace( '-', '', $isbn );
3213 $num = str_replace( ' ', '', $num );
3214 $num = str_replace( 'x', 'X', $num );
3217 $text .= "ISBN $blank$x";
3219 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3220 $text .= '<a href="' .
3221 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3222 "\" class=\"internal\">ISBN $isbn</a>";
3226 wfProfileOut( $fname );
3231 * Return an HTML link for the "RFC 1234" text
3234 * @param string $text Text to be processed
3235 * @param string $keyword Magic keyword to use (default RFC)
3236 * @param string $urlmsg Interface message to use (default rfcurl)
3239 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3241 $valid = '0123456789';
3244 $a = split( $keyword, ' '.$text );
3245 if ( count ( $a ) < 2 ) {
3248 $text = substr( array_shift( $a ), 1);
3250 /* Check if keyword is preceed by [[.
3251 * This test is made here cause of the array_shift above
3252 * that prevent the test to be done in the foreach.
3254 if ( substr( $text, -2 ) == '[[' ) {
3258 foreach ( $a as $x ) {
3259 /* token might be empty if we have RFC RFC 1234 */
3265 # hack: don't replace inside thumbnail title/alt
3267 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3268 $text .= $keyword . $x;
3274 /** remove and save whitespaces in $blank */
3275 while ( $x{0} == ' ' ) {
3277 $x = substr( $x, 1 );
3280 /** remove and save the rfc number in $id */
3281 while ( strstr( $valid, $x{0} ) != false ) {
3283 $x = substr( $x, 1 );
3287 /* call back stripped spaces*/
3288 $text .= $keyword.$blank.$x;
3289 } elseif( $internal ) {
3291 $text .= $keyword.$id.$x;
3293 /* build the external link*/
3294 $url = wfMsg( $urlmsg, $id);
3295 $sk =& $this->mOptions
->getSkin();
3296 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3297 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3300 /* Check if the next RFC keyword is preceed by [[ */
3301 $internal = ( substr($x,-2) == '[[' );
3307 * Transform wiki markup when saving a page by doing \r\n -> \n
3308 * conversion, substitting signatures, {{subst:}} templates, etc.
3310 * @param string $text the text to transform
3311 * @param Title &$title the Title object for the current article
3312 * @param User &$user the User object describing the current user
3313 * @param ParserOptions $options parsing options
3314 * @param bool $clearState whether to clear the parser state first
3315 * @return string the altered wiki markup
3318 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3319 $this->mOptions
= $options;
3320 $this->mTitle
=& $title;
3321 $this->mOutputType
= OT_WIKI
;
3323 if ( $clearState ) {
3324 $this->clearState();
3327 $stripState = false;
3331 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3332 $text = $this->strip( $text, $stripState, true );
3333 $text = $this->pstPass2( $text, $user );
3334 $text = $this->unstrip( $text, $stripState );
3335 $text = $this->unstripNoWiki( $text, $stripState );
3340 * Pre-save transform helper function
3343 function pstPass2( $text, &$user ) {
3344 global $wgContLang, $wgLocaltimezone;
3346 /* Note: This is the timestamp saved as hardcoded wikitext to
3347 * the database, we use $wgContLang here in order to give
3348 * everyone the same signiture and use the default one rather
3349 * than the one selected in each users preferences.
3351 if ( isset( $wgLocaltimezone ) ) {
3352 $oldtz = getenv( 'TZ' );
3353 putenv( 'TZ='.$wgLocaltimezone );
3355 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3356 ' (' . date( 'T' ) . ')';
3357 if ( isset( $wgLocaltimezone ) ) {
3358 putenv( 'TZ='.$oldtz );
3361 # Variable replacement
3362 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3363 $text = $this->replaceVariables( $text );
3366 $sigText = $this->getUserSig( $user );
3367 $text = strtr( $text, array(
3369 '~~~~' => "$sigText $d",
3373 # Context links: [[|name]] and [[name (context)|]]
3375 global $wgLegalTitleChars;
3376 $tc = "[$wgLegalTitleChars]";
3377 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3379 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3380 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3382 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3383 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3384 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3385 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3387 $t = $this->mTitle
->getText();
3388 if ( preg_match( $conpat, $t, $m ) ) {
3391 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3392 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3393 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3395 if ( '' == $context ) {
3396 $text = preg_replace( $p2, '[[\\1]]', $text );
3398 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3401 # Trim trailing whitespace
3402 # MAG_END (__END__) tag allows for trailing
3403 # whitespace to be deliberately included
3404 $text = rtrim( $text );
3405 $mw =& MagicWord
::get( MAG_END
);
3406 $mw->matchAndRemove( $text );
3412 * Fetch the user's signature text, if any, and normalize to
3413 * validated, ready-to-insert wikitext.
3419 function getUserSig( &$user ) {
3420 $username = $user->getName();
3421 $nickname = $user->getOption( 'nickname' );
3422 $nickname = $nickname === '' ?
$username : $nickname;
3424 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3425 # Sig. might contain markup; validate this
3426 if( $this->validateSig( $nickname ) !== false ) {
3427 # Validated; clean up (if needed) and return it
3428 return( $this->cleanSig( $nickname ) );
3430 # Failed to validate; fall back to the default
3431 $nickname = $username;
3432 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3436 # If we're still here, make it a link to the user page
3437 $userpage = $user->getUserPage();
3438 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3442 * Check that the user's signature contains no bad XML
3444 * @param string $text
3445 * @return mixed An expanded string, or false if invalid.
3447 function validateSig( $text ) {
3448 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3452 * Clean up signature text
3454 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3455 * 2) Substitute all transclusions
3457 * @param string $text
3458 * @return string Signature text
3460 function cleanSig( $text ) {
3461 $substWord = MagicWord
::get( MAG_SUBST
);
3462 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3463 $substText = '{{' . $substWord->getSynonym( 0 );
3465 $text = preg_replace( $substRegex, $substText, $text );
3466 $text = preg_replace( '/~{3,5}/', '', $text );
3467 $text = $this->replaceVariables( $text );
3473 * Set up some variables which are usually set up in parse()
3474 * so that an external function can call some class members with confidence
3477 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3478 $this->mTitle
=& $title;
3479 $this->mOptions
= $options;
3480 $this->mOutputType
= $outputType;
3481 if ( $clearState ) {
3482 $this->clearState();
3487 * Transform a MediaWiki message by replacing magic variables.
3489 * @param string $text the text to transform
3490 * @param ParserOptions $options options
3491 * @return string the text with variables substituted
3494 function transformMsg( $text, $options ) {
3496 static $executing = false;
3498 $fname = "Parser::transformMsg";
3500 # Guard against infinite recursion
3506 wfProfileIn($fname);
3508 $this->mTitle
= $wgTitle;
3509 $this->mOptions
= $options;
3510 $this->mOutputType
= OT_MSG
;
3511 $this->clearState();
3512 $text = $this->replaceVariables( $text );
3515 wfProfileOut($fname);
3520 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3521 * The callback should have the following form:
3522 * function myParserHook( $text, $params, &$parser ) { ... }
3524 * Transform and return $text. Use $parser for any required context, e.g. use
3525 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3529 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3530 * @param mixed $callback The callback function (and object) to use for the tag
3532 * @return The old value of the mTagHooks array associated with the hook
3534 function setHook( $tag, $callback ) {
3535 $oldVal = @$this->mTagHooks
[$tag];
3536 $this->mTagHooks
[$tag] = $callback;
3542 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3543 * Placeholders created in Skin::makeLinkObj()
3544 * Returns an array of links found, indexed by PDBK:
3548 * $options is a bit field, RLH_FOR_UPDATE to select for update
3550 function replaceLinkHolders( &$text, $options = 0 ) {
3552 global $wgOutputReplace;
3554 $fname = 'Parser::replaceLinkHolders';
3555 wfProfileIn( $fname );
3559 $sk =& $this->mOptions
->getSkin();
3560 $linkCache =& LinkCache
::singleton();
3562 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3563 wfProfileIn( $fname.'-check' );
3564 $dbr =& wfGetDB( DB_SLAVE
);
3565 $page = $dbr->tableName( 'page' );
3566 $threshold = $wgUser->getOption('stubthreshold');
3569 asort( $this->mLinkHolders
['namespaces'] );
3573 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3575 $title = $this->mLinkHolders
['titles'][$key];
3577 # Skip invalid entries.
3578 # Result will be ugly, but prevents crash.
3579 if ( is_null( $title ) ) {
3582 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3584 # Check if it's a static known link, e.g. interwiki
3585 if ( $title->isAlwaysKnown() ) {
3586 $colours[$pdbk] = 1;
3587 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3588 $colours[$pdbk] = 1;
3589 $this->mOutput
->addLink( $title, $id );
3590 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3591 $colours[$pdbk] = 0;
3593 # Not in the link cache, add it to the query
3594 if ( !isset( $current ) ) {
3596 $query = "SELECT page_id, page_namespace, page_title";
3597 if ( $threshold > 0 ) {
3598 $query .= ', page_len, page_is_redirect';
3600 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3601 } elseif ( $current != $ns ) {
3603 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3608 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3613 if ( $options & RLH_FOR_UPDATE
) {
3614 $query .= ' FOR UPDATE';
3617 $res = $dbr->query( $query, $fname );
3619 # Fetch data and form into an associative array
3620 # non-existent = broken
3623 while ( $s = $dbr->fetchObject($res) ) {
3624 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3625 $pdbk = $title->getPrefixedDBkey();
3626 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3627 $this->mOutput
->addLink( $title, $s->page_id
);
3629 if ( $threshold > 0 ) {
3630 $size = $s->page_len
;
3631 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3632 $colours[$pdbk] = 1;
3634 $colours[$pdbk] = 2;
3637 $colours[$pdbk] = 1;
3641 wfProfileOut( $fname.'-check' );
3643 # Construct search and replace arrays
3644 wfProfileIn( $fname.'-construct' );
3645 $wgOutputReplace = array();
3646 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3647 $pdbk = $pdbks[$key];
3648 $searchkey = "<!--LINK $key-->";
3649 $title = $this->mLinkHolders
['titles'][$key];
3650 if ( empty( $colours[$pdbk] ) ) {
3651 $linkCache->addBadLinkObj( $title );
3652 $colours[$pdbk] = 0;
3653 $this->mOutput
->addLink( $title, 0 );
3654 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3655 $this->mLinkHolders
['texts'][$key],
3656 $this->mLinkHolders
['queries'][$key] );
3657 } elseif ( $colours[$pdbk] == 1 ) {
3658 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3659 $this->mLinkHolders
['texts'][$key],
3660 $this->mLinkHolders
['queries'][$key] );
3661 } elseif ( $colours[$pdbk] == 2 ) {
3662 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3663 $this->mLinkHolders
['texts'][$key],
3664 $this->mLinkHolders
['queries'][$key] );
3667 wfProfileOut( $fname.'-construct' );
3670 wfProfileIn( $fname.'-replace' );
3672 $text = preg_replace_callback(
3673 '/(<!--LINK .*?-->)/',
3674 "wfOutputReplaceMatches",
3677 wfProfileOut( $fname.'-replace' );
3680 # Now process interwiki link holders
3681 # This is quite a bit simpler than internal links
3682 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3683 wfProfileIn( $fname.'-interwiki' );
3684 # Make interwiki link HTML
3685 $wgOutputReplace = array();
3686 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3687 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3688 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3691 $text = preg_replace_callback(
3692 '/<!--IWLINK (.*?)-->/',
3693 "wfOutputReplaceMatches",
3695 wfProfileOut( $fname.'-interwiki' );
3698 wfProfileOut( $fname );
3703 * Replace <!--LINK--> link placeholders with plain text of links
3704 * (not HTML-formatted).
3705 * @param string $text
3708 function replaceLinkHoldersText( $text ) {
3709 $fname = 'Parser::replaceLinkHoldersText';
3710 wfProfileIn( $fname );
3712 $text = preg_replace_callback(
3713 '/<!--(LINK|IWLINK) (.*?)-->/',
3714 array( &$this, 'replaceLinkHoldersTextCallback' ),
3717 wfProfileOut( $fname );
3722 * @param array $matches
3726 function replaceLinkHoldersTextCallback( $matches ) {
3727 $type = $matches[1];
3729 if( $type == 'LINK' ) {
3730 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3731 return $this->mLinkHolders
['texts'][$key];
3733 } elseif( $type == 'IWLINK' ) {
3734 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3735 return $this->mInterwikiLinkHolders
['texts'][$key];
3742 * Renders an image gallery from a text with one line per image.
3743 * text labels may be given by using |-style alternative text. E.g.
3744 * Image:one.jpg|The number "1"
3745 * Image:tree.jpg|A tree
3746 * given as text will return the HTML of a gallery with two images,
3747 * labeled 'The number "1"' and
3750 function renderImageGallery( $text ) {
3752 $parserOptions = new ParserOptions
;
3753 $localParser = new Parser();
3755 $ig = new ImageGallery();
3756 $ig->setShowBytes( false );
3757 $ig->setShowFilename( false );
3758 $lines = explode( "\n", $text );
3760 foreach ( $lines as $line ) {
3761 # match lines like these:
3762 # Image:someimage.jpg|This is some image
3763 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3765 if ( count( $matches ) == 0 ) {
3768 $nt =& Title
::newFromText( $matches[1] );
3769 if( is_null( $nt ) ) {
3770 # Bogus title. Ignore these so we don't bomb out later.
3773 if ( isset( $matches[3] ) ) {
3774 $label = $matches[3];
3779 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3780 $html = $pout->getText();
3782 $ig->add( new Image( $nt ), $html );
3783 $this->mOutput
->addImage( $nt->getDBkey() );
3785 return $ig->toHTML();
3789 * Parse image options text and use it to make an image
3791 function makeImage( &$nt, $options ) {
3792 global $wgUseImageResize;
3796 # Check if the options text is of the form "options|alt text"
3798 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3799 # * left no resizing, just left align. label is used for alt= only
3800 # * right same, but right aligned
3801 # * none same, but not aligned
3802 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3803 # * center center the image
3804 # * framed Keep original image size, no magnify-button.
3806 $part = explode( '|', $options);
3808 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3809 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3810 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3811 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3812 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3813 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3814 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3815 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3818 $width = $height = $framed = $thumb = false;
3819 $manual_thumb = '' ;
3821 foreach( $part as $key => $val ) {
3822 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3824 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3825 # use manually specified thumbnail
3827 $manual_thumb = $match;
3828 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3829 # remember to set an alignment, don't render immediately
3831 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3832 # remember to set an alignment, don't render immediately
3834 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3835 # remember to set an alignment, don't render immediately
3837 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3838 # remember to set an alignment, don't render immediately
3840 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3841 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3842 # $match is the image width in pixels
3843 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3844 $width = intval( $m[1] );
3845 $height = intval( $m[2] );
3847 $width = intval($match);
3849 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3855 # Strip bad stuff out of the alt text
3856 $alt = $this->replaceLinkHoldersText( $caption );
3858 # make sure there are no placeholders in thumbnail attributes
3859 # that are later expanded to html- so expand them now and
3861 $alt = $this->unstrip($alt, $this->mStripState
);
3862 $alt = Sanitizer
::stripAllTags( $alt );
3864 # Linker does the rest
3865 $sk =& $this->mOptions
->getSkin();
3866 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3870 * Set a flag in the output object indicating that the content is dynamic and
3871 * shouldn't be cached.
3873 function disableCache() {
3874 $this->mOutput
->mCacheTime
= -1;
3878 * Callback from the Sanitizer for expanding items found in HTML attribute
3879 * values, so they can be safely tested and escaped.
3880 * @param string $text
3881 * @param array $args
3885 function attributeStripCallback( &$text, $args ) {
3886 $text = $this->replaceVariables( $text, $args );
3887 $text = $this->unstripForHTML( $text );
3891 function unstripForHTML( $text ) {
3892 $text = $this->unstrip( $text, $this->mStripState
);
3893 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3901 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3902 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3903 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3909 function getTags() { return array_keys( $this->mTagHooks
); }
3915 * @package MediaWiki
3919 var $mText, # The output text
3920 $mLanguageLinks, # List of the full text of language links, in the order they appear
3921 $mCategories, # Map of category names to sort keys
3922 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3923 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
3924 $mVersion, # Compatibility check
3925 $mTitleText, # title text of the chosen language variant
3926 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3927 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3928 $mImages, # DB keys of the images used, in the array key only
3929 $mExternalLinks; # External link URLs, in the key only
3931 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3932 $containsOldMagic = false, $titletext = '' )
3934 $this->mText
= $text;
3935 $this->mLanguageLinks
= $languageLinks;
3936 $this->mCategories
= $categoryLinks;
3937 $this->mContainsOldMagic
= $containsOldMagic;
3938 $this->mCacheTime
= '';
3939 $this->mVersion
= MW_PARSER_VERSION
;
3940 $this->mTitleText
= $titletext;
3941 $this->mLinks
= array();
3942 $this->mTemplates
= array();
3943 $this->mImages
= array();
3944 $this->mExternalLinks
= array();
3947 function getText() { return $this->mText
; }
3948 function getLanguageLinks() { return $this->mLanguageLinks
; }
3949 function getCategoryLinks() { return array_keys( $this->mCategories
); }
3950 function &getCategories() { return $this->mCategories
; }
3951 function getCacheTime() { return $this->mCacheTime
; }
3952 function getTitleText() { return $this->mTitleText
; }
3953 function &getLinks() { return $this->mLinks
; }
3954 function &getTemplates() { return $this->mTemplates
; }
3955 function &getImages() { return $this->mImages
; }
3956 function &getExternalLinks() { return $this->mExternalLinks
; }
3958 function containsOldMagic() { return $this->mContainsOldMagic
; }
3959 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
3960 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
3961 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
3962 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
3963 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
3964 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
3966 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
3967 function addImage( $name ) { $this->mImages
[$name] = 1; }
3968 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
3969 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
3971 function addLink( $title, $id ) {
3972 $ns = $title->getNamespace();
3973 $dbk = $title->getDBkey();
3974 if ( !isset( $this->mLinks
[$ns] ) ) {
3975 $this->mLinks
[$ns] = array();
3977 $this->mLinks
[$ns][$dbk] = $id;
3980 function addTemplate( $title, $id ) {
3981 $ns = $title->getNamespace();
3982 $dbk = $title->getDBkey();
3983 if ( !isset( $this->mTemplates
[$ns] ) ) {
3984 $this->mTemplates
[$ns] = array();
3986 $this->mTemplates
[$ns][$dbk] = $id;
3993 function merge( $other ) {
3994 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3995 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3996 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
4000 * Return true if this cached output object predates the global or
4001 * per-article cache invalidation timestamps, or if it comes from
4002 * an incompatible older version.
4004 * @param string $touched the affected article's last touched timestamp
4008 function expired( $touched ) {
4009 global $wgCacheEpoch;
4010 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4011 $this->getCacheTime() < $touched ||
4012 $this->getCacheTime() <= $wgCacheEpoch ||
4013 !isset( $this->mVersion
) ||
4014 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4019 * Set options of the Parser
4021 * @package MediaWiki
4025 # All variables are private
4026 var $mUseTeX; # Use texvc to expand <math> tags
4027 var $mUseDynamicDates; # Use DateFormatter to format dates
4028 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4029 var $mAllowExternalImages; # Allow external images inline
4030 var $mAllowExternalImagesFrom; # If not, any exception?
4031 var $mSkin; # Reference to the preferred skin
4032 var $mDateFormat; # Date format index
4033 var $mEditSection; # Create "edit section" links
4034 var $mNumberHeadings; # Automatically number headings
4035 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4036 var $mTidy; # Ask for tidy cleanup
4038 function getUseTeX() { return $this->mUseTeX
; }
4039 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4040 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4041 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4042 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4043 function &getSkin() { return $this->mSkin
; }
4044 function getDateFormat() { return $this->mDateFormat
; }
4045 function getEditSection() { return $this->mEditSection
; }
4046 function getNumberHeadings() { return $this->mNumberHeadings
; }
4047 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4048 function getTidy() { return $this->mTidy
; }
4050 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4051 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4052 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4053 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4054 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4055 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4056 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4057 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4058 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4059 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4060 function setSkin( &$x ) { $this->mSkin
=& $x; }
4062 function ParserOptions() {
4064 $this->initialiseFromUser( $wgUser );
4068 * Get parser options
4071 function newFromUser( &$user ) {
4072 $popts = new ParserOptions
;
4073 $popts->initialiseFromUser( $user );
4077 /** Get user options */
4078 function initialiseFromUser( &$userInput ) {
4079 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4080 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4081 $fname = 'ParserOptions::initialiseFromUser';
4082 wfProfileIn( $fname );
4083 if ( !$userInput ) {
4085 $user->setLoaded( true );
4087 $user =& $userInput;
4090 $this->mUseTeX
= $wgUseTeX;
4091 $this->mUseDynamicDates
= $wgUseDynamicDates;
4092 $this->mInterwikiMagic
= $wgInterwikiMagic;
4093 $this->mAllowExternalImages
= $wgAllowExternalImages;
4094 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4095 wfProfileIn( $fname.'-skin' );
4096 $this->mSkin
=& $user->getSkin();
4097 wfProfileOut( $fname.'-skin' );
4098 $this->mDateFormat
= $user->getOption( 'date' );
4099 $this->mEditSection
= true;
4100 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4101 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4102 $this->mTidy
= false;
4103 wfProfileOut( $fname );
4108 * Callback function used by Parser::replaceLinkHolders()
4109 * to substitute link placeholders.
4111 function &wfOutputReplaceMatches( $matches ) {
4112 global $wgOutputReplace;
4113 return $wgOutputReplace[$matches[1]];
4117 * Return the total number of articles
4119 function wfNumberOfArticles() {
4120 global $wgNumberOfArticles;
4123 return $wgNumberOfArticles;
4127 * Return the number of files
4129 function wfNumberOfFiles() {
4130 $fname = 'wfNumberOfFiles';
4132 wfProfileIn( $fname );
4133 $dbr =& wfGetDB( DB_SLAVE
);
4134 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4135 wfProfileOut( $fname );
4141 * Get various statistics from the database
4144 function wfLoadSiteStats() {
4145 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4146 $fname = 'wfLoadSiteStats';
4148 if ( -1 != $wgNumberOfArticles ) return;
4149 $dbr =& wfGetDB( DB_SLAVE
);
4150 $s = $dbr->selectRow( 'site_stats',
4151 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4152 array( 'ss_row_id' => 1 ), $fname
4155 if ( $s === false ) {
4158 $wgTotalViews = $s->ss_total_views
;
4159 $wgTotalEdits = $s->ss_total_edits
;
4160 $wgNumberOfArticles = $s->ss_good_articles
;
4166 * Basically replacing " > and < with HTML entities ( ", >, <)
4168 * @param string $in Text that might contain HTML tags
4169 * @return string Escaped string
4171 function wfEscapeHTMLTagsOnly( $in ) {
4173 array( '"', '>', '<' ),
4174 array( '"', '>', '<' ),