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.1' );
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
96 private $mTagHooks, $mFunctionHooks;
98 # Cleared with clearState():
105 $mInterwikiLinkHolders,
109 $mStripState = array(),
114 $mTemplates, // cache of already loaded templates, avoids
115 // multiple SQL queries for the same string
116 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
117 // in this path. Used for loop detection.
120 # These are variables reset at least once per parse regardless of $clearState
122 $mOptions, // ParserOptions object
123 $mTitle, // Title context, used for self-link rendering and similar things
124 $mOutputType, // Output type, one of the OT_xxx constants
125 $mRevisionId; // ID to display in {{REVISIONID}} tags
135 $this->mTagHooks
= array();
136 $this->mFunctionHooks
= array();
145 function clearState() {
146 $this->mOutput
= new ParserOutput
;
147 $this->mAutonumber
= 0;
148 $this->mLastSection
= '';
149 $this->mDTopen
= false;
150 $this->mVariables
= false;
151 $this->mIncludeCount
= array();
152 $this->mStripState
= array();
153 $this->mArgStack
= array();
154 $this->mInPre
= false;
155 $this->mInterwikiLinkHolders
= array(
159 $this->mLinkHolders
= array(
160 'namespaces' => array(),
162 'queries' => array(),
166 $this->mRevisionId
= null;
167 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
169 # Clear these on every parse, bug 4549
170 $this->mTemplates
= array();
171 $this->mTemplatePath
= array();
173 wfRunHooks( 'ParserClearState', array( &$this ) );
177 * Accessor for mUniqPrefix.
181 function UniqPrefix() {
182 return $this->mUniqPrefix
;
186 * Convert wikitext to HTML
187 * Do not call this function recursively.
190 * @param string $text Text we want to parse
191 * @param Title &$title A title object
192 * @param array $options
193 * @param boolean $linestart
194 * @param boolean $clearState
195 * @param int $revid number to pass in {{REVISIONID}}
196 * @return ParserOutput a ParserOutput
198 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
200 * First pass--just handle <nowiki> sections, pass the rest off
201 * to internalParse() which does all the real work.
204 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
205 $fname = 'Parser::parse';
206 wfProfileIn( $fname );
212 $this->mOptions
= $options;
213 $this->mTitle
=& $title;
214 $this->mRevisionId
= $revid;
215 $this->mOutputType
= OT_HTML
;
217 //$text = $this->strip( $text, $this->mStripState );
218 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
219 $x =& $this->mStripState
;
221 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
222 $text = $this->strip( $text, $x );
223 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
225 # Hook to suspend the parser in this state
226 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
227 wfProfileOut( $fname );
231 $text = $this->internalParse( $text );
233 $text = $this->unstrip( $text, $this->mStripState
);
235 # Clean up special characters, only run once, next-to-last before doBlockLevels
237 # french spaces, last one Guillemet-left
238 # only if there is something before the space
239 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
240 # french spaces, Guillemet-right
241 '/(\\302\\253) /' => '\\1 ',
242 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
244 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
247 $text = $this->doBlockLevels( $text, $linestart );
249 $this->replaceLinkHolders( $text );
251 # the position of the parserConvert() call should not be changed. it
252 # assumes that the links are all replaced and the only thing left
253 # is the <nowiki> mark.
254 # Side-effects: this calls $this->mOutput->setTitleText()
255 $text = $wgContLang->parserConvert( $text, $this );
257 $text = $this->unstripNoWiki( $text, $this->mStripState
);
259 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
261 $text = Sanitizer
::normalizeCharReferences( $text );
263 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
264 $text = Parser
::tidy($text);
266 # attempt to sanitize at least some nesting problems
267 # (bug #2702 and quite a few others)
269 # ''Something [http://www.cool.com cool''] -->
270 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
271 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
272 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
273 # fix up an anchor inside another anchor, only
274 # at least for a single single nested link (bug 3695)
275 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
276 '\\1\\2</a>\\3</a>\\1\\4</a>',
277 # fix div inside inline elements- doBlockLevels won't wrap a line which
278 # contains a div, so fix it up here; replace
279 # div with escaped text
280 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
281 '\\1\\3<div\\5>\\6</div>\\8\\9',
282 # remove empty italic or bold tag pairs, some
283 # introduced by rules above
284 '/<([bi])><\/\\1>/' => ''
287 $text = preg_replace(
288 array_keys( $tidyregs ),
289 array_values( $tidyregs ),
293 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
295 $this->mOutput
->setText( $text );
296 wfProfileOut( $fname );
298 return $this->mOutput
;
302 * Get a random string
307 function getRandomString() {
308 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
311 function &getTitle() { return $this->mTitle
; }
312 function getOptions() { return $this->mOptions
; }
315 * Replaces all occurrences of <$tag>content</$tag> in the text
316 * with a random marker and returns the new text. the output parameter
317 * $content will be an associative array filled with data on the form
318 * $unique_marker => content.
320 * If $content is already set, the additional entries will be appended
321 * If $tag is set to STRIP_COMMENTS, the function will extract
322 * <!-- HTML comments -->
327 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
328 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
343 if( $tag == STRIP_COMMENTS
) {
347 $start = "/<$tag(\\s+[^>]*|\\s*\/?)>/i";
348 $end = "/<\\/$tag\\s*>/i";
351 while ( '' != $text ) {
352 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
354 if( count( $p ) < 3 ) {
360 // If $attributes ends with '/', we have an empty element tag, <tag />
361 if( $tag != STRIP_COMMENTS
&& substr( $attributes, -1 ) == '/' ) {
362 $attributes = substr( $attributes, 0, -1);
368 $marker = $rnd . sprintf('%08X', $n++
);
369 $stripped .= $marker;
371 $tags[$marker] = "<$tag$attributes$empty>";
372 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
374 if ( $empty === '/' ) {
375 // Empty element tag, <tag />
376 $content[$marker] = null;
379 $q = preg_split( $end, $inside, 2 );
380 $content[$marker] = $q[0];
381 if( count( $q ) < 2 ) {
382 # No end tag -- let it run out to the end of the text.
393 * Wrapper function for extractTagsAndParams
394 * for cases where $tags and $params isn't needed
395 * i.e. where tags will never have params, like <nowiki>
400 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
401 $dummy_tags = array();
402 $dummy_params = array();
404 return Parser
::extractTagsAndParams( $tag, $text, $content,
405 $dummy_tags, $dummy_params, $uniq_prefix );
409 * Strips and renders nowiki, pre, math, hiero
410 * If $render is set, performs necessary rendering operations on plugins
411 * Returns the text, and fills an array with data needed in unstrip()
412 * If the $state is already a valid strip state, it adds to the state
414 * @param bool $stripcomments when set, HTML comments <!-- like this -->
415 * will be stripped in addition to other tags. This is important
416 * for section editing, where these comments cause confusion when
417 * counting the sections in the wikisource
421 function strip( $text, &$state, $stripcomments = false ) {
422 $render = ($this->mOutputType
== OT_HTML
);
423 $html_content = array();
424 $nowiki_content = array();
425 $math_content = array();
426 $pre_content = array();
427 $comment_content = array();
428 $ext_content = array();
430 $ext_params = array();
431 $gallery_content = array();
433 # Replace any instances of the placeholders
434 $uniq_prefix = $this->mUniqPrefix
;
435 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
440 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
441 foreach( $html_content as $marker => $content ) {
443 # Raw and unchecked for validity.
444 $html_content[$marker] = $content;
446 $html_content[$marker] = '<html>'.$content.'</html>';
452 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
453 foreach( $nowiki_content as $marker => $content ) {
455 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
457 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
462 if( $this->mOptions
->getUseTeX() ) {
463 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
464 foreach( $math_content as $marker => $content ){
466 $math_content[$marker] = renderMath( $content );
468 $math_content[$marker] = '<math>'.$content.'</math>';
474 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
475 foreach( $pre_content as $marker => $content ){
477 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
479 $pre_content[$marker] = '<pre>'.$content.'</pre>';
484 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
485 foreach( $gallery_content as $marker => $content ) {
486 require_once( 'ImageGallery.php' );
488 $gallery_content[$marker] = $this->renderImageGallery( $content );
490 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
495 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
496 foreach( $comment_content as $marker => $content ){
497 $comment_content[$marker] = '<!--'.$content.'-->';
501 foreach ( $this->mTagHooks
as $tag => $callback ) {
502 $ext_content[$tag] = array();
503 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
504 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
505 foreach( $ext_content[$tag] as $marker => $content ) {
506 $full_tag = $ext_tags[$tag][$marker];
507 $params = $ext_params[$tag][$marker];
509 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
511 if ( is_null( $content ) ) {
513 $ext_content[$tag][$marker] = $full_tag;
515 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
521 # Unstrip comments unless explicitly told otherwise.
522 # (The comments are always stripped prior to this point, so as to
523 # not invoke any extension tags / parser hooks contained within
525 if ( !$stripcomments ) {
526 $tempstate = array( 'comment' => $comment_content );
527 $text = $this->unstrip( $text, $tempstate );
528 $comment_content = array();
531 # Merge state with the pre-existing state, if there is one
533 $state['html'] = $state['html'] +
$html_content;
534 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
535 $state['math'] = $state['math'] +
$math_content;
536 $state['pre'] = $state['pre'] +
$pre_content;
537 $state['gallery'] = $state['gallery'] +
$gallery_content;
538 $state['comment'] = $state['comment'] +
$comment_content;
540 foreach( $ext_content as $tag => $array ) {
541 if ( array_key_exists( $tag, $state ) ) {
542 $state[$tag] = $state[$tag] +
$array;
547 'html' => $html_content,
548 'nowiki' => $nowiki_content,
549 'math' => $math_content,
550 'pre' => $pre_content,
551 'gallery' => $gallery_content,
552 'comment' => $comment_content,
559 * restores pre, math, and hiero removed by strip()
561 * always call unstripNoWiki() after this one
564 function unstrip( $text, &$state ) {
565 if ( !is_array( $state ) ) {
569 # Must expand in reverse order, otherwise nested tags will be corrupted
570 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
571 if( $tag != 'nowiki' && $tag != 'html' ) {
572 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
573 $text = str_replace( $uniq, $content, $text );
582 * always call this after unstrip() to preserve the order
586 function unstripNoWiki( $text, &$state ) {
587 if ( !is_array( $state ) ) {
591 # Must expand in reverse order, otherwise nested tags will be corrupted
592 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
593 $text = str_replace( key( $state['nowiki'] ), $content, $text );
598 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
599 $text = str_replace( key( $state['html'] ), $content, $text );
607 * Add an item to the strip state
608 * Returns the unique tag which must be inserted into the stripped text
609 * The tag will be replaced with the original text in unstrip()
613 function insertStripItem( $text, &$state ) {
614 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
621 'comment' => array(),
622 'gallery' => array(),
625 $state['item'][$rnd] = $text;
630 * Interface with html tidy, used if $wgUseTidy = true.
631 * If tidy isn't able to correct the markup, the original will be
632 * returned in all its glory with a warning comment appended.
634 * Either the external tidy program or the in-process tidy extension
635 * will be used depending on availability. Override the default
636 * $wgTidyInternal setting to disable the internal if it's not working.
638 * @param string $text Hideous HTML input
639 * @return string Corrected HTML output
643 function tidy( $text ) {
644 global $wgTidyInternal;
645 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
646 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
647 '<head><title>test</title></head><body>'.$text.'</body></html>';
648 if( $wgTidyInternal ) {
649 $correctedtext = Parser
::internalTidy( $wrappedtext );
651 $correctedtext = Parser
::externalTidy( $wrappedtext );
653 if( is_null( $correctedtext ) ) {
654 wfDebug( "Tidy error detected!\n" );
655 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
657 return $correctedtext;
661 * Spawn an external HTML tidy process and get corrected markup back from it.
666 function externalTidy( $text ) {
667 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
668 $fname = 'Parser::externalTidy';
669 wfProfileIn( $fname );
674 $descriptorspec = array(
675 0 => array('pipe', 'r'),
676 1 => array('pipe', 'w'),
677 2 => array('file', '/dev/null', 'a')
680 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
681 if (is_resource($process)) {
682 // Theoretically, this style of communication could cause a deadlock
683 // here. If the stdout buffer fills up, then writes to stdin could
684 // block. This doesn't appear to happen with tidy, because tidy only
685 // writes to stdout after it's finished reading from stdin. Search
686 // for tidyParseStdin and tidySaveStdout in console/tidy.c
687 fwrite($pipes[0], $text);
689 while (!feof($pipes[1])) {
690 $cleansource .= fgets($pipes[1], 1024);
693 proc_close($process);
696 wfProfileOut( $fname );
698 if( $cleansource == '' && $text != '') {
699 // Some kind of error happened, so we couldn't get the corrected text.
700 // Just give up; we'll use the source text and append a warning.
708 * Use the HTML tidy PECL extension to use the tidy library in-process,
709 * saving the overhead of spawning a new process. Currently written to
710 * the PHP 4.3.x version of the extension, may not work on PHP 5.
712 * 'pear install tidy' should be able to compile the extension module.
717 function internalTidy( $text ) {
719 $fname = 'Parser::internalTidy';
720 wfProfileIn( $fname );
722 tidy_load_config( $wgTidyConf );
723 tidy_set_encoding( 'utf8' );
724 tidy_parse_string( $text );
726 if( tidy_get_status() == 2 ) {
727 // 2 is magic number for fatal error
728 // http://www.php.net/manual/en/function.tidy-get-status.php
731 $cleansource = tidy_get_output();
733 wfProfileOut( $fname );
738 * parse the wiki syntax used to render tables
742 function doTableStuff ( $t ) {
743 $fname = 'Parser::doTableStuff';
744 wfProfileIn( $fname );
746 $t = explode ( "\n" , $t ) ;
747 $td = array () ; # Is currently a td tag open?
748 $ltd = array () ; # Was it TD or TH?
749 $tr = array () ; # Is currently a tr tag open?
750 $ltr = array () ; # tr attributes
751 $has_opened_tr = array(); # Did this table open a <tr> element?
752 $indent_level = 0; # indent level of the table
753 foreach ( $t AS $k => $x )
756 $fc = substr ( $x , 0 , 1 ) ;
757 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
758 $indent_level = strlen( $matches[1] );
760 $attributes = $this->unstripForHTML( $matches[2] );
762 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
763 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
764 array_push ( $td , false ) ;
765 array_push ( $ltd , '' ) ;
766 array_push ( $tr , false ) ;
767 array_push ( $ltr , '' ) ;
768 array_push ( $has_opened_tr, false );
770 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
771 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
772 $z = "</table>" . substr ( $x , 2);
773 $l = array_pop ( $ltd ) ;
774 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
775 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
776 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
778 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
780 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
781 $x = substr ( $x , 1 ) ;
782 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
784 $l = array_pop ( $ltd ) ;
785 array_pop ( $has_opened_tr );
786 array_push ( $has_opened_tr , true ) ;
787 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
788 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
791 array_push ( $tr , false ) ;
792 array_push ( $td , false ) ;
793 array_push ( $ltd , '' ) ;
794 $attributes = $this->unstripForHTML( $x );
795 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
797 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
799 if ( '|+' == substr ( $x , 0 , 2 ) ) {
801 $x = substr ( $x , 1 ) ;
803 $after = substr ( $x , 1 ) ;
804 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
806 // Split up multiple cells on the same line.
807 // FIXME: This can result in improper nesting of tags processed
808 // by earlier parser steps, but should avoid splitting up eg
809 // attribute values containing literal "||".
810 $after = wfExplodeMarkup( '||', $after );
814 # Loop through each table cell
815 foreach ( $after AS $theline )
820 $tra = array_pop ( $ltr ) ;
821 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
822 array_push ( $tr , true ) ;
823 array_push ( $ltr , '' ) ;
824 array_pop ( $has_opened_tr );
825 array_push ( $has_opened_tr , true ) ;
828 $l = array_pop ( $ltd ) ;
829 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
830 if ( $fc == '|' ) $l = 'td' ;
831 else if ( $fc == '!' ) $l = 'th' ;
832 else if ( $fc == '+' ) $l = 'caption' ;
834 array_push ( $ltd , $l ) ;
837 $y = explode ( '|' , $theline , 2 ) ;
838 # Note that a '|' inside an invalid link should not
839 # be mistaken as delimiting cell parameters
840 if ( strpos( $y[0], '[[' ) !== false ) {
841 $y = array ($theline);
843 if ( count ( $y ) == 1 )
844 $y = "{$z}<{$l}>{$y[0]}" ;
846 $attributes = $this->unstripForHTML( $y[0] );
847 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
850 array_push ( $td , true ) ;
855 # Closing open td, tr && table
856 while ( count ( $td ) > 0 )
858 $l = array_pop ( $ltd ) ;
859 if ( array_pop ( $td ) ) $t[] = '</td>' ;
860 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
861 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
865 $t = implode ( "\n" , $t ) ;
866 # special case: don't return empty table
867 if($t == "<table>\n<tr><td></td></tr>\n</table>")
869 wfProfileOut( $fname );
874 * Helper function for parse() that transforms wiki markup into
875 * HTML. Only called for $mOutputType == OT_HTML.
879 function internalParse( $text ) {
882 $fname = 'Parser::internalParse';
883 wfProfileIn( $fname );
885 # Remove <noinclude> tags and <includeonly> sections
886 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
887 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
888 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
890 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
891 $text = $this->replaceVariables( $text, $args );
893 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
895 $text = $this->doHeadings( $text );
896 if($this->mOptions
->getUseDynamicDates()) {
897 $df =& DateFormatter
::getInstance();
898 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
900 $text = $this->doAllQuotes( $text );
901 $text = $this->replaceInternalLinks( $text );
902 $text = $this->replaceExternalLinks( $text );
904 # replaceInternalLinks may sometimes leave behind
905 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
906 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
908 $text = $this->doMagicLinks( $text );
909 $text = $this->doTableStuff( $text );
910 $text = $this->formatHeadings( $text, $isMain );
912 wfProfileOut( $fname );
917 * Replace special strings like "ISBN xxx" and "RFC xxx" with
918 * magic external links.
922 function &doMagicLinks( &$text ) {
923 $text = $this->magicISBN( $text );
924 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
925 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
930 * Parse headers and return html
934 function doHeadings( $text ) {
935 $fname = 'Parser::doHeadings';
936 wfProfileIn( $fname );
937 for ( $i = 6; $i >= 1; --$i ) {
938 $h = str_repeat( '=', $i );
939 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
940 "<h{$i}>\\1</h{$i}>\\2", $text );
942 wfProfileOut( $fname );
947 * Replace single quotes with HTML markup
949 * @return string the altered text
951 function doAllQuotes( $text ) {
952 $fname = 'Parser::doAllQuotes';
953 wfProfileIn( $fname );
955 $lines = explode( "\n", $text );
956 foreach ( $lines as $line ) {
957 $outtext .= $this->doQuotes ( $line ) . "\n";
959 $outtext = substr($outtext, 0,-1);
960 wfProfileOut( $fname );
965 * Helper function for doAllQuotes()
968 function doQuotes( $text ) {
969 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
970 if ( count( $arr ) == 1 )
974 # First, do some preliminary work. This may shift some apostrophes from
975 # being mark-up to being text. It also counts the number of occurrences
976 # of bold and italics mark-ups.
980 foreach ( $arr as $r )
982 if ( ( $i %
2 ) == 1 )
984 # If there are ever four apostrophes, assume the first is supposed to
985 # be text, and the remaining three constitute mark-up for bold text.
986 if ( strlen( $arr[$i] ) == 4 )
991 # If there are more than 5 apostrophes in a row, assume they're all
992 # text except for the last 5.
993 else if ( strlen( $arr[$i] ) > 5 )
995 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
998 # Count the number of occurrences of bold and italics mark-ups.
999 # We are not counting sequences of five apostrophes.
1000 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
1001 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
1002 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1007 # If there is an odd number of both bold and italics, it is likely
1008 # that one of the bold ones was meant to be an apostrophe followed
1009 # by italics. Which one we cannot know for certain, but it is more
1010 # likely to be one that has a single-letter word before it.
1011 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1014 $firstsingleletterword = -1;
1015 $firstmultiletterword = -1;
1017 foreach ( $arr as $r )
1019 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1021 $x1 = substr ($arr[$i-1], -1);
1022 $x2 = substr ($arr[$i-1], -2, 1);
1024 if ($firstspace == -1) $firstspace = $i;
1025 } else if ($x2 == ' ') {
1026 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1028 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1034 # If there is a single-letter word, use it!
1035 if ($firstsingleletterword > -1)
1037 $arr [ $firstsingleletterword ] = "''";
1038 $arr [ $firstsingleletterword-1 ] .= "'";
1040 # If not, but there's a multi-letter word, use that one.
1041 else if ($firstmultiletterword > -1)
1043 $arr [ $firstmultiletterword ] = "''";
1044 $arr [ $firstmultiletterword-1 ] .= "'";
1046 # ... otherwise use the first one that has neither.
1047 # (notice that it is possible for all three to be -1 if, for example,
1048 # there is only one pentuple-apostrophe in the line)
1049 else if ($firstspace > -1)
1051 $arr [ $firstspace ] = "''";
1052 $arr [ $firstspace-1 ] .= "'";
1056 # Now let's actually convert our apostrophic mush to HTML!
1061 foreach ($arr as $r)
1065 if ($state == 'both')
1072 if (strlen ($r) == 2)
1075 { $output .= '</i>'; $state = ''; }
1076 else if ($state == 'bi')
1077 { $output .= '</i>'; $state = 'b'; }
1078 else if ($state == 'ib')
1079 { $output .= '</b></i><b>'; $state = 'b'; }
1080 else if ($state == 'both')
1081 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1082 else # $state can be 'b' or ''
1083 { $output .= '<i>'; $state .= 'i'; }
1085 else if (strlen ($r) == 3)
1088 { $output .= '</b>'; $state = ''; }
1089 else if ($state == 'bi')
1090 { $output .= '</i></b><i>'; $state = 'i'; }
1091 else if ($state == 'ib')
1092 { $output .= '</b>'; $state = 'i'; }
1093 else if ($state == 'both')
1094 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1095 else # $state can be 'i' or ''
1096 { $output .= '<b>'; $state .= 'b'; }
1098 else if (strlen ($r) == 5)
1101 { $output .= '</b><i>'; $state = 'i'; }
1102 else if ($state == 'i')
1103 { $output .= '</i><b>'; $state = 'b'; }
1104 else if ($state == 'bi')
1105 { $output .= '</i></b>'; $state = ''; }
1106 else if ($state == 'ib')
1107 { $output .= '</b></i>'; $state = ''; }
1108 else if ($state == 'both')
1109 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1110 else # ($state == '')
1111 { $buffer = ''; $state = 'both'; }
1116 # Now close all remaining tags. Notice that the order is important.
1117 if ($state == 'b' ||
$state == 'ib')
1119 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1123 if ($state == 'both')
1124 $output .= '<b><i>'.$buffer.'</i></b>';
1130 * Replace external links
1132 * Note: this is all very hackish and the order of execution matters a lot.
1133 * Make sure to run maintenance/parserTests.php if you change this code.
1137 function replaceExternalLinks( $text ) {
1139 $fname = 'Parser::replaceExternalLinks';
1140 wfProfileIn( $fname );
1142 $sk =& $this->mOptions
->getSkin();
1144 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1146 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1149 while ( $i<count( $bits ) ) {
1151 $protocol = $bits[$i++
];
1152 $text = $bits[$i++
];
1153 $trail = $bits[$i++
];
1155 # The characters '<' and '>' (which were escaped by
1156 # removeHTMLtags()) should not be included in
1157 # URLs, per RFC 2396.
1158 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1159 $text = substr($url, $m2[0][1]) . ' ' . $text;
1160 $url = substr($url, 0, $m2[0][1]);
1163 # If the link text is an image URL, replace it with an <img> tag
1164 # This happened by accident in the original parser, but some people used it extensively
1165 $img = $this->maybeMakeExternalImage( $text );
1166 if ( $img !== false ) {
1172 # Set linktype for CSS - if URL==text, link is essentially free
1173 $linktype = ($text == $url) ?
'free' : 'text';
1175 # No link text, e.g. [http://domain.tld/some.link]
1176 if ( $text == '' ) {
1177 # Autonumber if allowed
1178 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1179 $text = '[' . ++
$this->mAutonumber
. ']';
1180 $linktype = 'autonumber';
1182 # Otherwise just use the URL
1183 $text = htmlspecialchars( $url );
1187 # Have link text, e.g. [http://domain.tld/some.link text]s
1189 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1192 $text = $wgContLang->markNoConversion($text);
1194 # Replace & from obsolete syntax with &.
1195 # All HTML entities will be escaped by makeExternalLink()
1196 $url = str_replace( '&', '&', $url );
1198 # Process the trail (i.e. everything after this link up until start of the next link),
1199 # replacing any non-bracketed links
1200 $trail = $this->replaceFreeExternalLinks( $trail );
1202 # Use the encoded URL
1203 # This means that users can paste URLs directly into the text
1204 # Funny characters like ö aren't valid in URLs anyway
1205 # This was changed in August 2004
1206 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1208 # Register link in the output object.
1209 # Replace unnecessary URL escape codes with the referenced character
1210 # This prevents spammers from hiding links from the filters
1211 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1212 $this->mOutput
->addExternalLink( $pasteurized );
1215 wfProfileOut( $fname );
1220 * Replace anything that looks like a URL with a link
1223 function replaceFreeExternalLinks( $text ) {
1225 $fname = 'Parser::replaceFreeExternalLinks';
1226 wfProfileIn( $fname );
1228 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1229 $s = array_shift( $bits );
1232 $sk =& $this->mOptions
->getSkin();
1234 while ( $i < count( $bits ) ){
1235 $protocol = $bits[$i++
];
1236 $remainder = $bits[$i++
];
1238 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1239 # Found some characters after the protocol that look promising
1240 $url = $protocol . $m[1];
1243 # special case: handle urls as url args:
1244 # http://www.example.com/foo?=http://www.example.com/bar
1245 if(strlen($trail) == 0 &&
1247 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1248 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1251 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1256 # The characters '<' and '>' (which were escaped by
1257 # removeHTMLtags()) should not be included in
1258 # URLs, per RFC 2396.
1259 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1260 $trail = substr($url, $m2[0][1]) . $trail;
1261 $url = substr($url, 0, $m2[0][1]);
1264 # Move trailing punctuation to $trail
1266 # If there is no left bracket, then consider right brackets fair game too
1267 if ( strpos( $url, '(' ) === false ) {
1271 $numSepChars = strspn( strrev( $url ), $sep );
1272 if ( $numSepChars ) {
1273 $trail = substr( $url, -$numSepChars ) . $trail;
1274 $url = substr( $url, 0, -$numSepChars );
1277 # Replace & from obsolete syntax with &.
1278 # All HTML entities will be escaped by makeExternalLink()
1279 # or maybeMakeExternalImage()
1280 $url = str_replace( '&', '&', $url );
1282 # Is this an external image?
1283 $text = $this->maybeMakeExternalImage( $url );
1284 if ( $text === false ) {
1285 # Not an image, make a link
1286 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1287 # Register it in the output object...
1288 # Replace unnecessary URL escape codes with their equivalent characters
1289 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1290 $this->mOutput
->addExternalLink( $pasteurized );
1292 $s .= $text . $trail;
1294 $s .= $protocol . $remainder;
1297 wfProfileOut( $fname );
1302 * Replace unusual URL escape codes with their equivalent characters
1306 * @fixme This can merge genuinely required bits in the path or query string,
1307 * breaking legit URLs. A proper fix would treat the various parts of
1308 * the URL differently; as a workaround, just use the output for
1309 * statistical records, not for actual linking/output.
1311 function replaceUnusualEscapes( $url ) {
1312 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1313 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1317 * Callback function used in replaceUnusualEscapes().
1318 * Replaces unusual URL escape codes with their equivalent character
1322 function replaceUnusualEscapesCallback( $matches ) {
1323 $char = urldecode( $matches[0] );
1324 $ord = ord( $char );
1325 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1326 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1327 // No, shouldn't be escaped
1330 // Yes, leave it escaped
1336 * make an image if it's allowed, either through the global
1337 * option or through the exception
1340 function maybeMakeExternalImage( $url ) {
1341 $sk =& $this->mOptions
->getSkin();
1342 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1343 $imagesexception = !empty($imagesfrom);
1345 if ( $this->mOptions
->getAllowExternalImages()
1346 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1347 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1349 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1356 * Process [[ ]] wikilinks
1360 function replaceInternalLinks( $s ) {
1362 static $fname = 'Parser::replaceInternalLinks' ;
1364 wfProfileIn( $fname );
1366 wfProfileIn( $fname.'-setup' );
1368 # the % is needed to support urlencoded titles as well
1369 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1371 $sk =& $this->mOptions
->getSkin();
1373 #split the entire text string on occurences of [[
1374 $a = explode( '[[', ' ' . $s );
1375 #get the first element (all text up to first [[), and remove the space we added
1376 $s = array_shift( $a );
1377 $s = substr( $s, 1 );
1379 # Match a link having the form [[namespace:link|alternate]]trail
1381 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1382 # Match cases where there is no "]]", which might still be images
1383 static $e1_img = FALSE;
1384 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1385 # Match the end of a line for a word that's not followed by whitespace,
1386 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1387 $e2 = wfMsgForContent( 'linkprefix' );
1389 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1391 if( is_null( $this->mTitle
) ) {
1392 wfDebugDieBacktrace( 'nooo' );
1394 $nottalk = !$this->mTitle
->isTalkPage();
1396 if ( $useLinkPrefixExtension ) {
1397 if ( preg_match( $e2, $s, $m ) ) {
1398 $first_prefix = $m[2];
1400 $first_prefix = false;
1406 $selflink = $this->mTitle
->getPrefixedText();
1407 wfProfileOut( $fname.'-setup' );
1409 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1410 $useSubpages = $this->areSubpagesAllowed();
1412 # Loop for each link
1413 for ($k = 0; isset( $a[$k] ); $k++
) {
1415 if ( $useLinkPrefixExtension ) {
1416 wfProfileIn( $fname.'-prefixhandling' );
1417 if ( preg_match( $e2, $s, $m ) ) {
1425 $prefix = $first_prefix;
1426 $first_prefix = false;
1428 wfProfileOut( $fname.'-prefixhandling' );
1431 $might_be_img = false;
1433 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1435 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1436 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1437 # the real problem is with the $e1 regex
1440 # Still some problems for cases where the ] is meant to be outside punctuation,
1441 # and no image is in sight. See bug 2095.
1444 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1445 strpos($text, '[') !== false
1448 $text .= ']'; # so that replaceExternalLinks($text) works later
1451 # fix up urlencoded title texts
1452 if(preg_match('/%/', $m[1] ))
1453 # Should anchors '#' also be rejected?
1454 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1456 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1457 $might_be_img = true;
1459 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1461 } else { # Invalid form; output directly
1462 $s .= $prefix . '[[' . $line ;
1466 # Don't allow internal links to pages containing
1467 # PROTO: where PROTO is a valid URL protocol; these
1468 # should be external links.
1469 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1470 $s .= $prefix . '[[' . $line ;
1474 # Make subpage if necessary
1475 if( $useSubpages ) {
1476 $link = $this->maybeDoSubpageLink( $m[1], $text );
1481 $noforce = (substr($m[1], 0, 1) != ':');
1483 # Strip off leading ':'
1484 $link = substr($link, 1);
1487 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1489 $s .= $prefix . '[[' . $line;
1493 #check other language variants of the link
1494 #if the article does not exist
1495 if( $checkVariantLink
1496 && $nt->getArticleID() == 0 ) {
1497 $wgContLang->findVariantLink($link, $nt);
1500 $ns = $nt->getNamespace();
1501 $iw = $nt->getInterWiki();
1503 if ($might_be_img) { # if this is actually an invalid link
1504 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1506 while (isset ($a[$k+
1]) ) {
1507 #look at the next 'line' to see if we can close it there
1508 $spliced = array_splice( $a, $k +
1, 1 );
1509 $next_line = array_shift( $spliced );
1510 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1511 # the first ]] closes the inner link, the second the image
1513 $text .= '[[' . $m[1];
1516 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1517 #if there's exactly one ]] that's fine, we'll keep looking
1518 $text .= '[[' . $m[0];
1520 #if $next_line is invalid too, we need look no further
1521 $text .= '[[' . $next_line;
1526 # we couldn't find the end of this imageLink, so output it raw
1527 #but don't ignore what might be perfectly normal links in the text we've examined
1528 $text = $this->replaceInternalLinks($text);
1529 $s .= $prefix . '[[' . $link . '|' . $text;
1530 # note: no $trail, because without an end, there *is* no trail
1533 } else { #it's not an image, so output it raw
1534 $s .= $prefix . '[[' . $link . '|' . $text;
1535 # note: no $trail, because without an end, there *is* no trail
1540 $wasblank = ( '' == $text );
1541 if( $wasblank ) $text = $link;
1544 # Link not escaped by : , create the various objects
1548 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1549 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1550 $s = rtrim($s . "\n");
1551 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1555 if ( $ns == NS_IMAGE
) {
1556 wfProfileIn( "$fname-image" );
1557 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1558 # recursively parse links inside the image caption
1559 # actually, this will parse them in any other parameters, too,
1560 # but it might be hard to fix that, and it doesn't matter ATM
1561 $text = $this->replaceExternalLinks($text);
1562 $text = $this->replaceInternalLinks($text);
1564 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1565 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1566 $this->mOutput
->addImage( $nt->getDBkey() );
1568 wfProfileOut( "$fname-image" );
1571 wfProfileOut( "$fname-image" );
1575 if ( $ns == NS_CATEGORY
) {
1576 wfProfileIn( "$fname-category" );
1577 $s = rtrim($s . "\n"); # bug 87
1580 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1581 $sortkey = $this->mTitle
->getText();
1583 $sortkey = $this->mTitle
->getPrefixedText();
1588 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1589 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1590 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1593 * Strip the whitespace Category links produce, see bug 87
1594 * @todo We might want to use trim($tmp, "\n") here.
1596 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1598 wfProfileOut( "$fname-category" );
1603 if( ( $nt->getPrefixedText() === $selflink ) &&
1604 ( $nt->getFragment() === '' ) ) {
1605 # Self-links are handled specially; generally de-link and change to bold.
1606 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1610 # Special and Media are pseudo-namespaces; no pages actually exist in them
1611 if( $ns == NS_MEDIA
) {
1612 $link = $sk->makeMediaLinkObj( $nt, $text );
1613 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1614 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1615 $this->mOutput
->addImage( $nt->getDBkey() );
1617 } elseif( $ns == NS_SPECIAL
) {
1618 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1620 } elseif( $ns == NS_IMAGE
) {
1621 $img = Image
::newFromTitle( $nt );
1622 if( $img->exists() ) {
1623 // Force a blue link if the file exists; may be a remote
1624 // upload on the shared repository, and we want to see its
1625 // auto-generated page.
1626 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1630 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1632 wfProfileOut( $fname );
1637 * Make a link placeholder. The text returned can be later resolved to a real link with
1638 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1639 * parsing of interwiki links, and secondly to allow all extistence checks and
1640 * article length checks (for stub links) to be bundled into a single query.
1643 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1644 if ( ! is_object($nt) ) {
1646 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1648 # Separate the link trail from the rest of the link
1649 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1651 if ( $nt->isExternal() ) {
1652 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1653 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1654 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1656 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1657 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1658 $this->mLinkHolders
['queries'][] = $query;
1659 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1660 $this->mLinkHolders
['titles'][] = $nt;
1662 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1669 * Render a forced-blue link inline; protect against double expansion of
1670 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1671 * Since this little disaster has to split off the trail text to avoid
1672 * breaking URLs in the following text without breaking trails on the
1673 * wiki links, it's been made into a horrible function.
1676 * @param string $text
1677 * @param string $query
1678 * @param string $trail
1679 * @param string $prefix
1680 * @return string HTML-wikitext mix oh yuck
1682 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1683 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1684 $sk =& $this->mOptions
->getSkin();
1685 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1686 return $this->armorLinks( $link ) . $trail;
1690 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1691 * going to go through further parsing steps before inline URL expansion.
1693 * In particular this is important when using action=render, which causes
1694 * full URLs to be included.
1696 * Oh man I hate our multi-layer parser!
1698 * @param string more-or-less HTML
1699 * @return string less-or-more HTML with NOPARSE bits
1701 function armorLinks( $text ) {
1702 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1703 "{$this->mUniqPrefix}NOPARSE$1", $text );
1707 * Return true if subpage links should be expanded on this page.
1710 function areSubpagesAllowed() {
1711 # Some namespaces don't allow subpages
1712 global $wgNamespacesWithSubpages;
1713 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1717 * Handle link to subpage if necessary
1718 * @param string $target the source of the link
1719 * @param string &$text the link text, modified as necessary
1720 * @return string the full name of the link
1723 function maybeDoSubpageLink($target, &$text) {
1726 # :Foobar -- override special treatment of prefix (images, language links)
1727 # /Foobar -- convert to CurrentPage/Foobar
1728 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1729 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1730 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1732 $fname = 'Parser::maybeDoSubpageLink';
1733 wfProfileIn( $fname );
1734 $ret = $target; # default return value is no change
1736 # Some namespaces don't allow subpages,
1737 # so only perform processing if subpages are allowed
1738 if( $this->areSubpagesAllowed() ) {
1739 # Look at the first character
1740 if( $target != '' && $target{0} == '/' ) {
1741 # / at end means we don't want the slash to be shown
1742 if( substr( $target, -1, 1 ) == '/' ) {
1743 $target = substr( $target, 1, -1 );
1746 $noslash = substr( $target, 1 );
1749 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1750 if( '' === $text ) {
1752 } # this might be changed for ugliness reasons
1754 # check for .. subpage backlinks
1756 $nodotdot = $target;
1757 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1759 $nodotdot = substr( $nodotdot, 3 );
1761 if($dotdotcount > 0) {
1762 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1763 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1764 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1765 # / at the end means don't show full path
1766 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1767 $nodotdot = substr( $nodotdot, 0, -1 );
1768 if( '' === $text ) {
1772 $nodotdot = trim( $nodotdot );
1773 if( $nodotdot != '' ) {
1774 $ret .= '/' . $nodotdot;
1781 wfProfileOut( $fname );
1786 * Used by doBlockLevels()
1789 /* private */ function closeParagraph() {
1791 if ( '' != $this->mLastSection
) {
1792 $result = '</' . $this->mLastSection
. ">\n";
1794 $this->mInPre
= false;
1795 $this->mLastSection
= '';
1798 # getCommon() returns the length of the longest common substring
1799 # of both arguments, starting at the beginning of both.
1801 /* private */ function getCommon( $st1, $st2 ) {
1802 $fl = strlen( $st1 );
1803 $shorter = strlen( $st2 );
1804 if ( $fl < $shorter ) { $shorter = $fl; }
1806 for ( $i = 0; $i < $shorter; ++
$i ) {
1807 if ( $st1{$i} != $st2{$i} ) { break; }
1811 # These next three functions open, continue, and close the list
1812 # element appropriate to the prefix character passed into them.
1814 /* private */ function openList( $char ) {
1815 $result = $this->closeParagraph();
1817 if ( '*' == $char ) { $result .= '<ul><li>'; }
1818 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1819 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1820 else if ( ';' == $char ) {
1821 $result .= '<dl><dt>';
1822 $this->mDTopen
= true;
1824 else { $result = '<!-- ERR 1 -->'; }
1829 /* private */ function nextItem( $char ) {
1830 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1831 else if ( ':' == $char ||
';' == $char ) {
1833 if ( $this->mDTopen
) { $close = '</dt>'; }
1834 if ( ';' == $char ) {
1835 $this->mDTopen
= true;
1836 return $close . '<dt>';
1838 $this->mDTopen
= false;
1839 return $close . '<dd>';
1842 return '<!-- ERR 2 -->';
1845 /* private */ function closeList( $char ) {
1846 if ( '*' == $char ) { $text = '</li></ul>'; }
1847 else if ( '#' == $char ) { $text = '</li></ol>'; }
1848 else if ( ':' == $char ) {
1849 if ( $this->mDTopen
) {
1850 $this->mDTopen
= false;
1851 $text = '</dt></dl>';
1853 $text = '</dd></dl>';
1856 else { return '<!-- ERR 3 -->'; }
1862 * Make lists from lines starting with ':', '*', '#', etc.
1865 * @return string the lists rendered as HTML
1867 function doBlockLevels( $text, $linestart ) {
1868 $fname = 'Parser::doBlockLevels';
1869 wfProfileIn( $fname );
1871 # Parsing through the text line by line. The main thing
1872 # happening here is handling of block-level elements p, pre,
1873 # and making lists from lines starting with * # : etc.
1875 $textLines = explode( "\n", $text );
1877 $lastPrefix = $output = '';
1878 $this->mDTopen
= $inBlockElem = false;
1880 $paragraphStack = false;
1882 if ( !$linestart ) {
1883 $output .= array_shift( $textLines );
1885 foreach ( $textLines as $oLine ) {
1886 $lastPrefixLength = strlen( $lastPrefix );
1887 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1888 $preOpenMatch = preg_match('/<pre/i', $oLine );
1889 if ( !$this->mInPre
) {
1890 # Multiple prefixes may abut each other for nested lists.
1891 $prefixLength = strspn( $oLine, '*#:;' );
1892 $pref = substr( $oLine, 0, $prefixLength );
1895 $pref2 = str_replace( ';', ':', $pref );
1896 $t = substr( $oLine, $prefixLength );
1897 $this->mInPre
= !empty($preOpenMatch);
1899 # Don't interpret any other prefixes in preformatted text
1901 $pref = $pref2 = '';
1906 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1907 # Same as the last item, so no need to deal with nesting or opening stuff
1908 $output .= $this->nextItem( substr( $pref, -1 ) );
1909 $paragraphStack = false;
1911 if ( substr( $pref, -1 ) == ';') {
1912 # The one nasty exception: definition lists work like this:
1913 # ; title : definition text
1914 # So we check for : in the remainder text to split up the
1915 # title and definition, without b0rking links.
1917 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1919 $output .= $term . $this->nextItem( ':' );
1922 } elseif( $prefixLength ||
$lastPrefixLength ) {
1923 # Either open or close a level...
1924 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1925 $paragraphStack = false;
1927 while( $commonPrefixLength < $lastPrefixLength ) {
1928 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1929 --$lastPrefixLength;
1931 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1932 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1934 while ( $prefixLength > $commonPrefixLength ) {
1935 $char = substr( $pref, $commonPrefixLength, 1 );
1936 $output .= $this->openList( $char );
1938 if ( ';' == $char ) {
1939 # FIXME: This is dupe of code above
1940 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1942 $output .= $term . $this->nextItem( ':' );
1945 ++
$commonPrefixLength;
1947 $lastPrefix = $pref2;
1949 if( 0 == $prefixLength ) {
1950 wfProfileIn( "$fname-paragraph" );
1951 # No prefix (not in list)--go to paragraph mode
1952 // XXX: use a stack for nestable elements like span, table and div
1953 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1954 $closematch = preg_match(
1955 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1956 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1957 if ( $openmatch or $closematch ) {
1958 $paragraphStack = false;
1959 #Â TODO bug 5718: paragraph closed
1960 $output .= $this->closeParagraph();
1961 if ( $preOpenMatch and !$preCloseMatch ) {
1962 $this->mInPre
= true;
1964 if ( $closematch ) {
1965 $inBlockElem = false;
1967 $inBlockElem = true;
1969 } else if ( !$inBlockElem && !$this->mInPre
) {
1970 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1972 if ($this->mLastSection
!= 'pre') {
1973 $paragraphStack = false;
1974 $output .= $this->closeParagraph().'<pre>';
1975 $this->mLastSection
= 'pre';
1977 $t = substr( $t, 1 );
1980 if ( '' == trim($t) ) {
1981 if ( $paragraphStack ) {
1982 $output .= $paragraphStack.'<br />';
1983 $paragraphStack = false;
1984 $this->mLastSection
= 'p';
1986 if ($this->mLastSection
!= 'p' ) {
1987 $output .= $this->closeParagraph();
1988 $this->mLastSection
= '';
1989 $paragraphStack = '<p>';
1991 $paragraphStack = '</p><p>';
1995 if ( $paragraphStack ) {
1996 $output .= $paragraphStack;
1997 $paragraphStack = false;
1998 $this->mLastSection
= 'p';
1999 } else if ($this->mLastSection
!= 'p') {
2000 $output .= $this->closeParagraph().'<p>';
2001 $this->mLastSection
= 'p';
2006 wfProfileOut( "$fname-paragraph" );
2008 // somewhere above we forget to get out of pre block (bug 785)
2009 if($preCloseMatch && $this->mInPre
) {
2010 $this->mInPre
= false;
2012 if ($paragraphStack === false) {
2016 while ( $prefixLength ) {
2017 $output .= $this->closeList( $pref2{$prefixLength-1} );
2020 if ( '' != $this->mLastSection
) {
2021 $output .= '</' . $this->mLastSection
. '>';
2022 $this->mLastSection
= '';
2025 wfProfileOut( $fname );
2030 * Split up a string on ':', ignoring any occurences inside
2031 * <a>..</a> or <span>...</span>
2032 * @param string $str the string to split
2033 * @param string &$before set to everything before the ':'
2034 * @param string &$after set to everything after the ':'
2035 * return string the position of the ':', or false if none found
2037 function findColonNoLinks($str, &$before, &$after) {
2038 # I wonder if we should make this count all tags, not just <a>
2039 # and <span>. That would prevent us from matching a ':' that
2040 # comes in the middle of italics other such formatting....
2042 $fname = 'Parser::findColonNoLinks';
2043 wfProfileIn( $fname );
2046 $colon = strpos($str, ':', $pos);
2048 if ($colon !== false) {
2049 $before = substr($str, 0, $colon);
2050 $after = substr($str, $colon +
1);
2052 # Skip any ':' within <a> or <span> pairs
2053 $a = substr_count($before, '<a');
2054 $s = substr_count($before, '<span');
2055 $ca = substr_count($before, '</a>');
2056 $cs = substr_count($before, '</span>');
2058 if ($a <= $ca and $s <= $cs) {
2059 # Tags are balanced before ':'; ok
2064 } while ($colon !== false);
2065 wfProfileOut( $fname );
2070 * Return value of a magic variable (like PAGENAME)
2074 function getVariableValue( $index ) {
2075 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2078 * Some of these require message or data lookups and can be
2079 * expensive to check many times.
2081 static $varCache = array();
2082 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2083 if ( isset( $varCache[$index] ) )
2084 return $varCache[$index];
2087 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2090 case MAG_CURRENTMONTH
:
2091 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2092 case MAG_CURRENTMONTHNAME
:
2093 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2094 case MAG_CURRENTMONTHNAMEGEN
:
2095 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2096 case MAG_CURRENTMONTHABBREV
:
2097 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2098 case MAG_CURRENTDAY
:
2099 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2100 case MAG_CURRENTDAY2
:
2101 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2103 return $this->mTitle
->getText();
2105 return $this->mTitle
->getPartialURL();
2106 case MAG_FULLPAGENAME
:
2107 return $this->mTitle
->getPrefixedText();
2108 case MAG_FULLPAGENAMEE
:
2109 return $this->mTitle
->getPrefixedURL();
2110 case MAG_SUBPAGENAME
:
2111 return $this->mTitle
->getSubpageText();
2112 case MAG_SUBPAGENAMEE
:
2113 return $this->mTitle
->getSubpageUrlForm();
2114 case MAG_TALKPAGENAME
:
2115 if( $this->mTitle
->canTalk() ) {
2116 $talkPage = $this->mTitle
->getTalkPage();
2117 return $talkPage->getPrefixedText();
2121 case MAG_TALKPAGENAMEE
:
2122 if( $this->mTitle
->canTalk() ) {
2123 $talkPage = $this->mTitle
->getTalkPage();
2124 return $talkPage->getPrefixedUrl();
2128 case MAG_SUBJECTPAGENAME
:
2129 $subjPage = $this->mTitle
->getSubjectPage();
2130 return $subjPage->getPrefixedText();
2131 case MAG_SUBJECTPAGENAMEE
:
2132 $subjPage = $this->mTitle
->getSubjectPage();
2133 return $subjPage->getPrefixedUrl();
2134 case MAG_REVISIONID
:
2135 return $this->mRevisionId
;
2137 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2138 case MAG_NAMESPACEE
:
2139 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2141 return $this->mTitle
->canTalk() ?
$this->mTitle
->getTalkNsText() : '';
2142 case MAG_TALKSPACEE
:
2143 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2144 case MAG_SUBJECTSPACE
:
2145 return $this->mTitle
->getSubjectNsText();
2146 case MAG_SUBJECTSPACEE
:
2147 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2148 case MAG_CURRENTDAYNAME
:
2149 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2150 case MAG_CURRENTYEAR
:
2151 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2152 case MAG_CURRENTTIME
:
2153 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2154 case MAG_CURRENTWEEK
:
2155 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2156 // int to remove the padding
2157 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2158 case MAG_CURRENTDOW
:
2159 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2160 case MAG_NUMBEROFARTICLES
:
2161 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2162 case MAG_NUMBEROFFILES
:
2163 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2164 case MAG_NUMBEROFUSERS
:
2165 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2170 case MAG_SERVERNAME
:
2171 return $wgServerName;
2172 case MAG_SCRIPTPATH
:
2173 return $wgScriptPath;
2176 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2184 * initialise the magic variables (like CURRENTMONTHNAME)
2188 function initialiseVariables() {
2189 $fname = 'Parser::initialiseVariables';
2190 wfProfileIn( $fname );
2191 global $wgVariableIDs;
2192 $this->mVariables
= array();
2193 foreach ( $wgVariableIDs as $id ) {
2194 $mw =& MagicWord
::get( $id );
2195 $mw->addToArray( $this->mVariables
, $id );
2197 wfProfileOut( $fname );
2201 * parse any parentheses in format ((title|part|part))
2202 * and call callbacks to get a replacement text for any found piece
2204 * @param string $text The text to parse
2205 * @param array $callbacks rules in form:
2206 * '{' => array( # opening parentheses
2207 * 'end' => '}', # closing parentheses
2208 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2209 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2214 function replace_callback ($text, $callbacks) {
2215 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2216 $lastOpeningBrace = -1; # last not closed parentheses
2218 for ($i = 0; $i < strlen($text); $i++
) {
2219 # check for any opening brace
2222 foreach ($callbacks as $key => $value) {
2223 $pos = strpos ($text, $key, $i);
2224 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2230 if ($lastOpeningBrace >= 0) {
2231 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2233 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2238 $pos = strpos ($text, '|', $i);
2240 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2251 # found openning brace, lets add it to parentheses stack
2252 if (null != $rule) {
2253 $piece = array('brace' => $text[$i],
2254 'braceEnd' => $rule['end'],
2259 # count openning brace characters
2260 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2265 $piece['startAt'] = $i+
1;
2266 $piece['partStart'] = $i+
1;
2268 # we need to add to stack only if openning brace count is enough for any given rule
2269 foreach ($rule['cb'] as $cnt => $fn) {
2270 if ($piece['count'] >= $cnt) {
2271 $lastOpeningBrace ++
;
2272 $openingBraceStack[$lastOpeningBrace] = $piece;
2279 else if ($lastOpeningBrace >= 0) {
2280 # first check if it is a closing brace
2281 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2282 # lets check if it is enough characters for closing brace
2284 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2287 # if there are more closing parentheses than opening ones, we parse less
2288 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2289 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2291 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2293 $matchingCallback = null;
2294 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2295 if ($count >= $cnt && $matchingCount < $cnt) {
2296 $matchingCount = $cnt;
2297 $matchingCallback = $fn;
2301 if ($matchingCount == 0) {
2306 # lets set a title or last part (if '|' was found)
2307 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2308 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2310 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2312 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2313 $pieceEnd = $i +
$matchingCount;
2315 if( is_callable( $matchingCallback ) ) {
2317 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2318 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2319 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2320 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2322 # finally we can call a user callback and replace piece of text
2323 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2324 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2325 $i = $pieceStart +
strlen($replaceWith) - 1;
2328 # null value for callback means that parentheses should be parsed, but not replaced
2329 $i +
= $matchingCount - 1;
2332 # reset last openning parentheses, but keep it in case there are unused characters
2333 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2334 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2335 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2338 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2339 $openingBraceStack[$lastOpeningBrace--] = null;
2341 if ($matchingCount < $piece['count']) {
2342 $piece['count'] -= $matchingCount;
2343 $piece['startAt'] -= $matchingCount;
2344 $piece['partStart'] = $piece['startAt'];
2345 # do we still qualify for any callback with remaining count?
2346 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2347 if ($piece['count'] >= $cnt) {
2348 $lastOpeningBrace ++
;
2349 $openingBraceStack[$lastOpeningBrace] = $piece;
2357 # lets set a title if it is a first separator, or next part otherwise
2358 if ($text[$i] == '|') {
2359 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2360 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2361 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2364 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2366 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2375 * Replace magic variables, templates, and template arguments
2376 * with the appropriate text. Templates are substituted recursively,
2377 * taking care to avoid infinite loops.
2379 * Note that the substitution depends on value of $mOutputType:
2380 * OT_WIKI: only {{subst:}} templates
2381 * OT_MSG: only magic variables
2382 * OT_HTML: all templates and magic variables
2384 * @param string $tex The text to transform
2385 * @param array $args Key-value pairs representing template parameters to substitute
2386 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2389 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2390 # Prevent too big inclusions
2391 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2395 $fname = 'Parser::replaceVariables';
2396 wfProfileIn( $fname );
2398 # This function is called recursively. To keep track of arguments we need a stack:
2399 array_push( $this->mArgStack
, $args );
2401 $braceCallbacks = array();
2403 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2405 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2406 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2408 $callbacks = array();
2409 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2410 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2411 $text = $this->replace_callback ($text, $callbacks);
2413 array_pop( $this->mArgStack
);
2415 wfProfileOut( $fname );
2420 * Replace magic variables
2423 function variableSubstitution( $matches ) {
2424 $fname = 'Parser::variableSubstitution';
2425 $varname = $matches[1];
2426 wfProfileIn( $fname );
2427 if ( !$this->mVariables
) {
2428 $this->initialiseVariables();
2431 if ( $this->mOutputType
== OT_WIKI
) {
2432 # Do only magic variables prefixed by SUBST
2433 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2434 if (!$mwSubst->matchStartAndRemove( $varname ))
2436 # Note that if we don't substitute the variable below,
2437 # we don't remove the {{subst:}} magic word, in case
2438 # it is a template rather than a magic variable.
2440 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2441 $id = $this->mVariables
[$varname];
2442 $text = $this->getVariableValue( $id );
2443 $this->mOutput
->mContainsOldMagic
= true;
2445 $text = $matches[0];
2447 wfProfileOut( $fname );
2451 # Split template arguments
2452 function getTemplateArgs( $argsString ) {
2453 if ( $argsString === '' ) {
2457 $args = explode( '|', substr( $argsString, 1 ) );
2459 # If any of the arguments contains a '[[' but no ']]', it needs to be
2460 # merged with the next arg because the '|' character between belongs
2461 # to the link syntax and not the template parameter syntax.
2462 $argc = count($args);
2464 for ( $i = 0; $i < $argc-1; $i++
) {
2465 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2466 $args[$i] .= '|'.$args[$i+
1];
2467 array_splice($args, $i+
1, 1);
2477 * Return the text of a template, after recursively
2478 * replacing any variables or templates within the template.
2480 * @param array $piece The parts of the template
2481 * $piece['text']: matched text
2482 * $piece['title']: the title, i.e. the part before the |
2483 * $piece['parts']: the parameter array
2484 * @return string the text of the template
2487 function braceSubstitution( $piece ) {
2488 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2489 $fname = 'Parser::braceSubstitution';
2490 wfProfileIn( $fname );
2493 $found = false; # $text has been filled
2494 $nowiki = false; # wiki markup in $text should be escaped
2495 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2496 $noargs = false; # Don't replace triple-brace arguments in $text
2497 $replaceHeadings = false; # Make the edit section links go to the template not the article
2498 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2499 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2501 # Title object, where $text came from
2506 # $part1 is the bit before the first |, and must contain only title characters
2507 # $args is a list of arguments, starting from index 0, not including $part1
2509 $part1 = $piece['title'];
2510 # If the third subpattern matched anything, it will start with |
2512 if (null == $piece['parts']) {
2513 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2514 if ($replaceWith != $piece['text']) {
2515 $text = $replaceWith;
2522 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2523 $argc = count( $args );
2527 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2528 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2529 # One of two possibilities is true:
2530 # 1) Found SUBST but not in the PST phase
2531 # 2) Didn't find SUBST and in the PST phase
2532 # In either case, return without further processing
2533 $text = $piece['text'];
2540 # MSG, MSGNW, INT and RAW
2543 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2544 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2547 # Remove obsolete MSG:
2548 $mwMsg =& MagicWord
::get( MAG_MSG
);
2549 $mwMsg->matchStartAndRemove( $part1 );
2553 $mwRaw =& MagicWord
::get( MAG_RAW
);
2554 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2555 $forceRawInterwiki = true;
2558 # Check if it is an internal message
2559 $mwInt =& MagicWord
::get( MAG_INT
);
2560 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2561 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2562 $text = $linestart . wfMsgReal( $part1, $args, true );
2570 # Check for NS: (namespace expansion)
2571 $mwNs = MagicWord
::get( MAG_NS
);
2572 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2573 if ( intval( $part1 ) ||
$part1 == "0" ) {
2574 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2577 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2578 if ( !is_null( $index ) ) {
2579 $text = $linestart . $wgContLang->getNsText( $index );
2586 # LCFIRST, UCFIRST, LC and UC
2588 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2589 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2590 $lc =& MagicWord
::get( MAG_LC
);
2591 $uc =& MagicWord
::get( MAG_UC
);
2592 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2593 $text = $linestart . $wgContLang->lcfirst( $part1 );
2595 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2596 $text = $linestart . $wgContLang->ucfirst( $part1 );
2598 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2599 $text = $linestart . $wgContLang->lc( $part1 );
2601 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2602 $text = $linestart . $wgContLang->uc( $part1 );
2607 # LOCALURL and FULLURL
2609 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2610 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2611 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2612 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2615 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2616 $func = 'getLocalURL';
2617 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2618 $func = 'escapeLocalURL';
2619 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2620 $func = 'getFullURL';
2621 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2622 $func = 'escapeFullURL';
2627 if ( $func !== false ) {
2628 $title = Title
::newFromText( $part1 );
2629 if ( !is_null( $title ) ) {
2631 $text = $linestart . $title->$func( $args[0] );
2633 $text = $linestart . $title->$func();
2640 $lang = $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
2642 if ( !$found && $argc == 1 ) {
2643 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2644 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2645 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2651 if ( !$found && $argc >= 2 ) {
2652 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2653 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2654 if ($argc==2) {$args[2]=$args[1];}
2655 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2661 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2662 $mwDT =& MagicWord
::get( MAG_DISPLAYTITLE
);
2663 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2665 # Set title in parser output object
2667 $parserOptions = new ParserOptions
;
2668 $local_parser = new Parser ();
2669 $t2 = $local_parser->parse ( $param, $this->mTitle
, $parserOptions, false );
2670 $this->mOutput
->mHTMLtitle
= $t2->GetText();
2673 $t = $this->mTitle
->getPrefixedText();
2674 $this->mOutput
->mSubtitle
.= wfMsg('displaytitle', $t);
2680 # NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2682 $mwWordsToCheck = array( MAG_NUMBEROFUSERS
=> 'wfNumberOfUsers', MAG_NUMBEROFARTICLES
=> 'wfNumberOfArticles', MAG_NUMBEROFFILES
=> 'wfNumberOfFiles' );
2683 foreach( $mwWordsToCheck as $word => $func ) {
2684 $mwCurrentWord =& MagicWord
::get( $word );
2685 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2686 $mwRawSuffix =& MagicWord
::get( MAG_RAWSUFFIX
);
2687 if( $mwRawSuffix->match( $args[0] ) ) {
2688 # Raw and unformatted
2689 $text = $linestart . call_user_func( $func );
2691 # Formatted according to the content default
2692 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2700 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2701 $colonPos = strpos( $part1, ':' );
2702 if ( $colonPos !== false ) {
2703 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2704 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2705 $funcArgs = array_map( 'trim', $args );
2706 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2707 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2710 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2714 if ( is_array( $result ) ) {
2715 $text = $linestart . $result[0];
2716 unset( $result[0] );
2718 // Extract flags into the local scope
2719 // This allows callers to set flags such as nowiki, noparse, found, etc.
2722 $text = $linestart . $result;
2728 # Template table test
2730 # Did we encounter this template already? If yes, it is in the cache
2731 # and we need to check for loops.
2732 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2735 # Infinite loop test
2736 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2740 $text = $linestart .
2741 '{{' . $part1 . '}}' .
2742 '<!-- WARNING: template loop detected -->';
2743 wfDebug( "$fname: template loop broken at '$part1'\n" );
2745 # set $text to cached message.
2746 $text = $linestart . $this->mTemplates
[$piece['title']];
2750 # Load from database
2751 $lastPathLevel = $this->mTemplatePath
;
2754 # declaring $subpage directly in the function call
2755 # does not work correctly with references and breaks
2756 # {{/subpage}}-style inclusions
2758 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2759 if ($subpage !== '') {
2760 $ns = $this->mTitle
->getNamespace();
2762 $title = Title
::newFromText( $part1, $ns );
2764 if ( !is_null( $title ) ) {
2765 if ( !$title->isExternal() ) {
2766 # Check for excessive inclusion
2767 $dbk = $title->getPrefixedDBkey();
2768 if ( $this->incrementIncludeCount( $dbk ) ) {
2769 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2770 $text = SpecialPage
::capturePath( $title );
2771 if ( is_string( $text ) ) {
2776 $this->disableCache();
2779 $articleContent = $this->fetchTemplate( $title );
2780 if ( $articleContent !== false ) {
2782 $text = $articleContent;
2783 $replaceHeadings = true;
2788 # If the title is valid but undisplayable, make a link to it
2789 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2790 $text = '[['.$title->getPrefixedText().']]';
2793 } elseif ( $title->isTrans() ) {
2794 // Interwiki transclusion
2795 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2796 $text = $this->interwikiTransclude( $title, 'render' );
2800 $text = $this->interwikiTransclude( $title, 'raw' );
2801 $replaceHeadings = true;
2806 # Template cache array insertion
2807 # Use the original $piece['title'] not the mangled $part1, so that
2808 # modifiers such as RAW: produce separate cache entries
2810 $this->mTemplates
[$piece['title']] = $text;
2811 $text = $linestart . $text;
2816 # Recursive parsing, escaping and link table handling
2817 # Only for HTML output
2818 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2819 $text = wfEscapeWikiText( $text );
2820 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2822 $assocArgs = array();
2824 # Clean up argument array
2825 $assocArgs = array();
2827 foreach( $args as $arg ) {
2828 $eqpos = strpos( $arg, '=' );
2829 if ( $eqpos === false ) {
2830 $assocArgs[$index++
] = $arg;
2832 $name = trim( substr( $arg, 0, $eqpos ) );
2833 $value = trim( substr( $arg, $eqpos+
1 ) );
2834 if ( $value === false ) {
2837 if ( $name !== false ) {
2838 $assocArgs[$name] = $value;
2843 # Add a new element to the templace recursion path
2844 $this->mTemplatePath
[$part1] = 1;
2848 # If there are any <onlyinclude> tags, only include them
2849 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2850 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2852 foreach ($m[1] as $piece)
2855 # Remove <noinclude> sections and <includeonly> tags
2856 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2857 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2859 if( $this->mOutputType
== OT_HTML
) {
2860 # Strip <nowiki>, <pre>, etc.
2861 $text = $this->strip( $text, $this->mStripState
);
2862 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2864 $text = $this->replaceVariables( $text, $assocArgs );
2866 # If the template begins with a table or block-level
2867 # element, it should be treated as beginning a new line.
2868 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2869 $text = "\n" . $text;
2871 } elseif ( !$noargs ) {
2872 # $noparse and !$noargs
2873 # Just replace the arguments, not any double-brace items
2874 # This is used for rendered interwiki transclusion
2875 $text = $this->replaceVariables( $text, $assocArgs, true );
2878 # Prune lower levels off the recursion check path
2879 $this->mTemplatePath
= $lastPathLevel;
2882 wfProfileOut( $fname );
2883 return $piece['text'];
2886 # Replace raw HTML by a placeholder
2887 # Add a blank line preceding, to prevent it from mucking up
2888 # immediately preceding headings
2889 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2891 # replace ==section headers==
2892 # XXX this needs to go away once we have a better parser.
2893 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2894 if( !is_null( $title ) )
2895 $encodedname = base64_encode($title->getPrefixedDBkey());
2897 $encodedname = base64_encode("");
2898 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2899 PREG_SPLIT_DELIM_CAPTURE
);
2902 for( $i = 0; $i < count($m); $i +
= 2 ) {
2904 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2906 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2910 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2911 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2912 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2920 # Prune lower levels off the recursion check path
2921 $this->mTemplatePath
= $lastPathLevel;
2924 wfProfileOut( $fname );
2925 return $piece['text'];
2927 wfProfileOut( $fname );
2933 * Fetch the unparsed text of a template and register a reference to it.
2935 function fetchTemplate( $title ) {
2937 // Loop to fetch the article, with up to 1 redirect
2938 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2939 $rev = Revision
::newFromTitle( $title );
2940 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2944 $text = $rev->getText();
2945 if ( $text === false ) {
2949 $title = Title
::newFromRedirect( $text );
2955 * Transclude an interwiki link.
2957 function interwikiTransclude( $title, $action ) {
2958 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2960 if (!$wgEnableScaryTranscluding)
2961 return wfMsg('scarytranscludedisabled');
2963 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2964 // But we'll handle it generally anyway
2965 if ( $title->getNamespace() ) {
2966 // Use the canonical namespace, which should work anywhere
2967 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2969 $articleName = $title->getDBkey();
2972 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2973 $url .= "?action=$action";
2974 if (strlen($url) > 255)
2975 return wfMsg('scarytranscludetoolong');
2976 return $this->fetchScaryTemplateMaybeFromCache($url);
2979 function fetchScaryTemplateMaybeFromCache($url) {
2980 global $wgTranscludeCacheExpiry;
2981 $dbr =& wfGetDB(DB_SLAVE
);
2982 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2983 array('tc_url' => $url));
2985 $time = $obj->tc_time
;
2986 $text = $obj->tc_contents
;
2987 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2992 $text = wfGetHTTP($url);
2994 return wfMsg('scarytranscludefailed', $url);
2996 $dbw =& wfGetDB(DB_MASTER
);
2997 $dbw->replace('transcache', array('tc_url'), array(
2999 'tc_time' => time(),
3000 'tc_contents' => $text));
3006 * Triple brace replacement -- used for template arguments
3009 function argSubstitution( $matches ) {
3010 $arg = trim( $matches['title'] );
3011 $text = $matches['text'];
3012 $inputArgs = end( $this->mArgStack
);
3014 if ( array_key_exists( $arg, $inputArgs ) ) {
3015 $text = $inputArgs[$arg];
3016 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3017 $text = $matches['parts'][0];
3024 * Returns true if the function is allowed to include this entity
3027 function incrementIncludeCount( $dbk ) {
3028 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3029 $this->mIncludeCount
[$dbk] = 0;
3031 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3039 * This function accomplishes several tasks:
3040 * 1) Auto-number headings if that option is enabled
3041 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3042 * 3) Add a Table of contents on the top for users who have enabled the option
3043 * 4) Auto-anchor headings
3045 * It loops through all headlines, collects the necessary data, then splits up the
3046 * string and re-inserts the newly formatted headlines.
3048 * @param string $text
3049 * @param boolean $isMain
3052 function formatHeadings( $text, $isMain=true ) {
3053 global $wgMaxTocLevel, $wgContLang;
3055 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3057 $forceTocHere = false;
3058 if( !$this->mTitle
->userCanEdit() ) {
3061 $showEditLink = $this->mOptions
->getEditSection();
3064 # Inhibit editsection links if requested in the page
3065 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
3066 if( $esw->matchAndRemove( $text ) ) {
3069 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3071 $mw =& MagicWord
::get( MAG_NOTOC
);
3072 if( $mw->matchAndRemove( $text ) ) {
3076 # Get all headlines for numbering them and adding funky stuff like [edit]
3077 # links - this is for later, but we need the number of headlines right now
3078 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3080 # if there are fewer than 4 headlines in the article, do not show TOC
3081 if( $numMatches < 4 ) {
3085 # Allow user to stipulate that a page should have a "new section"
3086 # link added via __NEWSECTIONLINK__
3087 $mw =& MagicWord
::get( MAG_NEWSECTIONLINK
);
3088 if( $mw->matchAndRemove( $text ) )
3089 $this->mOutput
->setNewSection( true );
3091 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
3092 # override above conditions and always show TOC at that place
3094 $mw =& MagicWord
::get( MAG_TOC
);
3095 if($mw->match( $text ) ) {
3097 $forceTocHere = true;
3099 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3100 # override above conditions and always show TOC above first header
3101 $mw =& MagicWord
::get( MAG_FORCETOC
);
3102 if ($mw->matchAndRemove( $text ) ) {
3107 # Never ever show TOC if no headers
3108 if( $numMatches < 1 ) {
3112 # We need this to perform operations on the HTML
3113 $sk =& $this->mOptions
->getSkin();
3117 $sectionCount = 0; # headlineCount excluding template sections
3119 # Ugh .. the TOC should have neat indentation levels which can be
3120 # passed to the skin functions. These are determined here
3124 $sublevelCount = array();
3125 $levelCount = array();
3132 foreach( $matches[3] as $headline ) {
3134 $templatetitle = '';
3135 $templatesection = 0;
3138 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3140 $templatetitle = base64_decode($mat[1]);
3141 $templatesection = 1 +
(int)base64_decode($mat[2]);
3142 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3146 $prevlevel = $level;
3147 $prevtoclevel = $toclevel;
3149 $level = $matches[1][$headlineCount];
3151 if( $doNumberHeadings ||
$doShowToc ) {
3153 if ( $level > $prevlevel ) {
3154 # Increase TOC level
3156 $sublevelCount[$toclevel] = 0;
3157 if( $toclevel<$wgMaxTocLevel ) {
3158 $toc .= $sk->tocIndent();
3161 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3162 # Decrease TOC level, find level to jump to
3164 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3165 # Can only go down to level 1
3168 for ($i = $toclevel; $i > 0; $i--) {
3169 if ( $levelCount[$i] == $level ) {
3170 # Found last matching level
3174 elseif ( $levelCount[$i] < $level ) {
3175 # Found first matching level below current level
3181 if( $toclevel<$wgMaxTocLevel ) {
3182 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3186 # No change in level, end TOC line
3187 if( $toclevel<$wgMaxTocLevel ) {
3188 $toc .= $sk->tocLineEnd();
3192 $levelCount[$toclevel] = $level;
3194 # count number of headlines for each level
3195 @$sublevelCount[$toclevel]++
;
3197 for( $i = 1; $i <= $toclevel; $i++
) {
3198 if( !empty( $sublevelCount[$i] ) ) {
3202 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3208 # The canonized header is a version of the header text safe to use for links
3209 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3210 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3211 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3213 # Remove link placeholders by the link text.
3214 # <!--LINK number-->
3216 # link text with suffix
3217 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3218 "\$this->mLinkHolders['texts'][\$1]",
3219 $canonized_headline );
3220 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3221 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3222 $canonized_headline );
3225 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3226 $tocline = trim( $canonized_headline );
3227 # Save headline for section edit hint before it's escaped
3228 $headline_hint = trim( $canonized_headline );
3229 $canonized_headline = Sanitizer
::escapeId( $tocline );
3230 $refers[$headlineCount] = $canonized_headline;
3232 # count how many in assoc. array so we can track dupes in anchors
3233 @$refers[$canonized_headline]++
;
3234 $refcount[$headlineCount]=$refers[$canonized_headline];
3236 # Don't number the heading if it is the only one (looks silly)
3237 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3238 # the two are different if the line contains a link
3239 $headline=$numbering . ' ' . $headline;
3242 # Create the anchor for linking from the TOC to the section
3243 $anchor = $canonized_headline;
3244 if($refcount[$headlineCount] > 1 ) {
3245 $anchor .= '_' . $refcount[$headlineCount];
3247 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3248 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3250 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3251 if ( empty( $head[$headlineCount] ) ) {
3252 $head[$headlineCount] = '';
3255 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3257 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3260 # give headline the correct <h#> tag
3261 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3269 if( $toclevel<$wgMaxTocLevel ) {
3270 $toc .= $sk->tocUnindent( $toclevel - 1 );
3272 $toc = $sk->tocList( $toc );
3275 # split up and insert constructed headlines
3277 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3280 foreach( $blocks as $block ) {
3281 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3282 # This is the [edit] link that appears for the top block of text when
3283 # section editing is enabled
3285 # Disabled because it broke block formatting
3286 # For example, a bullet point in the top line
3287 # $full .= $sk->editSectionLink(0);
3290 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3291 # Top anchor now in skin
3295 if( !empty( $head[$i] ) ) {
3301 $mw =& MagicWord
::get( MAG_TOC
);
3302 return $mw->replace( $toc, $full );
3309 * Return an HTML link for the "ISBN 123456" text
3312 function magicISBN( $text ) {
3313 $fname = 'Parser::magicISBN';
3314 wfProfileIn( $fname );
3316 $a = split( 'ISBN ', ' '.$text );
3317 if ( count ( $a ) < 2 ) {
3318 wfProfileOut( $fname );
3321 $text = substr( array_shift( $a ), 1);
3322 $valid = '0123456789-Xx';
3324 foreach ( $a as $x ) {
3325 # hack: don't replace inside thumbnail title/alt
3327 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3332 $isbn = $blank = '' ;
3333 while ( ' ' == $x{0} ) {
3335 $x = substr( $x, 1 );
3337 if ( $x == '' ) { # blank isbn
3338 $text .= "ISBN $blank";
3341 while ( strstr( $valid, $x{0} ) != false ) {
3343 $x = substr( $x, 1 );
3345 $num = str_replace( '-', '', $isbn );
3346 $num = str_replace( ' ', '', $num );
3347 $num = str_replace( 'x', 'X', $num );
3350 $text .= "ISBN $blank$x";
3352 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3353 $text .= '<a href="' .
3354 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3355 "\" class=\"internal\">ISBN $isbn</a>";
3359 wfProfileOut( $fname );
3364 * Return an HTML link for the "RFC 1234" text
3367 * @param string $text Text to be processed
3368 * @param string $keyword Magic keyword to use (default RFC)
3369 * @param string $urlmsg Interface message to use (default rfcurl)
3372 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3374 $valid = '0123456789';
3377 $a = split( $keyword, ' '.$text );
3378 if ( count ( $a ) < 2 ) {
3381 $text = substr( array_shift( $a ), 1);
3383 /* Check if keyword is preceed by [[.
3384 * This test is made here cause of the array_shift above
3385 * that prevent the test to be done in the foreach.
3387 if ( substr( $text, -2 ) == '[[' ) {
3391 foreach ( $a as $x ) {
3392 /* token might be empty if we have RFC RFC 1234 */
3398 # hack: don't replace inside thumbnail title/alt
3400 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3401 $text .= $keyword . $x;
3407 /** remove and save whitespaces in $blank */
3408 while ( $x{0} == ' ' ) {
3410 $x = substr( $x, 1 );
3413 /** remove and save the rfc number in $id */
3414 while ( strstr( $valid, $x{0} ) != false ) {
3416 $x = substr( $x, 1 );
3420 /* call back stripped spaces*/
3421 $text .= $keyword.$blank.$x;
3422 } elseif( $internal ) {
3424 $text .= $keyword.$id.$x;
3426 /* build the external link*/
3427 $url = wfMsg( $urlmsg, $id);
3428 $sk =& $this->mOptions
->getSkin();
3429 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3430 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3433 /* Check if the next RFC keyword is preceed by [[ */
3434 $internal = ( substr($x,-2) == '[[' );
3440 * Transform wiki markup when saving a page by doing \r\n -> \n
3441 * conversion, substitting signatures, {{subst:}} templates, etc.
3443 * @param string $text the text to transform
3444 * @param Title &$title the Title object for the current article
3445 * @param User &$user the User object describing the current user
3446 * @param ParserOptions $options parsing options
3447 * @param bool $clearState whether to clear the parser state first
3448 * @return string the altered wiki markup
3451 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3452 $this->mOptions
= $options;
3453 $this->mTitle
=& $title;
3454 $this->mOutputType
= OT_WIKI
;
3456 if ( $clearState ) {
3457 $this->clearState();
3460 $stripState = false;
3464 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3465 $text = $this->strip( $text, $stripState, true );
3466 $text = $this->pstPass2( $text, $stripState, $user );
3467 $text = $this->unstrip( $text, $stripState );
3468 $text = $this->unstripNoWiki( $text, $stripState );
3473 * Pre-save transform helper function
3476 function pstPass2( $text, &$stripState, &$user ) {
3477 global $wgContLang, $wgLocaltimezone;
3479 /* Note: This is the timestamp saved as hardcoded wikitext to
3480 * the database, we use $wgContLang here in order to give
3481 * everyone the same signature and use the default one rather
3482 * than the one selected in each user's preferences.
3484 if ( isset( $wgLocaltimezone ) ) {
3485 $oldtz = getenv( 'TZ' );
3486 putenv( 'TZ='.$wgLocaltimezone );
3488 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3489 ' (' . date( 'T' ) . ')';
3490 if ( isset( $wgLocaltimezone ) ) {
3491 putenv( 'TZ='.$oldtz );
3494 # Variable replacement
3495 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3496 $text = $this->replaceVariables( $text );
3498 # Strip out <nowiki> etc. added via replaceVariables
3499 $text = $this->strip( $text, $stripState );
3502 $sigText = $this->getUserSig( $user );
3503 $text = strtr( $text, array(
3505 '~~~~' => "$sigText $d",
3509 # Context links: [[|name]] and [[name (context)|]]
3511 global $wgLegalTitleChars;
3512 $tc = "[$wgLegalTitleChars]";
3513 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3515 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3516 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3518 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3519 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3520 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3521 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3523 $t = $this->mTitle
->getText();
3524 if ( preg_match( $conpat, $t, $m ) ) {
3527 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3528 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3529 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3531 if ( '' == $context ) {
3532 $text = preg_replace( $p2, '[[\\1]]', $text );
3534 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3537 # Trim trailing whitespace
3538 # MAG_END (__END__) tag allows for trailing
3539 # whitespace to be deliberately included
3540 $text = rtrim( $text );
3541 $mw =& MagicWord
::get( MAG_END
);
3542 $mw->matchAndRemove( $text );
3548 * Fetch the user's signature text, if any, and normalize to
3549 * validated, ready-to-insert wikitext.
3555 function getUserSig( &$user ) {
3556 $username = $user->getName();
3557 $nickname = $user->getOption( 'nickname' );
3558 $nickname = $nickname === '' ?
$username : $nickname;
3560 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3561 # Sig. might contain markup; validate this
3562 if( $this->validateSig( $nickname ) !== false ) {
3563 # Validated; clean up (if needed) and return it
3564 return $this->cleanSig( $nickname, true );
3566 # Failed to validate; fall back to the default
3567 $nickname = $username;
3568 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3572 # If we're still here, make it a link to the user page
3573 $userpage = $user->getUserPage();
3574 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3578 * Check that the user's signature contains no bad XML
3580 * @param string $text
3581 * @return mixed An expanded string, or false if invalid.
3583 function validateSig( $text ) {
3584 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3588 * Clean up signature text
3590 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3591 * 2) Substitute all transclusions
3593 * @param string $text
3594 * @param $parsing Whether we're cleaning (preferences save) or parsing
3595 * @return string Signature text
3597 function cleanSig( $text, $parsing = false ) {
3599 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3601 $substWord = MagicWord
::get( MAG_SUBST
);
3602 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3603 $substText = '{{' . $substWord->getSynonym( 0 );
3605 $text = preg_replace( $substRegex, $substText, $text );
3606 $text = preg_replace( '/~{3,5}/', '', $text );
3607 $text = $this->replaceVariables( $text );
3609 $this->clearState();
3614 * Set up some variables which are usually set up in parse()
3615 * so that an external function can call some class members with confidence
3618 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3619 $this->mTitle
=& $title;
3620 $this->mOptions
= $options;
3621 $this->mOutputType
= $outputType;
3622 if ( $clearState ) {
3623 $this->clearState();
3628 * Transform a MediaWiki message by replacing magic variables.
3630 * @param string $text the text to transform
3631 * @param ParserOptions $options options
3632 * @return string the text with variables substituted
3635 function transformMsg( $text, $options ) {
3637 static $executing = false;
3639 $fname = "Parser::transformMsg";
3641 # Guard against infinite recursion
3647 wfProfileIn($fname);
3649 $this->mTitle
= $wgTitle;
3650 $this->mOptions
= $options;
3651 $this->mOutputType
= OT_MSG
;
3652 $this->clearState();
3653 $text = $this->replaceVariables( $text );
3656 wfProfileOut($fname);
3661 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3662 * The callback should have the following form:
3663 * function myParserHook( $text, $params, &$parser ) { ... }
3665 * Transform and return $text. Use $parser for any required context, e.g. use
3666 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3670 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3671 * @param mixed $callback The callback function (and object) to use for the tag
3673 * @return The old value of the mTagHooks array associated with the hook
3675 function setHook( $tag, $callback ) {
3676 $oldVal = @$this->mTagHooks
[$tag];
3677 $this->mTagHooks
[$tag] = $callback;
3683 * Create a function, e.g. {{sum:1|2|3}}
3684 * The callback function should have the form:
3685 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3687 * The callback may either return the text result of the function, or an array with the text
3688 * in element 0, and a number of flags in the other elements. The names of the flags are
3689 * specified in the keys. Valid flags are:
3690 * found The text returned is valid, stop processing the template. This
3692 * nowiki Wiki markup in the return value should be escaped
3693 * noparse Unsafe HTML tags should not be stripped, etc.
3694 * noargs Don't replace triple-brace arguments in the return value
3695 * isHTML The returned text is HTML, armour it against wikitext transformation
3699 * @param string $name The function name. Function names are case-insensitive.
3700 * @param mixed $callback The callback function (and object) to use
3702 * @return The old callback function for this name, if any
3704 function setFunctionHook( $name, $callback ) {
3705 $name = strtolower( $name );
3706 $oldVal = @$this->mFunctionHooks
[$name];
3707 $this->mFunctionHooks
[$name] = $callback;
3712 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3713 * Placeholders created in Skin::makeLinkObj()
3714 * Returns an array of links found, indexed by PDBK:
3718 * $options is a bit field, RLH_FOR_UPDATE to select for update
3720 function replaceLinkHolders( &$text, $options = 0 ) {
3722 global $wgOutputReplace;
3724 $fname = 'Parser::replaceLinkHolders';
3725 wfProfileIn( $fname );
3729 $sk =& $this->mOptions
->getSkin();
3730 $linkCache =& LinkCache
::singleton();
3732 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3733 wfProfileIn( $fname.'-check' );
3734 $dbr =& wfGetDB( DB_SLAVE
);
3735 $page = $dbr->tableName( 'page' );
3736 $threshold = $wgUser->getOption('stubthreshold');
3739 asort( $this->mLinkHolders
['namespaces'] );
3743 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3745 $title = $this->mLinkHolders
['titles'][$key];
3747 # Skip invalid entries.
3748 # Result will be ugly, but prevents crash.
3749 if ( is_null( $title ) ) {
3752 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3754 # Check if it's a static known link, e.g. interwiki
3755 if ( $title->isAlwaysKnown() ) {
3756 $colours[$pdbk] = 1;
3757 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3758 $colours[$pdbk] = 1;
3759 $this->mOutput
->addLink( $title, $id );
3760 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3761 $colours[$pdbk] = 0;
3763 # Not in the link cache, add it to the query
3764 if ( !isset( $current ) ) {
3766 $query = "SELECT page_id, page_namespace, page_title";
3767 if ( $threshold > 0 ) {
3768 $query .= ', page_len, page_is_redirect';
3770 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3771 } elseif ( $current != $ns ) {
3773 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3778 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3783 if ( $options & RLH_FOR_UPDATE
) {
3784 $query .= ' FOR UPDATE';
3787 $res = $dbr->query( $query, $fname );
3789 # Fetch data and form into an associative array
3790 # non-existent = broken
3793 while ( $s = $dbr->fetchObject($res) ) {
3794 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3795 $pdbk = $title->getPrefixedDBkey();
3796 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3797 $this->mOutput
->addLink( $title, $s->page_id
);
3799 if ( $threshold > 0 ) {
3800 $size = $s->page_len
;
3801 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3802 $colours[$pdbk] = 1;
3804 $colours[$pdbk] = 2;
3807 $colours[$pdbk] = 1;
3811 wfProfileOut( $fname.'-check' );
3813 # Construct search and replace arrays
3814 wfProfileIn( $fname.'-construct' );
3815 $wgOutputReplace = array();
3816 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3817 $pdbk = $pdbks[$key];
3818 $searchkey = "<!--LINK $key-->";
3819 $title = $this->mLinkHolders
['titles'][$key];
3820 if ( empty( $colours[$pdbk] ) ) {
3821 $linkCache->addBadLinkObj( $title );
3822 $colours[$pdbk] = 0;
3823 $this->mOutput
->addLink( $title, 0 );
3824 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3825 $this->mLinkHolders
['texts'][$key],
3826 $this->mLinkHolders
['queries'][$key] );
3827 } elseif ( $colours[$pdbk] == 1 ) {
3828 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3829 $this->mLinkHolders
['texts'][$key],
3830 $this->mLinkHolders
['queries'][$key] );
3831 } elseif ( $colours[$pdbk] == 2 ) {
3832 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3833 $this->mLinkHolders
['texts'][$key],
3834 $this->mLinkHolders
['queries'][$key] );
3837 wfProfileOut( $fname.'-construct' );
3840 wfProfileIn( $fname.'-replace' );
3842 $text = preg_replace_callback(
3843 '/(<!--LINK .*?-->)/',
3844 "wfOutputReplaceMatches",
3847 wfProfileOut( $fname.'-replace' );
3850 # Now process interwiki link holders
3851 # This is quite a bit simpler than internal links
3852 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3853 wfProfileIn( $fname.'-interwiki' );
3854 # Make interwiki link HTML
3855 $wgOutputReplace = array();
3856 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3857 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3858 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3861 $text = preg_replace_callback(
3862 '/<!--IWLINK (.*?)-->/',
3863 "wfOutputReplaceMatches",
3865 wfProfileOut( $fname.'-interwiki' );
3868 wfProfileOut( $fname );
3873 * Replace <!--LINK--> link placeholders with plain text of links
3874 * (not HTML-formatted).
3875 * @param string $text
3878 function replaceLinkHoldersText( $text ) {
3879 $fname = 'Parser::replaceLinkHoldersText';
3880 wfProfileIn( $fname );
3882 $text = preg_replace_callback(
3883 '/<!--(LINK|IWLINK) (.*?)-->/',
3884 array( &$this, 'replaceLinkHoldersTextCallback' ),
3887 wfProfileOut( $fname );
3892 * @param array $matches
3896 function replaceLinkHoldersTextCallback( $matches ) {
3897 $type = $matches[1];
3899 if( $type == 'LINK' ) {
3900 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3901 return $this->mLinkHolders
['texts'][$key];
3903 } elseif( $type == 'IWLINK' ) {
3904 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3905 return $this->mInterwikiLinkHolders
['texts'][$key];
3912 * Renders an image gallery from a text with one line per image.
3913 * text labels may be given by using |-style alternative text. E.g.
3914 * Image:one.jpg|The number "1"
3915 * Image:tree.jpg|A tree
3916 * given as text will return the HTML of a gallery with two images,
3917 * labeled 'The number "1"' and
3920 function renderImageGallery( $text ) {
3922 $parserOptions = new ParserOptions
;
3923 $localParser = new Parser();
3925 $ig = new ImageGallery();
3926 $ig->setShowBytes( false );
3927 $ig->setShowFilename( false );
3928 $lines = explode( "\n", $text );
3930 foreach ( $lines as $line ) {
3931 # match lines like these:
3932 # Image:someimage.jpg|This is some image
3933 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3935 if ( count( $matches ) == 0 ) {
3938 $nt =& Title
::newFromText( $matches[1] );
3939 if( is_null( $nt ) ) {
3940 # Bogus title. Ignore these so we don't bomb out later.
3943 if ( isset( $matches[3] ) ) {
3944 $label = $matches[3];
3949 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3950 $html = $pout->getText();
3952 $ig->add( new Image( $nt ), $html );
3954 # Only add real images (bug #5586)
3955 if ( $nt->getNamespace() == NS_IMAGE
) {
3956 $this->mOutput
->addImage( $nt->getDBkey() );
3959 return $ig->toHTML();
3963 * Parse image options text and use it to make an image
3965 function makeImage( &$nt, $options ) {
3966 global $wgUseImageResize;
3970 # Check if the options text is of the form "options|alt text"
3972 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3973 # * left no resizing, just left align. label is used for alt= only
3974 # * right same, but right aligned
3975 # * none same, but not aligned
3976 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3977 # * center center the image
3978 # * framed Keep original image size, no magnify-button.
3980 $part = explode( '|', $options);
3982 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3983 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3984 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3985 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3986 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3987 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3988 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3989 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3992 $width = $height = $framed = $thumb = false;
3993 $manual_thumb = '' ;
3995 foreach( $part as $key => $val ) {
3996 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3998 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3999 # use manually specified thumbnail
4001 $manual_thumb = $match;
4002 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4003 # remember to set an alignment, don't render immediately
4005 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4006 # remember to set an alignment, don't render immediately
4008 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4009 # remember to set an alignment, don't render immediately
4011 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4012 # remember to set an alignment, don't render immediately
4014 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4015 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4016 # $match is the image width in pixels
4017 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4018 $width = intval( $m[1] );
4019 $height = intval( $m[2] );
4021 $width = intval($match);
4023 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4029 # Strip bad stuff out of the alt text
4030 $alt = $this->replaceLinkHoldersText( $caption );
4032 # make sure there are no placeholders in thumbnail attributes
4033 # that are later expanded to html- so expand them now and
4035 $alt = $this->unstrip($alt, $this->mStripState
);
4036 $alt = Sanitizer
::stripAllTags( $alt );
4038 # Linker does the rest
4039 $sk =& $this->mOptions
->getSkin();
4040 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4044 * Set a flag in the output object indicating that the content is dynamic and
4045 * shouldn't be cached.
4047 function disableCache() {
4048 $this->mOutput
->mCacheTime
= -1;
4052 * Callback from the Sanitizer for expanding items found in HTML attribute
4053 * values, so they can be safely tested and escaped.
4054 * @param string $text
4055 * @param array $args
4059 function attributeStripCallback( &$text, $args ) {
4060 $text = $this->replaceVariables( $text, $args );
4061 $text = $this->unstripForHTML( $text );
4065 function unstripForHTML( $text ) {
4066 $text = $this->unstrip( $text, $this->mStripState
);
4067 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4075 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4076 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4077 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4083 function getTags() { return array_keys( $this->mTagHooks
); }
4089 * @package MediaWiki
4094 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4095 $mCategories, # Map of category names to sort keys
4096 $mExternalLinks, # External link URLs, in the key only
4097 $mImages, # DB keys of the images used, in the array key only
4098 $mLanguageLinks, # List of the full text of language links, in the order they appear
4099 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4100 $mNewSection, # Show a new section link?
4101 $mSubtitle, # Additional subtitle
4102 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4103 $mText, # The output text
4104 $mTitleText, # title text of the chosen language variant
4105 $mVersion ; # Compatibility check
4107 /** @todo FIXME should those be public ? */
4109 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4110 $mHTMLtitle ; # Display HTML title
4112 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4113 $containsOldMagic = false, $titletext = '' )
4115 $this->mText
= $text;
4116 $this->mLanguageLinks
= $languageLinks;
4117 $this->mCategories
= $categoryLinks;
4118 $this->mContainsOldMagic
= $containsOldMagic;
4119 $this->mCacheTime
= '';
4120 $this->mVersion
= MW_PARSER_VERSION
;
4121 $this->mTitleText
= $titletext;
4122 $this->mLinks
= array();
4123 $this->mTemplates
= array();
4124 $this->mImages
= array();
4125 $this->mExternalLinks
= array();
4126 $this->mHTMLtitle
= "" ;
4127 $this->mSubtitle
= "" ;
4128 $this->mNewSection
= false;
4131 function getText() { return $this->mText
; }
4132 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4133 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4134 function &getCategories() { return $this->mCategories
; }
4135 function getCacheTime() { return $this->mCacheTime
; }
4136 function getTitleText() { return $this->mTitleText
; }
4137 function &getLinks() { return $this->mLinks
; }
4138 function &getTemplates() { return $this->mTemplates
; }
4139 function &getImages() { return $this->mImages
; }
4140 function &getExternalLinks() { return $this->mExternalLinks
; }
4142 function containsOldMagic() { return $this->mContainsOldMagic
; }
4143 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4144 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4145 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4146 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4147 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4148 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4150 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4151 function addImage( $name ) { $this->mImages
[$name] = 1; }
4152 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4153 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4155 function setNewSection( $value ) {
4156 $this->mNewSection
= (bool)$value;
4158 function getNewSection() {
4159 return (bool)$this->mNewSection
;
4162 function addLink( $title, $id ) {
4163 $ns = $title->getNamespace();
4164 $dbk = $title->getDBkey();
4165 if ( !isset( $this->mLinks
[$ns] ) ) {
4166 $this->mLinks
[$ns] = array();
4168 $this->mLinks
[$ns][$dbk] = $id;
4171 function addTemplate( $title, $id ) {
4172 $ns = $title->getNamespace();
4173 $dbk = $title->getDBkey();
4174 if ( !isset( $this->mTemplates
[$ns] ) ) {
4175 $this->mTemplates
[$ns] = array();
4177 $this->mTemplates
[$ns][$dbk] = $id;
4181 * Return true if this cached output object predates the global or
4182 * per-article cache invalidation timestamps, or if it comes from
4183 * an incompatible older version.
4185 * @param string $touched the affected article's last touched timestamp
4189 function expired( $touched ) {
4190 global $wgCacheEpoch;
4191 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4192 $this->getCacheTime() < $touched ||
4193 $this->getCacheTime() <= $wgCacheEpoch ||
4194 !isset( $this->mVersion
) ||
4195 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4200 * Set options of the Parser
4202 * @package MediaWiki
4206 # All variables are private
4208 $mAllowExternalImages, # Allow external images inline
4209 $mAllowExternalImagesFrom, # If not, any exception?
4210 $mAllowSpecialInclusion, # Allow inclusion of special pages
4211 $mDateFormat, # Date format index
4212 $mEditSection, # Create "edit section" links
4213 $mInterfaceMessage, # Which lang to call for PLURAL and GRAMMAR
4214 $mInterwikiMagic, # Interlanguage links are removed and returned in an array
4215 $mNumberHeadings, # Automatically number headings
4216 $mSkin, # Reference to the preferred skin
4217 $mTidy, # Ask for tidy cleanup
4218 $mUseDynamicDates, # Use DateFormatter to format dates
4219 $mUseTeX ; # Use texvc to expand <math> tags
4221 function getUseTeX() { return $this->mUseTeX
; }
4222 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4223 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4224 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4225 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4226 function &getSkin() { return $this->mSkin
; }
4227 function getDateFormat() { return $this->mDateFormat
; }
4228 function getEditSection() { return $this->mEditSection
; }
4229 function getNumberHeadings() { return $this->mNumberHeadings
; }
4230 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4231 function getTidy() { return $this->mTidy
; }
4232 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4234 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4235 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4236 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4237 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4238 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4239 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4240 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4241 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4242 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4243 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4244 function setSkin( &$x ) { $this->mSkin
=& $x; }
4245 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4247 function ParserOptions() {
4249 $this->initialiseFromUser( $wgUser );
4253 * Get parser options
4256 static function newFromUser( &$user ) {
4257 $popts = new ParserOptions
;
4258 $popts->initialiseFromUser( $user );
4262 /** Get user options */
4263 function initialiseFromUser( &$userInput ) {
4264 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4265 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4266 $fname = 'ParserOptions::initialiseFromUser';
4267 wfProfileIn( $fname );
4268 if ( !$userInput ) {
4270 $user->setLoaded( true );
4272 $user =& $userInput;
4275 $this->mUseTeX
= $wgUseTeX;
4276 $this->mUseDynamicDates
= $wgUseDynamicDates;
4277 $this->mInterwikiMagic
= $wgInterwikiMagic;
4278 $this->mAllowExternalImages
= $wgAllowExternalImages;
4279 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4280 wfProfileIn( $fname.'-skin' );
4281 $this->mSkin
=& $user->getSkin();
4282 wfProfileOut( $fname.'-skin' );
4283 $this->mDateFormat
= $user->getOption( 'date' );
4284 $this->mEditSection
= true;
4285 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4286 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4287 $this->mTidy
= false;
4288 $this->mInterfaceMessage
= false;
4289 wfProfileOut( $fname );
4294 * Callback function used by Parser::replaceLinkHolders()
4295 * to substitute link placeholders.
4297 function &wfOutputReplaceMatches( $matches ) {
4298 global $wgOutputReplace;
4299 return $wgOutputReplace[$matches[1]];
4303 * Return the total number of articles
4305 function wfNumberOfArticles() {
4306 global $wgNumberOfArticles;
4309 return $wgNumberOfArticles;
4313 * Return the number of files
4315 function wfNumberOfFiles() {
4316 $fname = 'wfNumberOfFiles';
4318 wfProfileIn( $fname );
4319 $dbr =& wfGetDB( DB_SLAVE
);
4320 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4321 wfProfileOut( $fname );
4327 * Return the number of user accounts
4330 function wfNumberOfUsers() {
4331 wfProfileIn( 'wfNumberOfUsers' );
4332 $dbr =& wfGetDB( DB_SLAVE
);
4333 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4334 wfProfileOut( 'wfNumberOfUsers' );
4339 * Get various statistics from the database
4342 function wfLoadSiteStats() {
4343 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4344 $fname = 'wfLoadSiteStats';
4346 if ( -1 != $wgNumberOfArticles ) return;
4347 $dbr =& wfGetDB( DB_SLAVE
);
4348 $s = $dbr->selectRow( 'site_stats',
4349 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4350 array( 'ss_row_id' => 1 ), $fname
4353 if ( $s === false ) {
4356 $wgTotalViews = $s->ss_total_views
;
4357 $wgTotalEdits = $s->ss_total_edits
;
4358 $wgNumberOfArticles = $s->ss_good_articles
;
4364 * Basically replacing " > and < with HTML entities ( ", >, <)
4366 * @param $in String: text that might contain HTML tags.
4367 * @return string Escaped string
4369 function wfEscapeHTMLTagsOnly( $in ) {
4371 array( '"', '>', '<' ),
4372 array( '"', '>', '<' ),