3 * File for Parser and related classes
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
18 define( 'MW_PARSER_VERSION', '1.6.0' );
21 * Variable substitution O(N^2) attack
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
33 define( 'RLH_FOR_UPDATE', 1 );
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS
.'+) *('.EXT_LINK_TEXT_CLASS
.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS
.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS
.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS
.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS
.')$/S' # Filename
64 * Processes wiki markup
67 * There are three main entry points into the Parser class:
69 * produces HTML output
71 * produces altered wiki markup.
73 * performs brace substitution on MediaWiki messages
76 * objects: $wgLang, $wgContLang
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
85 * * only within ParserOptions
96 var $mTagHooks, $mFunctionHooks;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
122 $this->mTagHooks
= array();
123 $this->mFunctionHooks
= array();
132 function clearState() {
133 $this->mOutput
= new ParserOutput
;
134 $this->mAutonumber
= 0;
135 $this->mLastSection
= '';
136 $this->mDTopen
= false;
137 $this->mVariables
= false;
138 $this->mIncludeCount
= array();
139 $this->mStripState
= array();
140 $this->mArgStack
= array();
141 $this->mInPre
= false;
142 $this->mInterwikiLinkHolders
= array(
146 $this->mLinkHolders
= array(
147 'namespaces' => array(),
149 'queries' => array(),
153 $this->mRevisionId
= null;
154 $this->mUniqPrefix
= 'UNIQ' . Parser
::getRandomString();
156 # Clear these on every parse, bug 4549
157 $this->mTemplates
= array();
158 $this->mTemplatePath
= array();
160 wfRunHooks( 'ParserClearState', array( &$this ) );
164 * Accessor for mUniqPrefix.
168 function UniqPrefix() {
169 return $this->mUniqPrefix
;
173 * Convert wikitext to HTML
174 * Do not call this function recursively.
177 * @param string $text Text we want to parse
178 * @param Title &$title A title object
179 * @param array $options
180 * @param boolean $linestart
181 * @param boolean $clearState
182 * @param int $revid number to pass in {{REVISIONID}}
183 * @return ParserOutput a ParserOutput
185 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
187 * First pass--just handle <nowiki> sections, pass the rest off
188 * to internalParse() which does all the real work.
191 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
192 $fname = 'Parser::parse';
193 wfProfileIn( $fname );
199 $this->mOptions
= $options;
200 $this->mTitle
=& $title;
201 $this->mRevisionId
= $revid;
202 $this->mOutputType
= OT_HTML
;
204 $this->mStripState
= NULL;
206 //$text = $this->strip( $text, $this->mStripState );
207 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
208 $x =& $this->mStripState
;
210 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
211 $text = $this->strip( $text, $x );
212 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
214 # Hook to suspend the parser in this state
215 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
216 wfProfileOut( $fname );
220 $text = $this->internalParse( $text );
222 $text = $this->unstrip( $text, $this->mStripState
);
224 # Clean up special characters, only run once, next-to-last before doBlockLevels
226 # french spaces, last one Guillemet-left
227 # only if there is something before the space
228 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
229 # french spaces, Guillemet-right
230 '/(\\302\\253) /' => '\\1 ',
231 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
233 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
236 $text = $this->doBlockLevels( $text, $linestart );
238 $this->replaceLinkHolders( $text );
240 # the position of the parserConvert() call should not be changed. it
241 # assumes that the links are all replaced and the only thing left
242 # is the <nowiki> mark.
243 # Side-effects: this calls $this->mOutput->setTitleText()
244 $text = $wgContLang->parserConvert( $text, $this );
246 $text = $this->unstripNoWiki( $text, $this->mStripState
);
248 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
250 $text = Sanitizer
::normalizeCharReferences( $text );
252 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
253 $text = Parser
::tidy($text);
255 # attempt to sanitize at least some nesting problems
256 # (bug #2702 and quite a few others)
258 # ''Something [http://www.cool.com cool''] -->
259 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
260 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
261 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
262 # fix up an anchor inside another anchor, only
263 # at least for a single single nested link (bug 3695)
264 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
265 '\\1\\2</a>\\3</a>\\1\\4</a>',
266 # fix div inside inline elements- doBlockLevels won't wrap a line which
267 # contains a div, so fix it up here; replace
268 # div with escaped text
269 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
270 '\\1\\3<div\\5>\\6</div>\\8\\9',
271 # remove empty italic or bold tag pairs, some
272 # introduced by rules above
273 '/<([bi])><\/\\1>/' => ''
276 $text = preg_replace(
277 array_keys( $tidyregs ),
278 array_values( $tidyregs ),
282 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
284 $this->mOutput
->setText( $text );
285 wfProfileOut( $fname );
287 return $this->mOutput
;
291 * Get a random string
296 function getRandomString() {
297 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
300 function &getTitle() { return $this->mTitle
; }
301 function getOptions() { return $this->mOptions
; }
304 * Replaces all occurrences of <$tag>content</$tag> in the text
305 * with a random marker and returns the new text. the output parameter
306 * $content will be an associative array filled with data on the form
307 * $unique_marker => content.
309 * If $content is already set, the additional entries will be appended
310 * If $tag is set to STRIP_COMMENTS, the function will extract
311 * <!-- HTML comments -->
316 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
317 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
332 if( $tag == STRIP_COMMENTS
) {
333 $start = '/<!--()()/';
336 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
337 $end = "/<\\/$tag\\s*>/i";
340 while ( '' != $text ) {
341 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
343 if( count( $p ) < 4 ) {
350 $marker = $rnd . sprintf('%08X', $n++
);
351 $stripped .= $marker;
353 $tags[$marker] = "<$tag$attributes$empty>";
354 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
356 if ( $empty === '/' ) {
357 // Empty element tag, <tag />
358 $content[$marker] = null;
361 $q = preg_split( $end, $inside, 2 );
362 $content[$marker] = $q[0];
363 if( count( $q ) < 2 ) {
364 # No end tag -- let it run out to the end of the text.
375 * Wrapper function for extractTagsAndParams
376 * for cases where $tags and $params isn't needed
377 * i.e. where tags will never have params, like <nowiki>
382 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
383 $dummy_tags = array();
384 $dummy_params = array();
386 return Parser
::extractTagsAndParams( $tag, $text, $content,
387 $dummy_tags, $dummy_params, $uniq_prefix );
391 * Strips and renders nowiki, pre, math, hiero
392 * If $render is set, performs necessary rendering operations on plugins
393 * Returns the text, and fills an array with data needed in unstrip()
394 * If the $state is already a valid strip state, it adds to the state
396 * @param bool $stripcomments when set, HTML comments <!-- like this -->
397 * will be stripped in addition to other tags. This is important
398 * for section editing, where these comments cause confusion when
399 * counting the sections in the wikisource
403 function strip( $text, &$state, $stripcomments = false ) {
404 $render = ($this->mOutputType
== OT_HTML
);
405 $html_content = array();
406 $nowiki_content = array();
407 $math_content = array();
408 $pre_content = array();
409 $comment_content = array();
410 $ext_content = array();
412 $ext_params = array();
413 $gallery_content = array();
415 # Replace any instances of the placeholders
416 $uniq_prefix = $this->mUniqPrefix
;
417 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
422 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
423 foreach( $html_content as $marker => $content ) {
425 # Raw and unchecked for validity.
426 $html_content[$marker] = $content;
428 $html_content[$marker] = '<html>'.$content.'</html>';
434 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
435 foreach( $nowiki_content as $marker => $content ) {
437 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
439 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
444 if( $this->mOptions
->getUseTeX() ) {
445 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
446 foreach( $math_content as $marker => $content ){
448 $math_content[$marker] = renderMath( $content );
450 $math_content[$marker] = '<math>'.$content.'</math>';
456 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
457 foreach( $pre_content as $marker => $content ){
459 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
461 $pre_content[$marker] = '<pre>'.$content.'</pre>';
466 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
467 foreach( $gallery_content as $marker => $content ) {
468 require_once( 'ImageGallery.php' );
470 $gallery_content[$marker] = $this->renderImageGallery( $content );
472 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
477 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
478 foreach( $comment_content as $marker => $content ){
479 $comment_content[$marker] = '<!--'.$content.'-->';
483 foreach ( $this->mTagHooks
as $tag => $callback ) {
484 $ext_content[$tag] = array();
485 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
486 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
487 foreach( $ext_content[$tag] as $marker => $content ) {
488 $full_tag = $ext_tags[$tag][$marker];
489 $params = $ext_params[$tag][$marker];
491 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
493 if ( is_null( $content ) ) {
495 $ext_content[$tag][$marker] = $full_tag;
497 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
503 # Unstrip comments unless explicitly told otherwise.
504 # (The comments are always stripped prior to this point, so as to
505 # not invoke any extension tags / parser hooks contained within
507 if ( !$stripcomments ) {
508 $tempstate = array( 'comment' => $comment_content );
509 $text = $this->unstrip( $text, $tempstate );
510 $comment_content = array();
513 # Merge state with the pre-existing state, if there is one
515 $state['html'] = $state['html'] +
$html_content;
516 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
517 $state['math'] = $state['math'] +
$math_content;
518 $state['pre'] = $state['pre'] +
$pre_content;
519 $state['gallery'] = $state['gallery'] +
$gallery_content;
520 $state['comment'] = $state['comment'] +
$comment_content;
522 foreach( $ext_content as $tag => $array ) {
523 if ( array_key_exists( $tag, $state ) ) {
524 $state[$tag] = $state[$tag] +
$array;
529 'html' => $html_content,
530 'nowiki' => $nowiki_content,
531 'math' => $math_content,
532 'pre' => $pre_content,
533 'gallery' => $gallery_content,
534 'comment' => $comment_content,
541 * restores pre, math, and hiero removed by strip()
543 * always call unstripNoWiki() after this one
546 function unstrip( $text, &$state ) {
547 if ( !is_array( $state ) ) {
551 # Must expand in reverse order, otherwise nested tags will be corrupted
552 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
553 if( $tag != 'nowiki' && $tag != 'html' ) {
554 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
555 $text = str_replace( $uniq, $content, $text );
564 * always call this after unstrip() to preserve the order
568 function unstripNoWiki( $text, &$state ) {
569 if ( !is_array( $state ) ) {
573 # Must expand in reverse order, otherwise nested tags will be corrupted
574 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
575 $text = str_replace( key( $state['nowiki'] ), $content, $text );
580 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
581 $text = str_replace( key( $state['html'] ), $content, $text );
589 * Add an item to the strip state
590 * Returns the unique tag which must be inserted into the stripped text
591 * The tag will be replaced with the original text in unstrip()
595 function insertStripItem( $text, &$state ) {
596 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
603 'comment' => array(),
604 'gallery' => array(),
607 $state['item'][$rnd] = $text;
612 * Interface with html tidy, used if $wgUseTidy = true.
613 * If tidy isn't able to correct the markup, the original will be
614 * returned in all its glory with a warning comment appended.
616 * Either the external tidy program or the in-process tidy extension
617 * will be used depending on availability. Override the default
618 * $wgTidyInternal setting to disable the internal if it's not working.
620 * @param string $text Hideous HTML input
621 * @return string Corrected HTML output
625 function tidy( $text ) {
626 global $wgTidyInternal;
627 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
628 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
629 '<head><title>test</title></head><body>'.$text.'</body></html>';
630 if( $wgTidyInternal ) {
631 $correctedtext = Parser
::internalTidy( $wrappedtext );
633 $correctedtext = Parser
::externalTidy( $wrappedtext );
635 if( is_null( $correctedtext ) ) {
636 wfDebug( "Tidy error detected!\n" );
637 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
639 return $correctedtext;
643 * Spawn an external HTML tidy process and get corrected markup back from it.
648 function externalTidy( $text ) {
649 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
650 $fname = 'Parser::externalTidy';
651 wfProfileIn( $fname );
656 $descriptorspec = array(
657 0 => array('pipe', 'r'),
658 1 => array('pipe', 'w'),
659 2 => array('file', '/dev/null', 'a')
662 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
663 if (is_resource($process)) {
664 // Theoretically, this style of communication could cause a deadlock
665 // here. If the stdout buffer fills up, then writes to stdin could
666 // block. This doesn't appear to happen with tidy, because tidy only
667 // writes to stdout after it's finished reading from stdin. Search
668 // for tidyParseStdin and tidySaveStdout in console/tidy.c
669 fwrite($pipes[0], $text);
671 while (!feof($pipes[1])) {
672 $cleansource .= fgets($pipes[1], 1024);
675 proc_close($process);
678 wfProfileOut( $fname );
680 if( $cleansource == '' && $text != '') {
681 // Some kind of error happened, so we couldn't get the corrected text.
682 // Just give up; we'll use the source text and append a warning.
690 * Use the HTML tidy PECL extension to use the tidy library in-process,
691 * saving the overhead of spawning a new process. Currently written to
692 * the PHP 4.3.x version of the extension, may not work on PHP 5.
694 * 'pear install tidy' should be able to compile the extension module.
699 function internalTidy( $text ) {
701 $fname = 'Parser::internalTidy';
702 wfProfileIn( $fname );
704 tidy_load_config( $wgTidyConf );
705 tidy_set_encoding( 'utf8' );
706 tidy_parse_string( $text );
708 if( tidy_get_status() == 2 ) {
709 // 2 is magic number for fatal error
710 // http://www.php.net/manual/en/function.tidy-get-status.php
713 $cleansource = tidy_get_output();
715 wfProfileOut( $fname );
720 * parse the wiki syntax used to render tables
724 function doTableStuff ( $t ) {
725 $fname = 'Parser::doTableStuff';
726 wfProfileIn( $fname );
728 $t = explode ( "\n" , $t ) ;
729 $td = array () ; # Is currently a td tag open?
730 $ltd = array () ; # Was it TD or TH?
731 $tr = array () ; # Is currently a tr tag open?
732 $ltr = array () ; # tr attributes
733 $has_opened_tr = array(); # Did this table open a <tr> element?
734 $indent_level = 0; # indent level of the table
735 foreach ( $t AS $k => $x )
738 $fc = substr ( $x , 0 , 1 ) ;
739 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
740 $indent_level = strlen( $matches[1] );
742 $attributes = $this->unstripForHTML( $matches[2] );
744 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
745 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
746 array_push ( $td , false ) ;
747 array_push ( $ltd , '' ) ;
748 array_push ( $tr , false ) ;
749 array_push ( $ltr , '' ) ;
750 array_push ( $has_opened_tr, false );
752 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
753 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
754 $z = "</table>" . substr ( $x , 2);
755 $l = array_pop ( $ltd ) ;
756 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
757 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
758 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
760 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
762 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
763 $x = substr ( $x , 1 ) ;
764 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
766 $l = array_pop ( $ltd ) ;
767 array_pop ( $has_opened_tr );
768 array_push ( $has_opened_tr , true ) ;
769 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
770 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
773 array_push ( $tr , false ) ;
774 array_push ( $td , false ) ;
775 array_push ( $ltd , '' ) ;
776 $attributes = $this->unstripForHTML( $x );
777 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
779 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
781 if ( '|+' == substr ( $x , 0 , 2 ) ) {
783 $x = substr ( $x , 1 ) ;
785 $after = substr ( $x , 1 ) ;
786 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
788 // Split up multiple cells on the same line.
789 // FIXME: This can result in improper nesting of tags processed
790 // by earlier parser steps, but should avoid splitting up eg
791 // attribute values containing literal "||".
792 $after = wfExplodeMarkup( '||', $after );
796 # Loop through each table cell
797 foreach ( $after AS $theline )
802 $tra = array_pop ( $ltr ) ;
803 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
804 array_push ( $tr , true ) ;
805 array_push ( $ltr , '' ) ;
806 array_pop ( $has_opened_tr );
807 array_push ( $has_opened_tr , true ) ;
810 $l = array_pop ( $ltd ) ;
811 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
812 if ( $fc == '|' ) $l = 'td' ;
813 else if ( $fc == '!' ) $l = 'th' ;
814 else if ( $fc == '+' ) $l = 'caption' ;
816 array_push ( $ltd , $l ) ;
819 $y = explode ( '|' , $theline , 2 ) ;
820 # Note that a '|' inside an invalid link should not
821 # be mistaken as delimiting cell parameters
822 if ( strpos( $y[0], '[[' ) !== false ) {
823 $y = array ($theline);
825 if ( count ( $y ) == 1 )
826 $y = "{$z}<{$l}>{$y[0]}" ;
828 $attributes = $this->unstripForHTML( $y[0] );
829 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
832 array_push ( $td , true ) ;
837 # Closing open td, tr && table
838 while ( count ( $td ) > 0 )
840 $l = array_pop ( $ltd ) ;
841 if ( array_pop ( $td ) ) $t[] = '</td>' ;
842 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
843 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
847 $t = implode ( "\n" , $t ) ;
848 # special case: don't return empty table
849 if($t == "<table>\n<tr><td></td></tr>\n</table>")
851 wfProfileOut( $fname );
856 * Helper function for parse() that transforms wiki markup into
857 * HTML. Only called for $mOutputType == OT_HTML.
861 function internalParse( $text ) {
864 $fname = 'Parser::internalParse';
865 wfProfileIn( $fname );
867 # Remove <noinclude> tags and <includeonly> sections
868 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
869 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
870 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
872 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
873 $text = $this->replaceVariables( $text, $args );
875 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
877 $text = $this->doHeadings( $text );
878 if($this->mOptions
->getUseDynamicDates()) {
879 $df =& DateFormatter
::getInstance();
880 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
882 $text = $this->doAllQuotes( $text );
883 $text = $this->replaceInternalLinks( $text );
884 $text = $this->replaceExternalLinks( $text );
886 # replaceInternalLinks may sometimes leave behind
887 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
888 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
890 $text = $this->doMagicLinks( $text );
891 $text = $this->doTableStuff( $text );
892 $text = $this->formatHeadings( $text, $isMain );
894 wfProfileOut( $fname );
899 * Replace special strings like "ISBN xxx" and "RFC xxx" with
900 * magic external links.
904 function &doMagicLinks( &$text ) {
905 $text = $this->magicISBN( $text );
906 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
907 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
912 * Parse headers and return html
916 function doHeadings( $text ) {
917 $fname = 'Parser::doHeadings';
918 wfProfileIn( $fname );
919 for ( $i = 6; $i >= 1; --$i ) {
920 $h = str_repeat( '=', $i );
921 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
922 "<h{$i}>\\1</h{$i}>\\2", $text );
924 wfProfileOut( $fname );
929 * Replace single quotes with HTML markup
931 * @return string the altered text
933 function doAllQuotes( $text ) {
934 $fname = 'Parser::doAllQuotes';
935 wfProfileIn( $fname );
937 $lines = explode( "\n", $text );
938 foreach ( $lines as $line ) {
939 $outtext .= $this->doQuotes ( $line ) . "\n";
941 $outtext = substr($outtext, 0,-1);
942 wfProfileOut( $fname );
947 * Helper function for doAllQuotes()
950 function doQuotes( $text ) {
951 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
952 if ( count( $arr ) == 1 )
956 # First, do some preliminary work. This may shift some apostrophes from
957 # being mark-up to being text. It also counts the number of occurrences
958 # of bold and italics mark-ups.
962 foreach ( $arr as $r )
964 if ( ( $i %
2 ) == 1 )
966 # If there are ever four apostrophes, assume the first is supposed to
967 # be text, and the remaining three constitute mark-up for bold text.
968 if ( strlen( $arr[$i] ) == 4 )
973 # If there are more than 5 apostrophes in a row, assume they're all
974 # text except for the last 5.
975 else if ( strlen( $arr[$i] ) > 5 )
977 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
980 # Count the number of occurrences of bold and italics mark-ups.
981 # We are not counting sequences of five apostrophes.
982 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
983 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
984 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
989 # If there is an odd number of both bold and italics, it is likely
990 # that one of the bold ones was meant to be an apostrophe followed
991 # by italics. Which one we cannot know for certain, but it is more
992 # likely to be one that has a single-letter word before it.
993 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
996 $firstsingleletterword = -1;
997 $firstmultiletterword = -1;
999 foreach ( $arr as $r )
1001 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1003 $x1 = substr ($arr[$i-1], -1);
1004 $x2 = substr ($arr[$i-1], -2, 1);
1006 if ($firstspace == -1) $firstspace = $i;
1007 } else if ($x2 == ' ') {
1008 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1010 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1016 # If there is a single-letter word, use it!
1017 if ($firstsingleletterword > -1)
1019 $arr [ $firstsingleletterword ] = "''";
1020 $arr [ $firstsingleletterword-1 ] .= "'";
1022 # If not, but there's a multi-letter word, use that one.
1023 else if ($firstmultiletterword > -1)
1025 $arr [ $firstmultiletterword ] = "''";
1026 $arr [ $firstmultiletterword-1 ] .= "'";
1028 # ... otherwise use the first one that has neither.
1029 # (notice that it is possible for all three to be -1 if, for example,
1030 # there is only one pentuple-apostrophe in the line)
1031 else if ($firstspace > -1)
1033 $arr [ $firstspace ] = "''";
1034 $arr [ $firstspace-1 ] .= "'";
1038 # Now let's actually convert our apostrophic mush to HTML!
1043 foreach ($arr as $r)
1047 if ($state == 'both')
1054 if (strlen ($r) == 2)
1057 { $output .= '</i>'; $state = ''; }
1058 else if ($state == 'bi')
1059 { $output .= '</i>'; $state = 'b'; }
1060 else if ($state == 'ib')
1061 { $output .= '</b></i><b>'; $state = 'b'; }
1062 else if ($state == 'both')
1063 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1064 else # $state can be 'b' or ''
1065 { $output .= '<i>'; $state .= 'i'; }
1067 else if (strlen ($r) == 3)
1070 { $output .= '</b>'; $state = ''; }
1071 else if ($state == 'bi')
1072 { $output .= '</i></b><i>'; $state = 'i'; }
1073 else if ($state == 'ib')
1074 { $output .= '</b>'; $state = 'i'; }
1075 else if ($state == 'both')
1076 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1077 else # $state can be 'i' or ''
1078 { $output .= '<b>'; $state .= 'b'; }
1080 else if (strlen ($r) == 5)
1083 { $output .= '</b><i>'; $state = 'i'; }
1084 else if ($state == 'i')
1085 { $output .= '</i><b>'; $state = 'b'; }
1086 else if ($state == 'bi')
1087 { $output .= '</i></b>'; $state = ''; }
1088 else if ($state == 'ib')
1089 { $output .= '</b></i>'; $state = ''; }
1090 else if ($state == 'both')
1091 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1092 else # ($state == '')
1093 { $buffer = ''; $state = 'both'; }
1098 # Now close all remaining tags. Notice that the order is important.
1099 if ($state == 'b' ||
$state == 'ib')
1101 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1105 if ($state == 'both')
1106 $output .= '<b><i>'.$buffer.'</i></b>';
1112 * Replace external links
1114 * Note: this is all very hackish and the order of execution matters a lot.
1115 * Make sure to run maintenance/parserTests.php if you change this code.
1119 function replaceExternalLinks( $text ) {
1121 $fname = 'Parser::replaceExternalLinks';
1122 wfProfileIn( $fname );
1124 $sk =& $this->mOptions
->getSkin();
1126 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1128 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1131 while ( $i<count( $bits ) ) {
1133 $protocol = $bits[$i++
];
1134 $text = $bits[$i++
];
1135 $trail = $bits[$i++
];
1137 # The characters '<' and '>' (which were escaped by
1138 # removeHTMLtags()) should not be included in
1139 # URLs, per RFC 2396.
1140 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1141 $text = substr($url, $m2[0][1]) . ' ' . $text;
1142 $url = substr($url, 0, $m2[0][1]);
1145 # If the link text is an image URL, replace it with an <img> tag
1146 # This happened by accident in the original parser, but some people used it extensively
1147 $img = $this->maybeMakeExternalImage( $text );
1148 if ( $img !== false ) {
1154 # Set linktype for CSS - if URL==text, link is essentially free
1155 $linktype = ($text == $url) ?
'free' : 'text';
1157 # No link text, e.g. [http://domain.tld/some.link]
1158 if ( $text == '' ) {
1159 # Autonumber if allowed
1160 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1161 $text = '[' . ++
$this->mAutonumber
. ']';
1162 $linktype = 'autonumber';
1164 # Otherwise just use the URL
1165 $text = htmlspecialchars( $url );
1169 # Have link text, e.g. [http://domain.tld/some.link text]s
1171 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1174 $text = $wgContLang->markNoConversion($text);
1176 # Replace & from obsolete syntax with &.
1177 # All HTML entities will be escaped by makeExternalLink()
1178 $url = str_replace( '&', '&', $url );
1180 # Process the trail (i.e. everything after this link up until start of the next link),
1181 # replacing any non-bracketed links
1182 $trail = $this->replaceFreeExternalLinks( $trail );
1184 # Use the encoded URL
1185 # This means that users can paste URLs directly into the text
1186 # Funny characters like ö aren't valid in URLs anyway
1187 # This was changed in August 2004
1188 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1190 # Register link in the output object.
1191 # Replace unnecessary URL escape codes with the referenced character
1192 # This prevents spammers from hiding links from the filters
1193 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1194 $this->mOutput
->addExternalLink( $pasteurized );
1197 wfProfileOut( $fname );
1202 * Replace anything that looks like a URL with a link
1205 function replaceFreeExternalLinks( $text ) {
1207 $fname = 'Parser::replaceFreeExternalLinks';
1208 wfProfileIn( $fname );
1210 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1211 $s = array_shift( $bits );
1214 $sk =& $this->mOptions
->getSkin();
1216 while ( $i < count( $bits ) ){
1217 $protocol = $bits[$i++
];
1218 $remainder = $bits[$i++
];
1220 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1221 # Found some characters after the protocol that look promising
1222 $url = $protocol . $m[1];
1225 # special case: handle urls as url args:
1226 # http://www.example.com/foo?=http://www.example.com/bar
1227 if(strlen($trail) == 0 &&
1229 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1230 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1233 $url .= $bits[$i] . $bits[$i +
1]; # protocol, url as arg to previous link
1238 # The characters '<' and '>' (which were escaped by
1239 # removeHTMLtags()) should not be included in
1240 # URLs, per RFC 2396.
1241 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1242 $trail = substr($url, $m2[0][1]) . $trail;
1243 $url = substr($url, 0, $m2[0][1]);
1246 # Move trailing punctuation to $trail
1248 # If there is no left bracket, then consider right brackets fair game too
1249 if ( strpos( $url, '(' ) === false ) {
1253 $numSepChars = strspn( strrev( $url ), $sep );
1254 if ( $numSepChars ) {
1255 $trail = substr( $url, -$numSepChars ) . $trail;
1256 $url = substr( $url, 0, -$numSepChars );
1259 # Replace & from obsolete syntax with &.
1260 # All HTML entities will be escaped by makeExternalLink()
1261 # or maybeMakeExternalImage()
1262 $url = str_replace( '&', '&', $url );
1264 # Is this an external image?
1265 $text = $this->maybeMakeExternalImage( $url );
1266 if ( $text === false ) {
1267 # Not an image, make a link
1268 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1269 # Register it in the output object...
1270 # Replace unnecessary URL escape codes with their equivalent characters
1271 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1272 $this->mOutput
->addExternalLink( $pasteurized );
1274 $s .= $text . $trail;
1276 $s .= $protocol . $remainder;
1279 wfProfileOut( $fname );
1284 * Replace unusual URL escape codes with their equivalent characters
1288 * @fixme This can merge genuinely required bits in the path or query string,
1289 * breaking legit URLs. A proper fix would treat the various parts of
1290 * the URL differently; as a workaround, just use the output for
1291 * statistical records, not for actual linking/output.
1293 function replaceUnusualEscapes( $url ) {
1294 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1295 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1299 * Callback function used in replaceUnusualEscapes().
1300 * Replaces unusual URL escape codes with their equivalent character
1304 function replaceUnusualEscapesCallback( $matches ) {
1305 $char = urldecode( $matches[0] );
1306 $ord = ord( $char );
1307 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1308 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1309 // No, shouldn't be escaped
1312 // Yes, leave it escaped
1318 * make an image if it's allowed, either through the global
1319 * option or through the exception
1322 function maybeMakeExternalImage( $url ) {
1323 $sk =& $this->mOptions
->getSkin();
1324 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1325 $imagesexception = !empty($imagesfrom);
1327 if ( $this->mOptions
->getAllowExternalImages()
1328 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1329 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1331 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1338 * Process [[ ]] wikilinks
1342 function replaceInternalLinks( $s ) {
1344 static $fname = 'Parser::replaceInternalLinks' ;
1346 wfProfileIn( $fname );
1348 wfProfileIn( $fname.'-setup' );
1350 # the % is needed to support urlencoded titles as well
1351 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1353 $sk =& $this->mOptions
->getSkin();
1355 #split the entire text string on occurences of [[
1356 $a = explode( '[[', ' ' . $s );
1357 #get the first element (all text up to first [[), and remove the space we added
1358 $s = array_shift( $a );
1359 $s = substr( $s, 1 );
1361 # Match a link having the form [[namespace:link|alternate]]trail
1363 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1364 # Match cases where there is no "]]", which might still be images
1365 static $e1_img = FALSE;
1366 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1367 # Match the end of a line for a word that's not followed by whitespace,
1368 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1369 $e2 = wfMsgForContent( 'linkprefix' );
1371 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1373 if( is_null( $this->mTitle
) ) {
1374 wfDebugDieBacktrace( 'nooo' );
1376 $nottalk = !$this->mTitle
->isTalkPage();
1378 if ( $useLinkPrefixExtension ) {
1379 if ( preg_match( $e2, $s, $m ) ) {
1380 $first_prefix = $m[2];
1382 $first_prefix = false;
1388 $selflink = $this->mTitle
->getPrefixedText();
1389 wfProfileOut( $fname.'-setup' );
1391 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1392 $useSubpages = $this->areSubpagesAllowed();
1394 # Loop for each link
1395 for ($k = 0; isset( $a[$k] ); $k++
) {
1397 if ( $useLinkPrefixExtension ) {
1398 wfProfileIn( $fname.'-prefixhandling' );
1399 if ( preg_match( $e2, $s, $m ) ) {
1407 $prefix = $first_prefix;
1408 $first_prefix = false;
1410 wfProfileOut( $fname.'-prefixhandling' );
1413 $might_be_img = false;
1415 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1417 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1418 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1419 # the real problem is with the $e1 regex
1422 # Still some problems for cases where the ] is meant to be outside punctuation,
1423 # and no image is in sight. See bug 2095.
1426 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1427 strpos($text, '[') !== false
1430 $text .= ']'; # so that replaceExternalLinks($text) works later
1433 # fix up urlencoded title texts
1434 if(preg_match('/%/', $m[1] ))
1435 # Should anchors '#' also be rejected?
1436 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1438 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1439 $might_be_img = true;
1441 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1443 } else { # Invalid form; output directly
1444 $s .= $prefix . '[[' . $line ;
1448 # Don't allow internal links to pages containing
1449 # PROTO: where PROTO is a valid URL protocol; these
1450 # should be external links.
1451 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1452 $s .= $prefix . '[[' . $line ;
1456 # Make subpage if necessary
1457 if( $useSubpages ) {
1458 $link = $this->maybeDoSubpageLink( $m[1], $text );
1463 $noforce = (substr($m[1], 0, 1) != ':');
1465 # Strip off leading ':'
1466 $link = substr($link, 1);
1469 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1471 $s .= $prefix . '[[' . $line;
1475 #check other language variants of the link
1476 #if the article does not exist
1477 if( $checkVariantLink
1478 && $nt->getArticleID() == 0 ) {
1479 $wgContLang->findVariantLink($link, $nt);
1482 $ns = $nt->getNamespace();
1483 $iw = $nt->getInterWiki();
1485 if ($might_be_img) { # if this is actually an invalid link
1486 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1488 while (isset ($a[$k+
1]) ) {
1489 #look at the next 'line' to see if we can close it there
1490 $spliced = array_splice( $a, $k +
1, 1 );
1491 $next_line = array_shift( $spliced );
1492 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1493 # the first ]] closes the inner link, the second the image
1495 $text .= '[[' . $m[1];
1498 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1499 #if there's exactly one ]] that's fine, we'll keep looking
1500 $text .= '[[' . $m[0];
1502 #if $next_line is invalid too, we need look no further
1503 $text .= '[[' . $next_line;
1508 # we couldn't find the end of this imageLink, so output it raw
1509 #but don't ignore what might be perfectly normal links in the text we've examined
1510 $text = $this->replaceInternalLinks($text);
1511 $s .= $prefix . '[[' . $link . '|' . $text;
1512 # note: no $trail, because without an end, there *is* no trail
1515 } else { #it's not an image, so output it raw
1516 $s .= $prefix . '[[' . $link . '|' . $text;
1517 # note: no $trail, because without an end, there *is* no trail
1522 $wasblank = ( '' == $text );
1523 if( $wasblank ) $text = $link;
1526 # Link not escaped by : , create the various objects
1530 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1531 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1532 $s = rtrim($s . "\n");
1533 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1537 if ( $ns == NS_IMAGE
) {
1538 wfProfileIn( "$fname-image" );
1539 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1540 # recursively parse links inside the image caption
1541 # actually, this will parse them in any other parameters, too,
1542 # but it might be hard to fix that, and it doesn't matter ATM
1543 $text = $this->replaceExternalLinks($text);
1544 $text = $this->replaceInternalLinks($text);
1546 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1547 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1548 $this->mOutput
->addImage( $nt->getDBkey() );
1550 wfProfileOut( "$fname-image" );
1553 wfProfileOut( "$fname-image" );
1557 if ( $ns == NS_CATEGORY
) {
1558 wfProfileIn( "$fname-category" );
1559 $s = rtrim($s . "\n"); # bug 87
1562 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1563 $sortkey = $this->mTitle
->getText();
1565 $sortkey = $this->mTitle
->getPrefixedText();
1570 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1571 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1572 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1575 * Strip the whitespace Category links produce, see bug 87
1576 * @todo We might want to use trim($tmp, "\n") here.
1578 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1580 wfProfileOut( "$fname-category" );
1585 if( ( $nt->getPrefixedText() === $selflink ) &&
1586 ( $nt->getFragment() === '' ) ) {
1587 # Self-links are handled specially; generally de-link and change to bold.
1588 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1592 # Special and Media are pseudo-namespaces; no pages actually exist in them
1593 if( $ns == NS_MEDIA
) {
1594 $link = $sk->makeMediaLinkObj( $nt, $text );
1595 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1596 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1597 $this->mOutput
->addImage( $nt->getDBkey() );
1599 } elseif( $ns == NS_SPECIAL
) {
1600 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1602 } elseif( $ns == NS_IMAGE
) {
1603 $img = Image
::newFromTitle( $nt );
1604 if( $img->exists() ) {
1605 // Force a blue link if the file exists; may be a remote
1606 // upload on the shared repository, and we want to see its
1607 // auto-generated page.
1608 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1612 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1614 wfProfileOut( $fname );
1619 * Make a link placeholder. The text returned can be later resolved to a real link with
1620 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1621 * parsing of interwiki links, and secondly to allow all extistence checks and
1622 * article length checks (for stub links) to be bundled into a single query.
1625 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1626 if ( ! is_object($nt) ) {
1628 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1630 # Separate the link trail from the rest of the link
1631 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1633 if ( $nt->isExternal() ) {
1634 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1635 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1636 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1638 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1639 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1640 $this->mLinkHolders
['queries'][] = $query;
1641 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1642 $this->mLinkHolders
['titles'][] = $nt;
1644 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1651 * Render a forced-blue link inline; protect against double expansion of
1652 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1653 * Since this little disaster has to split off the trail text to avoid
1654 * breaking URLs in the following text without breaking trails on the
1655 * wiki links, it's been made into a horrible function.
1658 * @param string $text
1659 * @param string $query
1660 * @param string $trail
1661 * @param string $prefix
1662 * @return string HTML-wikitext mix oh yuck
1664 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1665 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1666 $sk =& $this->mOptions
->getSkin();
1667 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1668 return $this->armorLinks( $link ) . $trail;
1672 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1673 * going to go through further parsing steps before inline URL expansion.
1675 * In particular this is important when using action=render, which causes
1676 * full URLs to be included.
1678 * Oh man I hate our multi-layer parser!
1680 * @param string more-or-less HTML
1681 * @return string less-or-more HTML with NOPARSE bits
1683 function armorLinks( $text ) {
1684 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1685 "{$this->mUniqPrefix}NOPARSE$1", $text );
1689 * Return true if subpage links should be expanded on this page.
1692 function areSubpagesAllowed() {
1693 # Some namespaces don't allow subpages
1694 global $wgNamespacesWithSubpages;
1695 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1699 * Handle link to subpage if necessary
1700 * @param string $target the source of the link
1701 * @param string &$text the link text, modified as necessary
1702 * @return string the full name of the link
1705 function maybeDoSubpageLink($target, &$text) {
1708 # :Foobar -- override special treatment of prefix (images, language links)
1709 # /Foobar -- convert to CurrentPage/Foobar
1710 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1711 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1712 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1714 $fname = 'Parser::maybeDoSubpageLink';
1715 wfProfileIn( $fname );
1716 $ret = $target; # default return value is no change
1718 # Some namespaces don't allow subpages,
1719 # so only perform processing if subpages are allowed
1720 if( $this->areSubpagesAllowed() ) {
1721 # Look at the first character
1722 if( $target != '' && $target{0} == '/' ) {
1723 # / at end means we don't want the slash to be shown
1724 if( substr( $target, -1, 1 ) == '/' ) {
1725 $target = substr( $target, 1, -1 );
1728 $noslash = substr( $target, 1 );
1731 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1732 if( '' === $text ) {
1734 } # this might be changed for ugliness reasons
1736 # check for .. subpage backlinks
1738 $nodotdot = $target;
1739 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1741 $nodotdot = substr( $nodotdot, 3 );
1743 if($dotdotcount > 0) {
1744 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1745 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1746 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1747 # / at the end means don't show full path
1748 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1749 $nodotdot = substr( $nodotdot, 0, -1 );
1750 if( '' === $text ) {
1754 $nodotdot = trim( $nodotdot );
1755 if( $nodotdot != '' ) {
1756 $ret .= '/' . $nodotdot;
1763 wfProfileOut( $fname );
1768 * Used by doBlockLevels()
1771 /* private */ function closeParagraph() {
1773 if ( '' != $this->mLastSection
) {
1774 $result = '</' . $this->mLastSection
. ">\n";
1776 $this->mInPre
= false;
1777 $this->mLastSection
= '';
1780 # getCommon() returns the length of the longest common substring
1781 # of both arguments, starting at the beginning of both.
1783 /* private */ function getCommon( $st1, $st2 ) {
1784 $fl = strlen( $st1 );
1785 $shorter = strlen( $st2 );
1786 if ( $fl < $shorter ) { $shorter = $fl; }
1788 for ( $i = 0; $i < $shorter; ++
$i ) {
1789 if ( $st1{$i} != $st2{$i} ) { break; }
1793 # These next three functions open, continue, and close the list
1794 # element appropriate to the prefix character passed into them.
1796 /* private */ function openList( $char ) {
1797 $result = $this->closeParagraph();
1799 if ( '*' == $char ) { $result .= '<ul><li>'; }
1800 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1801 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1802 else if ( ';' == $char ) {
1803 $result .= '<dl><dt>';
1804 $this->mDTopen
= true;
1806 else { $result = '<!-- ERR 1 -->'; }
1811 /* private */ function nextItem( $char ) {
1812 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1813 else if ( ':' == $char ||
';' == $char ) {
1815 if ( $this->mDTopen
) { $close = '</dt>'; }
1816 if ( ';' == $char ) {
1817 $this->mDTopen
= true;
1818 return $close . '<dt>';
1820 $this->mDTopen
= false;
1821 return $close . '<dd>';
1824 return '<!-- ERR 2 -->';
1827 /* private */ function closeList( $char ) {
1828 if ( '*' == $char ) { $text = '</li></ul>'; }
1829 else if ( '#' == $char ) { $text = '</li></ol>'; }
1830 else if ( ':' == $char ) {
1831 if ( $this->mDTopen
) {
1832 $this->mDTopen
= false;
1833 $text = '</dt></dl>';
1835 $text = '</dd></dl>';
1838 else { return '<!-- ERR 3 -->'; }
1844 * Make lists from lines starting with ':', '*', '#', etc.
1847 * @return string the lists rendered as HTML
1849 function doBlockLevels( $text, $linestart ) {
1850 $fname = 'Parser::doBlockLevels';
1851 wfProfileIn( $fname );
1853 # Parsing through the text line by line. The main thing
1854 # happening here is handling of block-level elements p, pre,
1855 # and making lists from lines starting with * # : etc.
1857 $textLines = explode( "\n", $text );
1859 $lastPrefix = $output = '';
1860 $this->mDTopen
= $inBlockElem = false;
1862 $paragraphStack = false;
1864 if ( !$linestart ) {
1865 $output .= array_shift( $textLines );
1867 foreach ( $textLines as $oLine ) {
1868 $lastPrefixLength = strlen( $lastPrefix );
1869 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1870 $preOpenMatch = preg_match('/<pre/i', $oLine );
1871 if ( !$this->mInPre
) {
1872 # Multiple prefixes may abut each other for nested lists.
1873 $prefixLength = strspn( $oLine, '*#:;' );
1874 $pref = substr( $oLine, 0, $prefixLength );
1877 $pref2 = str_replace( ';', ':', $pref );
1878 $t = substr( $oLine, $prefixLength );
1879 $this->mInPre
= !empty($preOpenMatch);
1881 # Don't interpret any other prefixes in preformatted text
1883 $pref = $pref2 = '';
1888 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1889 # Same as the last item, so no need to deal with nesting or opening stuff
1890 $output .= $this->nextItem( substr( $pref, -1 ) );
1891 $paragraphStack = false;
1893 if ( substr( $pref, -1 ) == ';') {
1894 # The one nasty exception: definition lists work like this:
1895 # ; title : definition text
1896 # So we check for : in the remainder text to split up the
1897 # title and definition, without b0rking links.
1899 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1901 $output .= $term . $this->nextItem( ':' );
1904 } elseif( $prefixLength ||
$lastPrefixLength ) {
1905 # Either open or close a level...
1906 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1907 $paragraphStack = false;
1909 while( $commonPrefixLength < $lastPrefixLength ) {
1910 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1911 --$lastPrefixLength;
1913 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1914 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1916 while ( $prefixLength > $commonPrefixLength ) {
1917 $char = substr( $pref, $commonPrefixLength, 1 );
1918 $output .= $this->openList( $char );
1920 if ( ';' == $char ) {
1921 # FIXME: This is dupe of code above
1922 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1924 $output .= $term . $this->nextItem( ':' );
1927 ++
$commonPrefixLength;
1929 $lastPrefix = $pref2;
1931 if( 0 == $prefixLength ) {
1932 wfProfileIn( "$fname-paragraph" );
1933 # No prefix (not in list)--go to paragraph mode
1934 // XXX: use a stack for nestable elements like span, table and div
1935 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1936 $closematch = preg_match(
1937 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1938 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1939 if ( $openmatch or $closematch ) {
1940 $paragraphStack = false;
1941 $output .= $this->closeParagraph();
1942 if ( $preOpenMatch and !$preCloseMatch ) {
1943 $this->mInPre
= true;
1945 if ( $closematch ) {
1946 $inBlockElem = false;
1948 $inBlockElem = true;
1950 } else if ( !$inBlockElem && !$this->mInPre
) {
1951 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1953 if ($this->mLastSection
!= 'pre') {
1954 $paragraphStack = false;
1955 $output .= $this->closeParagraph().'<pre>';
1956 $this->mLastSection
= 'pre';
1958 $t = substr( $t, 1 );
1961 if ( '' == trim($t) ) {
1962 if ( $paragraphStack ) {
1963 $output .= $paragraphStack.'<br />';
1964 $paragraphStack = false;
1965 $this->mLastSection
= 'p';
1967 if ($this->mLastSection
!= 'p' ) {
1968 $output .= $this->closeParagraph();
1969 $this->mLastSection
= '';
1970 $paragraphStack = '<p>';
1972 $paragraphStack = '</p><p>';
1976 if ( $paragraphStack ) {
1977 $output .= $paragraphStack;
1978 $paragraphStack = false;
1979 $this->mLastSection
= 'p';
1980 } else if ($this->mLastSection
!= 'p') {
1981 $output .= $this->closeParagraph().'<p>';
1982 $this->mLastSection
= 'p';
1987 wfProfileOut( "$fname-paragraph" );
1989 // somewhere above we forget to get out of pre block (bug 785)
1990 if($preCloseMatch && $this->mInPre
) {
1991 $this->mInPre
= false;
1993 if ($paragraphStack === false) {
1997 while ( $prefixLength ) {
1998 $output .= $this->closeList( $pref2{$prefixLength-1} );
2001 if ( '' != $this->mLastSection
) {
2002 $output .= '</' . $this->mLastSection
. '>';
2003 $this->mLastSection
= '';
2006 wfProfileOut( $fname );
2011 * Split up a string on ':', ignoring any occurences inside
2012 * <a>..</a> or <span>...</span>
2013 * @param string $str the string to split
2014 * @param string &$before set to everything before the ':'
2015 * @param string &$after set to everything after the ':'
2016 * return string the position of the ':', or false if none found
2018 function findColonNoLinks($str, &$before, &$after) {
2019 # I wonder if we should make this count all tags, not just <a>
2020 # and <span>. That would prevent us from matching a ':' that
2021 # comes in the middle of italics other such formatting....
2023 $fname = 'Parser::findColonNoLinks';
2024 wfProfileIn( $fname );
2027 $colon = strpos($str, ':', $pos);
2029 if ($colon !== false) {
2030 $before = substr($str, 0, $colon);
2031 $after = substr($str, $colon +
1);
2033 # Skip any ':' within <a> or <span> pairs
2034 $a = substr_count($before, '<a');
2035 $s = substr_count($before, '<span');
2036 $ca = substr_count($before, '</a>');
2037 $cs = substr_count($before, '</span>');
2039 if ($a <= $ca and $s <= $cs) {
2040 # Tags are balanced before ':'; ok
2045 } while ($colon !== false);
2046 wfProfileOut( $fname );
2051 * Return value of a magic variable (like PAGENAME)
2055 function getVariableValue( $index ) {
2056 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2059 * Some of these require message or data lookups and can be
2060 * expensive to check many times.
2062 static $varCache = array();
2063 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2064 if ( isset( $varCache[$index] ) )
2065 return $varCache[$index];
2068 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2071 case MAG_CURRENTMONTH
:
2072 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2073 case MAG_CURRENTMONTHNAME
:
2074 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2075 case MAG_CURRENTMONTHNAMEGEN
:
2076 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2077 case MAG_CURRENTMONTHABBREV
:
2078 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2079 case MAG_CURRENTDAY
:
2080 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2081 case MAG_CURRENTDAY2
:
2082 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2084 return $this->mTitle
->getText();
2086 return $this->mTitle
->getPartialURL();
2087 case MAG_FULLPAGENAME
:
2088 return $this->mTitle
->getPrefixedText();
2089 case MAG_FULLPAGENAMEE
:
2090 return $this->mTitle
->getPrefixedURL();
2091 case MAG_SUBPAGENAME
:
2092 return $this->mTitle
->getSubpageText();
2093 case MAG_SUBPAGENAMEE
:
2094 return $this->mTitle
->getSubpageUrlForm();
2095 case MAG_REVISIONID
:
2096 return $this->mRevisionId
;
2098 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2099 case MAG_NAMESPACEE
:
2100 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2101 case MAG_CURRENTDAYNAME
:
2102 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2103 case MAG_CURRENTYEAR
:
2104 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2105 case MAG_CURRENTTIME
:
2106 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2107 case MAG_CURRENTWEEK
:
2108 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2109 // int to remove the padding
2110 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2111 case MAG_CURRENTDOW
:
2112 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2113 case MAG_NUMBEROFARTICLES
:
2114 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2115 case MAG_NUMBEROFFILES
:
2116 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2121 case MAG_SERVERNAME
:
2122 return $wgServerName;
2123 case MAG_SCRIPTPATH
:
2124 return $wgScriptPath;
2127 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2135 * initialise the magic variables (like CURRENTMONTHNAME)
2139 function initialiseVariables() {
2140 $fname = 'Parser::initialiseVariables';
2141 wfProfileIn( $fname );
2142 global $wgVariableIDs;
2143 $this->mVariables
= array();
2144 foreach ( $wgVariableIDs as $id ) {
2145 $mw =& MagicWord
::get( $id );
2146 $mw->addToArray( $this->mVariables
, $id );
2148 wfProfileOut( $fname );
2152 * parse any parentheses in format ((title|part|part))
2153 * and call callbacks to get a replacement text for any found piece
2155 * @param string $text The text to parse
2156 * @param array $callbacks rules in form:
2157 * '{' => array( # opening parentheses
2158 * 'end' => '}', # closing parentheses
2159 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2160 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2165 function replace_callback ($text, $callbacks) {
2166 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2167 $lastOpeningBrace = -1; # last not closed parentheses
2169 for ($i = 0; $i < strlen($text); $i++
) {
2170 # check for any opening brace
2173 foreach ($callbacks as $key => $value) {
2174 $pos = strpos ($text, $key, $i);
2175 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2181 if ($lastOpeningBrace >= 0) {
2182 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2184 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2189 $pos = strpos ($text, '|', $i);
2191 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2202 # found openning brace, lets add it to parentheses stack
2203 if (null != $rule) {
2204 $piece = array('brace' => $text[$i],
2205 'braceEnd' => $rule['end'],
2210 # count openning brace characters
2211 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2216 $piece['startAt'] = $i+
1;
2217 $piece['partStart'] = $i+
1;
2219 # we need to add to stack only if openning brace count is enough for any given rule
2220 foreach ($rule['cb'] as $cnt => $fn) {
2221 if ($piece['count'] >= $cnt) {
2222 $lastOpeningBrace ++
;
2223 $openingBraceStack[$lastOpeningBrace] = $piece;
2230 else if ($lastOpeningBrace >= 0) {
2231 # first check if it is a closing brace
2232 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2233 # lets check if it is enough characters for closing brace
2235 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2238 # if there are more closing parentheses than opening ones, we parse less
2239 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2240 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2242 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2244 $matchingCallback = null;
2245 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2246 if ($count >= $cnt && $matchingCount < $cnt) {
2247 $matchingCount = $cnt;
2248 $matchingCallback = $fn;
2252 if ($matchingCount == 0) {
2257 # lets set a title or last part (if '|' was found)
2258 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2259 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2261 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2263 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2264 $pieceEnd = $i +
$matchingCount;
2266 if( is_callable( $matchingCallback ) ) {
2268 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2269 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2270 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2271 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2273 # finally we can call a user callback and replace piece of text
2274 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2275 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2276 $i = $pieceStart +
strlen($replaceWith) - 1;
2279 # null value for callback means that parentheses should be parsed, but not replaced
2280 $i +
= $matchingCount - 1;
2283 # reset last openning parentheses, but keep it in case there are unused characters
2284 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2285 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2286 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2289 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2290 $openingBraceStack[$lastOpeningBrace--] = null;
2292 if ($matchingCount < $piece['count']) {
2293 $piece['count'] -= $matchingCount;
2294 $piece['startAt'] -= $matchingCount;
2295 $piece['partStart'] = $piece['startAt'];
2296 # do we still qualify for any callback with remaining count?
2297 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2298 if ($piece['count'] >= $cnt) {
2299 $lastOpeningBrace ++
;
2300 $openingBraceStack[$lastOpeningBrace] = $piece;
2308 # lets set a title if it is a first separator, or next part otherwise
2309 if ($text[$i] == '|') {
2310 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2311 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2312 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2315 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2317 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2326 * Replace magic variables, templates, and template arguments
2327 * with the appropriate text. Templates are substituted recursively,
2328 * taking care to avoid infinite loops.
2330 * Note that the substitution depends on value of $mOutputType:
2331 * OT_WIKI: only {{subst:}} templates
2332 * OT_MSG: only magic variables
2333 * OT_HTML: all templates and magic variables
2335 * @param string $tex The text to transform
2336 * @param array $args Key-value pairs representing template parameters to substitute
2337 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2340 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2341 # Prevent too big inclusions
2342 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2346 $fname = 'Parser::replaceVariables';
2347 wfProfileIn( $fname );
2349 # This function is called recursively. To keep track of arguments we need a stack:
2350 array_push( $this->mArgStack
, $args );
2352 $braceCallbacks = array();
2354 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2356 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2357 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2359 $callbacks = array();
2360 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2361 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2362 $text = $this->replace_callback ($text, $callbacks);
2364 array_pop( $this->mArgStack
);
2366 wfProfileOut( $fname );
2371 * Replace magic variables
2374 function variableSubstitution( $matches ) {
2375 $fname = 'Parser::variableSubstitution';
2376 $varname = $matches[1];
2377 wfProfileIn( $fname );
2378 if ( !$this->mVariables
) {
2379 $this->initialiseVariables();
2382 if ( $this->mOutputType
== OT_WIKI
) {
2383 # Do only magic variables prefixed by SUBST
2384 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2385 if (!$mwSubst->matchStartAndRemove( $varname ))
2387 # Note that if we don't substitute the variable below,
2388 # we don't remove the {{subst:}} magic word, in case
2389 # it is a template rather than a magic variable.
2391 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2392 $id = $this->mVariables
[$varname];
2393 $text = $this->getVariableValue( $id );
2394 $this->mOutput
->mContainsOldMagic
= true;
2396 $text = $matches[0];
2398 wfProfileOut( $fname );
2402 # Split template arguments
2403 function getTemplateArgs( $argsString ) {
2404 if ( $argsString === '' ) {
2408 $args = explode( '|', substr( $argsString, 1 ) );
2410 # If any of the arguments contains a '[[' but no ']]', it needs to be
2411 # merged with the next arg because the '|' character between belongs
2412 # to the link syntax and not the template parameter syntax.
2413 $argc = count($args);
2415 for ( $i = 0; $i < $argc-1; $i++
) {
2416 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2417 $args[$i] .= '|'.$args[$i+
1];
2418 array_splice($args, $i+
1, 1);
2428 * Return the text of a template, after recursively
2429 * replacing any variables or templates within the template.
2431 * @param array $piece The parts of the template
2432 * $piece['text']: matched text
2433 * $piece['title']: the title, i.e. the part before the |
2434 * $piece['parts']: the parameter array
2435 * @return string the text of the template
2438 function braceSubstitution( $piece ) {
2440 $fname = 'Parser::braceSubstitution';
2441 wfProfileIn( $fname );
2444 $found = false; # $text has been filled
2445 $nowiki = false; # wiki markup in $text should be escaped
2446 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2447 $noargs = false; # Don't replace triple-brace arguments in $text
2448 $replaceHeadings = false; # Make the edit section links go to the template not the article
2449 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2450 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2452 # Title object, where $text came from
2457 # $part1 is the bit before the first |, and must contain only title characters
2458 # $args is a list of arguments, starting from index 0, not including $part1
2460 $part1 = $piece['title'];
2461 # If the third subpattern matched anything, it will start with |
2463 if (null == $piece['parts']) {
2464 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2465 if ($replaceWith != $piece['text']) {
2466 $text = $replaceWith;
2473 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2474 $argc = count( $args );
2478 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2479 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2480 # One of two possibilities is true:
2481 # 1) Found SUBST but not in the PST phase
2482 # 2) Didn't find SUBST and in the PST phase
2483 # In either case, return without further processing
2484 $text = $piece['text'];
2491 # MSG, MSGNW, INT and RAW
2494 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2495 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2498 # Remove obsolete MSG:
2499 $mwMsg =& MagicWord
::get( MAG_MSG
);
2500 $mwMsg->matchStartAndRemove( $part1 );
2504 $mwRaw =& MagicWord
::get( MAG_RAW
);
2505 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2506 $forceRawInterwiki = true;
2509 # Check if it is an internal message
2510 $mwInt =& MagicWord
::get( MAG_INT
);
2511 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2512 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2513 $text = $linestart . wfMsgReal( $part1, $args, true );
2521 # Check for NS: (namespace expansion)
2522 $mwNs = MagicWord
::get( MAG_NS
);
2523 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2524 if ( intval( $part1 ) ||
$part1 == "0" ) {
2525 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2528 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2529 if ( !is_null( $index ) ) {
2530 $text = $linestart . $wgContLang->getNsText( $index );
2537 # LCFIRST, UCFIRST, LC and UC
2539 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2540 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2541 $lc =& MagicWord
::get( MAG_LC
);
2542 $uc =& MagicWord
::get( MAG_UC
);
2543 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2544 $text = $linestart . $wgContLang->lcfirst( $part1 );
2546 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2547 $text = $linestart . $wgContLang->ucfirst( $part1 );
2549 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2550 $text = $linestart . $wgContLang->lc( $part1 );
2552 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2553 $text = $linestart . $wgContLang->uc( $part1 );
2558 # LOCALURL and FULLURL
2560 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2561 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2562 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2563 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2566 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2567 $func = 'getLocalURL';
2568 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2569 $func = 'escapeLocalURL';
2570 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2571 $func = 'getFullURL';
2572 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2573 $func = 'escapeFullURL';
2578 if ( $func !== false ) {
2579 $title = Title
::newFromText( $part1 );
2580 if ( !is_null( $title ) ) {
2582 $text = $linestart . $title->$func( $args[0] );
2584 $text = $linestart . $title->$func();
2592 if ( !$found && $argc == 1 ) {
2593 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2594 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2595 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2601 if ( !$found && $argc >= 2 ) {
2602 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2603 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2604 if ($argc==2) {$args[2]=$args[1];}
2605 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2612 $colonPos = strpos( $part1, ':' );
2613 if ( $colonPos !== false ) {
2614 $function = strtolower( substr( $part1, 0, $colonPos ) );
2615 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2616 $funcArgs = array_merge( array( &$this, substr( $part1, $colonPos +
1 ) ), $args );
2617 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2619 if ( is_array( $result ) ) {
2620 $text = $linestart . $result[0];
2621 unset( $result[0] );
2623 // Extract flags into the local scope
2624 // This allows callers to set flags such as nowiki, noparse, found, etc.
2627 $text = $linestart . $result;
2633 # Template table test
2635 # Did we encounter this template already? If yes, it is in the cache
2636 # and we need to check for loops.
2637 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2640 # Infinite loop test
2641 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2645 $text = $linestart .
2646 '{{' . $part1 . '}}' .
2647 '<!-- WARNING: template loop detected -->';
2648 wfDebug( "$fname: template loop broken at '$part1'\n" );
2650 # set $text to cached message.
2651 $text = $linestart . $this->mTemplates
[$piece['title']];
2655 # Load from database
2656 $lastPathLevel = $this->mTemplatePath
;
2659 # declaring $subpage directly in the function call
2660 # does not work correctly with references and breaks
2661 # {{/subpage}}-style inclusions
2663 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2664 if ($subpage !== '') {
2665 $ns = $this->mTitle
->getNamespace();
2667 $title = Title
::newFromText( $part1, $ns );
2669 if ( !is_null( $title ) ) {
2670 if ( !$title->isExternal() ) {
2671 # Check for excessive inclusion
2672 $dbk = $title->getPrefixedDBkey();
2673 if ( $this->incrementIncludeCount( $dbk ) ) {
2674 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2675 # Capture special page output
2676 $text = SpecialPage
::capturePath( $title );
2677 if ( is_string( $text ) ) {
2682 $this->disableCache();
2685 $articleContent = $this->fetchTemplate( $title );
2686 if ( $articleContent !== false ) {
2688 $text = $articleContent;
2689 $replaceHeadings = true;
2694 # If the title is valid but undisplayable, make a link to it
2695 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2696 $text = '[['.$title->getPrefixedText().']]';
2699 } elseif ( $title->isTrans() ) {
2700 // Interwiki transclusion
2701 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2702 $text = $this->interwikiTransclude( $title, 'render' );
2706 $text = $this->interwikiTransclude( $title, 'raw' );
2707 $replaceHeadings = true;
2712 # Template cache array insertion
2713 # Use the original $piece['title'] not the mangled $part1, so that
2714 # modifiers such as RAW: produce separate cache entries
2716 $this->mTemplates
[$piece['title']] = $text;
2717 $text = $linestart . $text;
2722 # Recursive parsing, escaping and link table handling
2723 # Only for HTML output
2724 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2725 $text = wfEscapeWikiText( $text );
2726 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2728 # Clean up argument array
2729 $assocArgs = array();
2731 foreach( $args as $arg ) {
2732 $eqpos = strpos( $arg, '=' );
2733 if ( $eqpos === false ) {
2734 $assocArgs[$index++
] = $arg;
2736 $name = trim( substr( $arg, 0, $eqpos ) );
2737 $value = trim( substr( $arg, $eqpos+
1 ) );
2738 if ( $value === false ) {
2741 if ( $name !== false ) {
2742 $assocArgs[$name] = $value;
2747 # Add a new element to the templace recursion path
2748 $this->mTemplatePath
[$part1] = 1;
2752 # If there are any <onlyinclude> tags, only include them
2753 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2754 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2756 foreach ($m[1] as $piece)
2759 # Remove <noinclude> sections and <includeonly> tags
2760 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2761 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2763 if( $this->mOutputType
== OT_HTML
) {
2764 # Strip <nowiki>, <pre>, etc.
2765 $text = $this->strip( $text, $this->mStripState
);
2766 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2768 $text = $this->replaceVariables( $text, $assocArgs );
2770 # If the template begins with a table or block-level
2771 # element, it should be treated as beginning a new line.
2772 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2773 $text = "\n" . $text;
2775 } elseif ( !$noargs ) {
2776 # $noparse and !$noargs
2777 # Just replace the arguments, not any double-brace items
2778 # This is used for rendered interwiki transclusion
2779 $text = $this->replaceVariables( $text, $assocArgs, true );
2782 # Prune lower levels off the recursion check path
2783 $this->mTemplatePath
= $lastPathLevel;
2786 wfProfileOut( $fname );
2787 return $piece['text'];
2790 # Replace raw HTML by a placeholder
2791 # Add a blank line preceding, to prevent it from mucking up
2792 # immediately preceding headings
2793 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2795 # replace ==section headers==
2796 # XXX this needs to go away once we have a better parser.
2797 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2798 if( !is_null( $title ) )
2799 $encodedname = base64_encode($title->getPrefixedDBkey());
2801 $encodedname = base64_encode("");
2802 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2803 PREG_SPLIT_DELIM_CAPTURE
);
2806 for( $i = 0; $i < count($m); $i +
= 2 ) {
2808 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2810 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2814 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2815 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2816 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2824 # Prune lower levels off the recursion check path
2825 $this->mTemplatePath
= $lastPathLevel;
2828 wfProfileOut( $fname );
2829 return $piece['text'];
2831 wfProfileOut( $fname );
2837 * Fetch the unparsed text of a template and register a reference to it.
2839 function fetchTemplate( $title ) {
2841 // Loop to fetch the article, with up to 1 redirect
2842 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2843 $rev = Revision
::newFromTitle( $title );
2844 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2848 $text = $rev->getText();
2849 if ( $text === false ) {
2853 $title = Title
::newFromRedirect( $text );
2859 * Transclude an interwiki link.
2861 function interwikiTransclude( $title, $action ) {
2862 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2864 if (!$wgEnableScaryTranscluding)
2865 return wfMsg('scarytranscludedisabled');
2867 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2868 // But we'll handle it generally anyway
2869 if ( $title->getNamespace() ) {
2870 // Use the canonical namespace, which should work anywhere
2871 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2873 $articleName = $title->getDBkey();
2876 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2877 $url .= "?action=$action";
2878 if (strlen($url) > 255)
2879 return wfMsg('scarytranscludetoolong');
2880 return $this->fetchScaryTemplateMaybeFromCache($url);
2883 function fetchScaryTemplateMaybeFromCache($url) {
2884 global $wgTranscludeCacheExpiry;
2885 $dbr =& wfGetDB(DB_SLAVE
);
2886 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2887 array('tc_url' => $url));
2889 $time = $obj->tc_time
;
2890 $text = $obj->tc_contents
;
2891 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2896 $text = wfGetHTTP($url);
2898 return wfMsg('scarytranscludefailed', $url);
2900 $dbw =& wfGetDB(DB_MASTER
);
2901 $dbw->replace('transcache', array('tc_url'), array(
2903 'tc_time' => time(),
2904 'tc_contents' => $text));
2910 * Triple brace replacement -- used for template arguments
2913 function argSubstitution( $matches ) {
2914 $arg = trim( $matches['title'] );
2915 $text = $matches['text'];
2916 $inputArgs = end( $this->mArgStack
);
2918 if ( array_key_exists( $arg, $inputArgs ) ) {
2919 $text = $inputArgs[$arg];
2920 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2921 $text = $matches['parts'][0];
2928 * Returns true if the function is allowed to include this entity
2931 function incrementIncludeCount( $dbk ) {
2932 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2933 $this->mIncludeCount
[$dbk] = 0;
2935 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2943 * This function accomplishes several tasks:
2944 * 1) Auto-number headings if that option is enabled
2945 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2946 * 3) Add a Table of contents on the top for users who have enabled the option
2947 * 4) Auto-anchor headings
2949 * It loops through all headlines, collects the necessary data, then splits up the
2950 * string and re-inserts the newly formatted headlines.
2952 * @param string $text
2953 * @param boolean $isMain
2956 function formatHeadings( $text, $isMain=true ) {
2957 global $wgMaxTocLevel, $wgContLang;
2959 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2961 $forceTocHere = false;
2962 if( !$this->mTitle
->userCanEdit() ) {
2965 $showEditLink = $this->mOptions
->getEditSection();
2968 # Inhibit editsection links if requested in the page
2969 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2970 if( $esw->matchAndRemove( $text ) ) {
2973 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2975 $mw =& MagicWord
::get( MAG_NOTOC
);
2976 if( $mw->matchAndRemove( $text ) ) {
2980 # Get all headlines for numbering them and adding funky stuff like [edit]
2981 # links - this is for later, but we need the number of headlines right now
2982 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2984 # if there are fewer than 4 headlines in the article, do not show TOC
2985 if( $numMatches < 4 ) {
2989 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2990 # override above conditions and always show TOC at that place
2992 $mw =& MagicWord
::get( MAG_TOC
);
2993 if($mw->match( $text ) ) {
2995 $forceTocHere = true;
2997 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2998 # override above conditions and always show TOC above first header
2999 $mw =& MagicWord
::get( MAG_FORCETOC
);
3000 if ($mw->matchAndRemove( $text ) ) {
3005 # Never ever show TOC if no headers
3006 if( $numMatches < 1 ) {
3010 # We need this to perform operations on the HTML
3011 $sk =& $this->mOptions
->getSkin();
3015 $sectionCount = 0; # headlineCount excluding template sections
3017 # Ugh .. the TOC should have neat indentation levels which can be
3018 # passed to the skin functions. These are determined here
3022 $sublevelCount = array();
3023 $levelCount = array();
3030 foreach( $matches[3] as $headline ) {
3032 $templatetitle = '';
3033 $templatesection = 0;
3036 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3038 $templatetitle = base64_decode($mat[1]);
3039 $templatesection = 1 +
(int)base64_decode($mat[2]);
3040 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3044 $prevlevel = $level;
3045 $prevtoclevel = $toclevel;
3047 $level = $matches[1][$headlineCount];
3049 if( $doNumberHeadings ||
$doShowToc ) {
3051 if ( $level > $prevlevel ) {
3052 # Increase TOC level
3054 $sublevelCount[$toclevel] = 0;
3055 $toc .= $sk->tocIndent();
3057 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3058 # Decrease TOC level, find level to jump to
3060 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3061 # Can only go down to level 1
3064 for ($i = $toclevel; $i > 0; $i--) {
3065 if ( $levelCount[$i] == $level ) {
3066 # Found last matching level
3070 elseif ( $levelCount[$i] < $level ) {
3071 # Found first matching level below current level
3078 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3081 # No change in level, end TOC line
3082 $toc .= $sk->tocLineEnd();
3085 $levelCount[$toclevel] = $level;
3087 # count number of headlines for each level
3088 @$sublevelCount[$toclevel]++
;
3090 for( $i = 1; $i <= $toclevel; $i++
) {
3091 if( !empty( $sublevelCount[$i] ) ) {
3095 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3101 # The canonized header is a version of the header text safe to use for links
3102 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3103 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3104 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3106 # Remove link placeholders by the link text.
3107 # <!--LINK number-->
3109 # link text with suffix
3110 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3111 "\$this->mLinkHolders['texts'][\$1]",
3112 $canonized_headline );
3113 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3114 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3115 $canonized_headline );
3118 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3119 $tocline = trim( $canonized_headline );
3120 # Save headline for section edit hint before it's escaped
3121 $headline_hint = trim( $canonized_headline );
3122 $canonized_headline = Sanitizer
::escapeId( $tocline );
3123 $refers[$headlineCount] = $canonized_headline;
3125 # count how many in assoc. array so we can track dupes in anchors
3126 @$refers[$canonized_headline]++
;
3127 $refcount[$headlineCount]=$refers[$canonized_headline];
3129 # Don't number the heading if it is the only one (looks silly)
3130 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3131 # the two are different if the line contains a link
3132 $headline=$numbering . ' ' . $headline;
3135 # Create the anchor for linking from the TOC to the section
3136 $anchor = $canonized_headline;
3137 if($refcount[$headlineCount] > 1 ) {
3138 $anchor .= '_' . $refcount[$headlineCount];
3140 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3141 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3143 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3144 if ( empty( $head[$headlineCount] ) ) {
3145 $head[$headlineCount] = '';
3148 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3150 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3153 # give headline the correct <h#> tag
3154 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3162 $toc .= $sk->tocUnindent( $toclevel - 1 );
3163 $toc = $sk->tocList( $toc );
3166 # split up and insert constructed headlines
3168 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3171 foreach( $blocks as $block ) {
3172 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3173 # This is the [edit] link that appears for the top block of text when
3174 # section editing is enabled
3176 # Disabled because it broke block formatting
3177 # For example, a bullet point in the top line
3178 # $full .= $sk->editSectionLink(0);
3181 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3182 # Top anchor now in skin
3186 if( !empty( $head[$i] ) ) {
3192 $mw =& MagicWord
::get( MAG_TOC
);
3193 return $mw->replace( $toc, $full );
3200 * Return an HTML link for the "ISBN 123456" text
3203 function magicISBN( $text ) {
3204 $fname = 'Parser::magicISBN';
3205 wfProfileIn( $fname );
3207 $a = split( 'ISBN ', ' '.$text );
3208 if ( count ( $a ) < 2 ) {
3209 wfProfileOut( $fname );
3212 $text = substr( array_shift( $a ), 1);
3213 $valid = '0123456789-Xx';
3215 foreach ( $a as $x ) {
3216 # hack: don't replace inside thumbnail title/alt
3218 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3223 $isbn = $blank = '' ;
3224 while ( ' ' == $x{0} ) {
3226 $x = substr( $x, 1 );
3228 if ( $x == '' ) { # blank isbn
3229 $text .= "ISBN $blank";
3232 while ( strstr( $valid, $x{0} ) != false ) {
3234 $x = substr( $x, 1 );
3236 $num = str_replace( '-', '', $isbn );
3237 $num = str_replace( ' ', '', $num );
3238 $num = str_replace( 'x', 'X', $num );
3241 $text .= "ISBN $blank$x";
3243 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3244 $text .= '<a href="' .
3245 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3246 "\" class=\"internal\">ISBN $isbn</a>";
3250 wfProfileOut( $fname );
3255 * Return an HTML link for the "RFC 1234" text
3258 * @param string $text Text to be processed
3259 * @param string $keyword Magic keyword to use (default RFC)
3260 * @param string $urlmsg Interface message to use (default rfcurl)
3263 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3265 $valid = '0123456789';
3268 $a = split( $keyword, ' '.$text );
3269 if ( count ( $a ) < 2 ) {
3272 $text = substr( array_shift( $a ), 1);
3274 /* Check if keyword is preceed by [[.
3275 * This test is made here cause of the array_shift above
3276 * that prevent the test to be done in the foreach.
3278 if ( substr( $text, -2 ) == '[[' ) {
3282 foreach ( $a as $x ) {
3283 /* token might be empty if we have RFC RFC 1234 */
3289 # hack: don't replace inside thumbnail title/alt
3291 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3292 $text .= $keyword . $x;
3298 /** remove and save whitespaces in $blank */
3299 while ( $x{0} == ' ' ) {
3301 $x = substr( $x, 1 );
3304 /** remove and save the rfc number in $id */
3305 while ( strstr( $valid, $x{0} ) != false ) {
3307 $x = substr( $x, 1 );
3311 /* call back stripped spaces*/
3312 $text .= $keyword.$blank.$x;
3313 } elseif( $internal ) {
3315 $text .= $keyword.$id.$x;
3317 /* build the external link*/
3318 $url = wfMsg( $urlmsg, $id);
3319 $sk =& $this->mOptions
->getSkin();
3320 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3321 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3324 /* Check if the next RFC keyword is preceed by [[ */
3325 $internal = ( substr($x,-2) == '[[' );
3331 * Transform wiki markup when saving a page by doing \r\n -> \n
3332 * conversion, substitting signatures, {{subst:}} templates, etc.
3334 * @param string $text the text to transform
3335 * @param Title &$title the Title object for the current article
3336 * @param User &$user the User object describing the current user
3337 * @param ParserOptions $options parsing options
3338 * @param bool $clearState whether to clear the parser state first
3339 * @return string the altered wiki markup
3342 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3343 $this->mOptions
= $options;
3344 $this->mTitle
=& $title;
3345 $this->mOutputType
= OT_WIKI
;
3347 if ( $clearState ) {
3348 $this->clearState();
3351 $stripState = false;
3355 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3356 $text = $this->strip( $text, $stripState, true );
3357 $text = $this->pstPass2( $text, $user );
3358 $text = $this->unstrip( $text, $stripState );
3359 $text = $this->unstripNoWiki( $text, $stripState );
3364 * Pre-save transform helper function
3367 function pstPass2( $text, &$user ) {
3368 global $wgContLang, $wgLocaltimezone;
3370 /* Note: This is the timestamp saved as hardcoded wikitext to
3371 * the database, we use $wgContLang here in order to give
3372 * everyone the same signiture and use the default one rather
3373 * than the one selected in each users preferences.
3375 if ( isset( $wgLocaltimezone ) ) {
3376 $oldtz = getenv( 'TZ' );
3377 putenv( 'TZ='.$wgLocaltimezone );
3379 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3380 ' (' . date( 'T' ) . ')';
3381 if ( isset( $wgLocaltimezone ) ) {
3382 putenv( 'TZ='.$oldtz );
3385 # Variable replacement
3386 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3387 $text = $this->replaceVariables( $text );
3390 $sigText = $this->getUserSig( $user );
3391 $text = strtr( $text, array(
3393 '~~~~' => "$sigText $d",
3397 # Context links: [[|name]] and [[name (context)|]]
3399 global $wgLegalTitleChars;
3400 $tc = "[$wgLegalTitleChars]";
3401 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3403 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3404 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3406 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3407 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3408 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3409 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3411 $t = $this->mTitle
->getText();
3412 if ( preg_match( $conpat, $t, $m ) ) {
3415 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3416 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3417 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3419 if ( '' == $context ) {
3420 $text = preg_replace( $p2, '[[\\1]]', $text );
3422 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3425 # Trim trailing whitespace
3426 # MAG_END (__END__) tag allows for trailing
3427 # whitespace to be deliberately included
3428 $text = rtrim( $text );
3429 $mw =& MagicWord
::get( MAG_END
);
3430 $mw->matchAndRemove( $text );
3436 * Fetch the user's signature text, if any, and normalize to
3437 * validated, ready-to-insert wikitext.
3443 function getUserSig( &$user ) {
3444 $username = $user->getName();
3445 $nickname = $user->getOption( 'nickname' );
3446 $nickname = $nickname === '' ?
$username : $nickname;
3448 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3449 # Sig. might contain markup; validate this
3450 if( $this->validateSig( $nickname ) !== false ) {
3451 # Validated; clean up (if needed) and return it
3452 return( $this->cleanSig( $nickname ) );
3454 # Failed to validate; fall back to the default
3455 $nickname = $username;
3456 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3460 # If we're still here, make it a link to the user page
3461 $userpage = $user->getUserPage();
3462 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3466 * Check that the user's signature contains no bad XML
3468 * @param string $text
3469 * @return mixed An expanded string, or false if invalid.
3471 function validateSig( $text ) {
3472 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3476 * Clean up signature text
3478 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3479 * 2) Substitute all transclusions
3481 * @param string $text
3482 * @return string Signature text
3484 function cleanSig( $text ) {
3485 $substWord = MagicWord
::get( MAG_SUBST
);
3486 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3487 $substText = '{{' . $substWord->getSynonym( 0 );
3489 $text = preg_replace( $substRegex, $substText, $text );
3490 $text = preg_replace( '/~{3,5}/', '', $text );
3491 $text = $this->replaceVariables( $text );
3497 * Set up some variables which are usually set up in parse()
3498 * so that an external function can call some class members with confidence
3501 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3502 $this->mTitle
=& $title;
3503 $this->mOptions
= $options;
3504 $this->mOutputType
= $outputType;
3505 if ( $clearState ) {
3506 $this->clearState();
3511 * Transform a MediaWiki message by replacing magic variables.
3513 * @param string $text the text to transform
3514 * @param ParserOptions $options options
3515 * @return string the text with variables substituted
3518 function transformMsg( $text, $options ) {
3520 static $executing = false;
3522 $fname = "Parser::transformMsg";
3524 # Guard against infinite recursion
3530 wfProfileIn($fname);
3532 $this->mTitle
= $wgTitle;
3533 $this->mOptions
= $options;
3534 $this->mOutputType
= OT_MSG
;
3535 $this->clearState();
3536 $text = $this->replaceVariables( $text );
3539 wfProfileOut($fname);
3544 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3545 * The callback should have the following form:
3546 * function myParserHook( $text, $params, &$parser ) { ... }
3548 * Transform and return $text. Use $parser for any required context, e.g. use
3549 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3553 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3554 * @param mixed $callback The callback function (and object) to use for the tag
3556 * @return The old value of the mTagHooks array associated with the hook
3558 function setHook( $tag, $callback ) {
3559 $oldVal = @$this->mTagHooks
[$tag];
3560 $this->mTagHooks
[$tag] = $callback;
3566 * Create a function, e.g. {{sum:1|2|3}}
3567 * The callback function should have the form:
3568 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3570 * The callback may either return the text result of the function, or an array with the text
3571 * in element 0, and a number of flags in the other elements. The names of the flags are
3572 * specified in the keys. Valid flags are:
3573 * found The text returned is valid, stop processing the template. This
3575 * nowiki Wiki markup in the return value should be escaped
3576 * noparse Unsafe HTML tags should not be stripped, etc.
3577 * noargs Don't replace triple-brace arguments in the return value
3578 * isHTML The returned text is HTML, armour it against wikitext transformation
3582 * @param string $name The function name. Function names are case-insensitive.
3583 * @param mixed $callback The callback function (and object) to use
3585 * @return The old callback function for this name, if any
3587 function setFunctionHook( $name, $callback ) {
3588 $name = strtolower( $name );
3589 $oldVal = @$this->mFunctionHooks
[$name];
3590 $this->mFunctionHooks
[$name] = $callback;
3595 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3596 * Placeholders created in Skin::makeLinkObj()
3597 * Returns an array of links found, indexed by PDBK:
3601 * $options is a bit field, RLH_FOR_UPDATE to select for update
3603 function replaceLinkHolders( &$text, $options = 0 ) {
3605 global $wgOutputReplace;
3607 $fname = 'Parser::replaceLinkHolders';
3608 wfProfileIn( $fname );
3612 $sk =& $this->mOptions
->getSkin();
3613 $linkCache =& LinkCache
::singleton();
3615 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3616 wfProfileIn( $fname.'-check' );
3617 $dbr =& wfGetDB( DB_SLAVE
);
3618 $page = $dbr->tableName( 'page' );
3619 $threshold = $wgUser->getOption('stubthreshold');
3622 asort( $this->mLinkHolders
['namespaces'] );
3626 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3628 $title = $this->mLinkHolders
['titles'][$key];
3630 # Skip invalid entries.
3631 # Result will be ugly, but prevents crash.
3632 if ( is_null( $title ) ) {
3635 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3637 # Check if it's a static known link, e.g. interwiki
3638 if ( $title->isAlwaysKnown() ) {
3639 $colours[$pdbk] = 1;
3640 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3641 $colours[$pdbk] = 1;
3642 $this->mOutput
->addLink( $title, $id );
3643 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3644 $colours[$pdbk] = 0;
3646 # Not in the link cache, add it to the query
3647 if ( !isset( $current ) ) {
3649 $query = "SELECT page_id, page_namespace, page_title";
3650 if ( $threshold > 0 ) {
3651 $query .= ', page_len, page_is_redirect';
3653 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3654 } elseif ( $current != $ns ) {
3656 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3661 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3666 if ( $options & RLH_FOR_UPDATE
) {
3667 $query .= ' FOR UPDATE';
3670 $res = $dbr->query( $query, $fname );
3672 # Fetch data and form into an associative array
3673 # non-existent = broken
3676 while ( $s = $dbr->fetchObject($res) ) {
3677 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3678 $pdbk = $title->getPrefixedDBkey();
3679 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3680 $this->mOutput
->addLink( $title, $s->page_id
);
3682 if ( $threshold > 0 ) {
3683 $size = $s->page_len
;
3684 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3685 $colours[$pdbk] = 1;
3687 $colours[$pdbk] = 2;
3690 $colours[$pdbk] = 1;
3694 wfProfileOut( $fname.'-check' );
3696 # Construct search and replace arrays
3697 wfProfileIn( $fname.'-construct' );
3698 $wgOutputReplace = array();
3699 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3700 $pdbk = $pdbks[$key];
3701 $searchkey = "<!--LINK $key-->";
3702 $title = $this->mLinkHolders
['titles'][$key];
3703 if ( empty( $colours[$pdbk] ) ) {
3704 $linkCache->addBadLinkObj( $title );
3705 $colours[$pdbk] = 0;
3706 $this->mOutput
->addLink( $title, 0 );
3707 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3708 $this->mLinkHolders
['texts'][$key],
3709 $this->mLinkHolders
['queries'][$key] );
3710 } elseif ( $colours[$pdbk] == 1 ) {
3711 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3712 $this->mLinkHolders
['texts'][$key],
3713 $this->mLinkHolders
['queries'][$key] );
3714 } elseif ( $colours[$pdbk] == 2 ) {
3715 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3716 $this->mLinkHolders
['texts'][$key],
3717 $this->mLinkHolders
['queries'][$key] );
3720 wfProfileOut( $fname.'-construct' );
3723 wfProfileIn( $fname.'-replace' );
3725 $text = preg_replace_callback(
3726 '/(<!--LINK .*?-->)/',
3727 "wfOutputReplaceMatches",
3730 wfProfileOut( $fname.'-replace' );
3733 # Now process interwiki link holders
3734 # This is quite a bit simpler than internal links
3735 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3736 wfProfileIn( $fname.'-interwiki' );
3737 # Make interwiki link HTML
3738 $wgOutputReplace = array();
3739 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3740 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3741 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3744 $text = preg_replace_callback(
3745 '/<!--IWLINK (.*?)-->/',
3746 "wfOutputReplaceMatches",
3748 wfProfileOut( $fname.'-interwiki' );
3751 wfProfileOut( $fname );
3756 * Replace <!--LINK--> link placeholders with plain text of links
3757 * (not HTML-formatted).
3758 * @param string $text
3761 function replaceLinkHoldersText( $text ) {
3762 $fname = 'Parser::replaceLinkHoldersText';
3763 wfProfileIn( $fname );
3765 $text = preg_replace_callback(
3766 '/<!--(LINK|IWLINK) (.*?)-->/',
3767 array( &$this, 'replaceLinkHoldersTextCallback' ),
3770 wfProfileOut( $fname );
3775 * @param array $matches
3779 function replaceLinkHoldersTextCallback( $matches ) {
3780 $type = $matches[1];
3782 if( $type == 'LINK' ) {
3783 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3784 return $this->mLinkHolders
['texts'][$key];
3786 } elseif( $type == 'IWLINK' ) {
3787 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3788 return $this->mInterwikiLinkHolders
['texts'][$key];
3795 * Renders an image gallery from a text with one line per image.
3796 * text labels may be given by using |-style alternative text. E.g.
3797 * Image:one.jpg|The number "1"
3798 * Image:tree.jpg|A tree
3799 * given as text will return the HTML of a gallery with two images,
3800 * labeled 'The number "1"' and
3803 function renderImageGallery( $text ) {
3805 $parserOptions = new ParserOptions
;
3806 $localParser = new Parser();
3808 $ig = new ImageGallery();
3809 $ig->setShowBytes( false );
3810 $ig->setShowFilename( false );
3811 $lines = explode( "\n", $text );
3813 foreach ( $lines as $line ) {
3814 # match lines like these:
3815 # Image:someimage.jpg|This is some image
3816 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3818 if ( count( $matches ) == 0 ) {
3821 $nt =& Title
::newFromText( $matches[1] );
3822 if( is_null( $nt ) ) {
3823 # Bogus title. Ignore these so we don't bomb out later.
3826 if ( isset( $matches[3] ) ) {
3827 $label = $matches[3];
3832 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3833 $html = $pout->getText();
3835 $ig->add( new Image( $nt ), $html );
3836 $this->mOutput
->addImage( $nt->getDBkey() );
3838 return $ig->toHTML();
3842 * Parse image options text and use it to make an image
3844 function makeImage( &$nt, $options ) {
3845 global $wgUseImageResize;
3849 # Check if the options text is of the form "options|alt text"
3851 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3852 # * left no resizing, just left align. label is used for alt= only
3853 # * right same, but right aligned
3854 # * none same, but not aligned
3855 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3856 # * center center the image
3857 # * framed Keep original image size, no magnify-button.
3859 $part = explode( '|', $options);
3861 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3862 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3863 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3864 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3865 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3866 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3867 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3868 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3871 $width = $height = $framed = $thumb = false;
3872 $manual_thumb = '' ;
3874 foreach( $part as $key => $val ) {
3875 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3877 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3878 # use manually specified thumbnail
3880 $manual_thumb = $match;
3881 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3882 # remember to set an alignment, don't render immediately
3884 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3885 # remember to set an alignment, don't render immediately
3887 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3888 # remember to set an alignment, don't render immediately
3890 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3891 # remember to set an alignment, don't render immediately
3893 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3894 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3895 # $match is the image width in pixels
3896 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3897 $width = intval( $m[1] );
3898 $height = intval( $m[2] );
3900 $width = intval($match);
3902 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3908 # Strip bad stuff out of the alt text
3909 $alt = $this->replaceLinkHoldersText( $caption );
3911 # make sure there are no placeholders in thumbnail attributes
3912 # that are later expanded to html- so expand them now and
3914 $alt = $this->unstrip($alt, $this->mStripState
);
3915 $alt = Sanitizer
::stripAllTags( $alt );
3917 # Linker does the rest
3918 $sk =& $this->mOptions
->getSkin();
3919 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3923 * Set a flag in the output object indicating that the content is dynamic and
3924 * shouldn't be cached.
3926 function disableCache() {
3927 $this->mOutput
->mCacheTime
= -1;
3931 * Callback from the Sanitizer for expanding items found in HTML attribute
3932 * values, so they can be safely tested and escaped.
3933 * @param string $text
3934 * @param array $args
3938 function attributeStripCallback( &$text, $args ) {
3939 $text = $this->replaceVariables( $text, $args );
3940 $text = $this->unstripForHTML( $text );
3944 function unstripForHTML( $text ) {
3945 $text = $this->unstrip( $text, $this->mStripState
);
3946 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3954 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3955 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3956 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3962 function getTags() { return array_keys( $this->mTagHooks
); }
3968 * @package MediaWiki
3972 var $mText, # The output text
3973 $mLanguageLinks, # List of the full text of language links, in the order they appear
3974 $mCategories, # Map of category names to sort keys
3975 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3976 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
3977 $mVersion, # Compatibility check
3978 $mTitleText, # title text of the chosen language variant
3979 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3980 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3981 $mImages, # DB keys of the images used, in the array key only
3982 $mExternalLinks; # External link URLs, in the key only
3984 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3985 $containsOldMagic = false, $titletext = '' )
3987 $this->mText
= $text;
3988 $this->mLanguageLinks
= $languageLinks;
3989 $this->mCategories
= $categoryLinks;
3990 $this->mContainsOldMagic
= $containsOldMagic;
3991 $this->mCacheTime
= '';
3992 $this->mVersion
= MW_PARSER_VERSION
;
3993 $this->mTitleText
= $titletext;
3994 $this->mLinks
= array();
3995 $this->mTemplates
= array();
3996 $this->mImages
= array();
3997 $this->mExternalLinks
= array();
4000 function getText() { return $this->mText
; }
4001 function getLanguageLinks() { return $this->mLanguageLinks
; }
4002 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4003 function &getCategories() { return $this->mCategories
; }
4004 function getCacheTime() { return $this->mCacheTime
; }
4005 function getTitleText() { return $this->mTitleText
; }
4006 function &getLinks() { return $this->mLinks
; }
4007 function &getTemplates() { return $this->mTemplates
; }
4008 function &getImages() { return $this->mImages
; }
4009 function &getExternalLinks() { return $this->mExternalLinks
; }
4011 function containsOldMagic() { return $this->mContainsOldMagic
; }
4012 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4013 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4014 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4015 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4016 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4017 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4019 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4020 function addImage( $name ) { $this->mImages
[$name] = 1; }
4021 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4022 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4024 function addLink( $title, $id ) {
4025 $ns = $title->getNamespace();
4026 $dbk = $title->getDBkey();
4027 if ( !isset( $this->mLinks
[$ns] ) ) {
4028 $this->mLinks
[$ns] = array();
4030 $this->mLinks
[$ns][$dbk] = $id;
4033 function addTemplate( $title, $id ) {
4034 $ns = $title->getNamespace();
4035 $dbk = $title->getDBkey();
4036 if ( !isset( $this->mTemplates
[$ns] ) ) {
4037 $this->mTemplates
[$ns] = array();
4039 $this->mTemplates
[$ns][$dbk] = $id;
4046 function merge( $other ) {
4047 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
4048 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
4049 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
4053 * Return true if this cached output object predates the global or
4054 * per-article cache invalidation timestamps, or if it comes from
4055 * an incompatible older version.
4057 * @param string $touched the affected article's last touched timestamp
4061 function expired( $touched ) {
4062 global $wgCacheEpoch;
4063 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4064 $this->getCacheTime() < $touched ||
4065 $this->getCacheTime() <= $wgCacheEpoch ||
4066 !isset( $this->mVersion
) ||
4067 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4072 * Set options of the Parser
4074 * @package MediaWiki
4078 # All variables are private
4079 var $mUseTeX; # Use texvc to expand <math> tags
4080 var $mUseDynamicDates; # Use DateFormatter to format dates
4081 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4082 var $mAllowExternalImages; # Allow external images inline
4083 var $mAllowExternalImagesFrom; # If not, any exception?
4084 var $mSkin; # Reference to the preferred skin
4085 var $mDateFormat; # Date format index
4086 var $mEditSection; # Create "edit section" links
4087 var $mNumberHeadings; # Automatically number headings
4088 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4089 var $mTidy; # Ask for tidy cleanup
4091 function getUseTeX() { return $this->mUseTeX
; }
4092 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4093 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4094 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4095 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4096 function &getSkin() { return $this->mSkin
; }
4097 function getDateFormat() { return $this->mDateFormat
; }
4098 function getEditSection() { return $this->mEditSection
; }
4099 function getNumberHeadings() { return $this->mNumberHeadings
; }
4100 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4101 function getTidy() { return $this->mTidy
; }
4103 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4104 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4105 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4106 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4107 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4108 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4109 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4110 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4111 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4112 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4113 function setSkin( &$x ) { $this->mSkin
=& $x; }
4115 function ParserOptions() {
4117 $this->initialiseFromUser( $wgUser );
4121 * Get parser options
4124 function newFromUser( &$user ) {
4125 $popts = new ParserOptions
;
4126 $popts->initialiseFromUser( $user );
4130 /** Get user options */
4131 function initialiseFromUser( &$userInput ) {
4132 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4133 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4134 $fname = 'ParserOptions::initialiseFromUser';
4135 wfProfileIn( $fname );
4136 if ( !$userInput ) {
4138 $user->setLoaded( true );
4140 $user =& $userInput;
4143 $this->mUseTeX
= $wgUseTeX;
4144 $this->mUseDynamicDates
= $wgUseDynamicDates;
4145 $this->mInterwikiMagic
= $wgInterwikiMagic;
4146 $this->mAllowExternalImages
= $wgAllowExternalImages;
4147 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4148 wfProfileIn( $fname.'-skin' );
4149 $this->mSkin
=& $user->getSkin();
4150 wfProfileOut( $fname.'-skin' );
4151 $this->mDateFormat
= $user->getOption( 'date' );
4152 $this->mEditSection
= true;
4153 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4154 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4155 $this->mTidy
= false;
4156 wfProfileOut( $fname );
4161 * Callback function used by Parser::replaceLinkHolders()
4162 * to substitute link placeholders.
4164 function &wfOutputReplaceMatches( $matches ) {
4165 global $wgOutputReplace;
4166 return $wgOutputReplace[$matches[1]];
4170 * Return the total number of articles
4172 function wfNumberOfArticles() {
4173 global $wgNumberOfArticles;
4176 return $wgNumberOfArticles;
4180 * Return the number of files
4182 function wfNumberOfFiles() {
4183 $fname = 'wfNumberOfFiles';
4185 wfProfileIn( $fname );
4186 $dbr =& wfGetDB( DB_SLAVE
);
4187 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4188 wfProfileOut( $fname );
4194 * Get various statistics from the database
4197 function wfLoadSiteStats() {
4198 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4199 $fname = 'wfLoadSiteStats';
4201 if ( -1 != $wgNumberOfArticles ) return;
4202 $dbr =& wfGetDB( DB_SLAVE
);
4203 $s = $dbr->selectRow( 'site_stats',
4204 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4205 array( 'ss_row_id' => 1 ), $fname
4208 if ( $s === false ) {
4211 $wgTotalViews = $s->ss_total_views
;
4212 $wgTotalEdits = $s->ss_total_edits
;
4213 $wgNumberOfArticles = $s->ss_good_articles
;
4219 * Basically replacing " > and < with HTML entities ( ", >, <)
4221 * @param string $in Text that might contain HTML tags
4222 * @return string Escaped string
4224 function wfEscapeHTMLTagsOnly( $in ) {
4226 array( '"', '>', '<' ),
4227 array( '"', '>', '<' ),