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 //$text = $this->strip( $text, $this->mStripState );
205 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
206 $x =& $this->mStripState
;
208 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
209 $text = $this->strip( $text, $x );
210 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
212 # Hook to suspend the parser in this state
213 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
214 wfProfileOut( $fname );
218 $text = $this->internalParse( $text );
220 $text = $this->unstrip( $text, $this->mStripState
);
222 # Clean up special characters, only run once, next-to-last before doBlockLevels
224 # french spaces, last one Guillemet-left
225 # only if there is something before the space
226 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
227 # french spaces, Guillemet-right
228 '/(\\302\\253) /' => '\\1 ',
229 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
231 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
234 $text = $this->doBlockLevels( $text, $linestart );
236 $this->replaceLinkHolders( $text );
238 # the position of the parserConvert() call should not be changed. it
239 # assumes that the links are all replaced and the only thing left
240 # is the <nowiki> mark.
241 # Side-effects: this calls $this->mOutput->setTitleText()
242 $text = $wgContLang->parserConvert( $text, $this );
244 $text = $this->unstripNoWiki( $text, $this->mStripState
);
246 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
248 $text = Sanitizer
::normalizeCharReferences( $text );
250 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
251 $text = Parser
::tidy($text);
253 # attempt to sanitize at least some nesting problems
254 # (bug #2702 and quite a few others)
256 # ''Something [http://www.cool.com cool''] -->
257 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
258 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
259 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
260 # fix up an anchor inside another anchor, only
261 # at least for a single single nested link (bug 3695)
262 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
263 '\\1\\2</a>\\3</a>\\1\\4</a>',
264 # fix div inside inline elements- doBlockLevels won't wrap a line which
265 # contains a div, so fix it up here; replace
266 # div with escaped text
267 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
268 '\\1\\3<div\\5>\\6</div>\\8\\9',
269 # remove empty italic or bold tag pairs, some
270 # introduced by rules above
271 '/<([bi])><\/\\1>/' => ''
274 $text = preg_replace(
275 array_keys( $tidyregs ),
276 array_values( $tidyregs ),
280 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
282 $this->mOutput
->setText( $text );
283 wfProfileOut( $fname );
285 return $this->mOutput
;
289 * Get a random string
294 function getRandomString() {
295 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
298 function &getTitle() { return $this->mTitle
; }
299 function getOptions() { return $this->mOptions
; }
302 * Replaces all occurrences of <$tag>content</$tag> in the text
303 * with a random marker and returns the new text. the output parameter
304 * $content will be an associative array filled with data on the form
305 * $unique_marker => content.
307 * If $content is already set, the additional entries will be appended
308 * If $tag is set to STRIP_COMMENTS, the function will extract
309 * <!-- HTML comments -->
314 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
315 $rnd = $uniq_prefix . '-' . $tag . Parser
::getRandomString();
330 if( $tag == STRIP_COMMENTS
) {
334 $start = "/<$tag(\\s+[^>]*|\\s*\/?)>/i";
335 $end = "/<\\/$tag\\s*>/i";
338 while ( '' != $text ) {
339 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
341 if( count( $p ) < 3 ) {
347 // If $attributes ends with '/', we have an empty element tag, <tag />
348 if( $tag != STRIP_COMMENTS
&& substr( $attributes, -1 ) == '/' ) {
349 $attributes = substr( $attributes, 0, -1);
355 $marker = $rnd . sprintf('%08X', $n++
);
356 $stripped .= $marker;
358 $tags[$marker] = "<$tag$attributes$empty>";
359 $params[$marker] = Sanitizer
::decodeTagAttributes( $attributes );
361 if ( $empty === '/' ) {
362 // Empty element tag, <tag />
363 $content[$marker] = null;
366 $q = preg_split( $end, $inside, 2 );
367 $content[$marker] = $q[0];
368 if( count( $q ) < 2 ) {
369 # No end tag -- let it run out to the end of the text.
380 * Wrapper function for extractTagsAndParams
381 * for cases where $tags and $params isn't needed
382 * i.e. where tags will never have params, like <nowiki>
387 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
388 $dummy_tags = array();
389 $dummy_params = array();
391 return Parser
::extractTagsAndParams( $tag, $text, $content,
392 $dummy_tags, $dummy_params, $uniq_prefix );
396 * Strips and renders nowiki, pre, math, hiero
397 * If $render is set, performs necessary rendering operations on plugins
398 * Returns the text, and fills an array with data needed in unstrip()
399 * If the $state is already a valid strip state, it adds to the state
401 * @param bool $stripcomments when set, HTML comments <!-- like this -->
402 * will be stripped in addition to other tags. This is important
403 * for section editing, where these comments cause confusion when
404 * counting the sections in the wikisource
408 function strip( $text, &$state, $stripcomments = false ) {
409 $render = ($this->mOutputType
== OT_HTML
);
410 $html_content = array();
411 $nowiki_content = array();
412 $math_content = array();
413 $pre_content = array();
414 $comment_content = array();
415 $ext_content = array();
417 $ext_params = array();
418 $gallery_content = array();
420 # Replace any instances of the placeholders
421 $uniq_prefix = $this->mUniqPrefix
;
422 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
427 $text = Parser
::extractTags('html', $text, $html_content, $uniq_prefix);
428 foreach( $html_content as $marker => $content ) {
430 # Raw and unchecked for validity.
431 $html_content[$marker] = $content;
433 $html_content[$marker] = '<html>'.$content.'</html>';
439 $text = Parser
::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
440 foreach( $nowiki_content as $marker => $content ) {
442 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
444 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
449 if( $this->mOptions
->getUseTeX() ) {
450 $text = Parser
::extractTags('math', $text, $math_content, $uniq_prefix);
451 foreach( $math_content as $marker => $content ){
453 $math_content[$marker] = renderMath( $content );
455 $math_content[$marker] = '<math>'.$content.'</math>';
461 $text = Parser
::extractTags('pre', $text, $pre_content, $uniq_prefix);
462 foreach( $pre_content as $marker => $content ){
464 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
466 $pre_content[$marker] = '<pre>'.$content.'</pre>';
471 $text = Parser
::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
472 foreach( $gallery_content as $marker => $content ) {
473 require_once( 'ImageGallery.php' );
475 $gallery_content[$marker] = $this->renderImageGallery( $content );
477 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
482 $text = Parser
::extractTags(STRIP_COMMENTS
, $text, $comment_content, $uniq_prefix);
483 foreach( $comment_content as $marker => $content ){
484 $comment_content[$marker] = '<!--'.$content.'-->';
488 foreach ( $this->mTagHooks
as $tag => $callback ) {
489 $ext_content[$tag] = array();
490 $text = Parser
::extractTagsAndParams( $tag, $text, $ext_content[$tag],
491 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
492 foreach( $ext_content[$tag] as $marker => $content ) {
493 $full_tag = $ext_tags[$tag][$marker];
494 $params = $ext_params[$tag][$marker];
496 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
498 if ( is_null( $content ) ) {
500 $ext_content[$tag][$marker] = $full_tag;
502 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
508 # Unstrip comments unless explicitly told otherwise.
509 # (The comments are always stripped prior to this point, so as to
510 # not invoke any extension tags / parser hooks contained within
512 if ( !$stripcomments ) {
513 $tempstate = array( 'comment' => $comment_content );
514 $text = $this->unstrip( $text, $tempstate );
515 $comment_content = array();
518 # Merge state with the pre-existing state, if there is one
520 $state['html'] = $state['html'] +
$html_content;
521 $state['nowiki'] = $state['nowiki'] +
$nowiki_content;
522 $state['math'] = $state['math'] +
$math_content;
523 $state['pre'] = $state['pre'] +
$pre_content;
524 $state['gallery'] = $state['gallery'] +
$gallery_content;
525 $state['comment'] = $state['comment'] +
$comment_content;
527 foreach( $ext_content as $tag => $array ) {
528 if ( array_key_exists( $tag, $state ) ) {
529 $state[$tag] = $state[$tag] +
$array;
534 'html' => $html_content,
535 'nowiki' => $nowiki_content,
536 'math' => $math_content,
537 'pre' => $pre_content,
538 'gallery' => $gallery_content,
539 'comment' => $comment_content,
546 * restores pre, math, and hiero removed by strip()
548 * always call unstripNoWiki() after this one
551 function unstrip( $text, &$state ) {
552 if ( !is_array( $state ) ) {
556 # Must expand in reverse order, otherwise nested tags will be corrupted
557 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
558 if( $tag != 'nowiki' && $tag != 'html' ) {
559 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
560 $text = str_replace( $uniq, $content, $text );
569 * always call this after unstrip() to preserve the order
573 function unstripNoWiki( $text, &$state ) {
574 if ( !is_array( $state ) ) {
578 # Must expand in reverse order, otherwise nested tags will be corrupted
579 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
580 $text = str_replace( key( $state['nowiki'] ), $content, $text );
585 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
586 $text = str_replace( key( $state['html'] ), $content, $text );
594 * Add an item to the strip state
595 * Returns the unique tag which must be inserted into the stripped text
596 * The tag will be replaced with the original text in unstrip()
600 function insertStripItem( $text, &$state ) {
601 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
608 'comment' => array(),
609 'gallery' => array(),
612 $state['item'][$rnd] = $text;
617 * Interface with html tidy, used if $wgUseTidy = true.
618 * If tidy isn't able to correct the markup, the original will be
619 * returned in all its glory with a warning comment appended.
621 * Either the external tidy program or the in-process tidy extension
622 * will be used depending on availability. Override the default
623 * $wgTidyInternal setting to disable the internal if it's not working.
625 * @param string $text Hideous HTML input
626 * @return string Corrected HTML output
630 function tidy( $text ) {
631 global $wgTidyInternal;
632 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
633 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
634 '<head><title>test</title></head><body>'.$text.'</body></html>';
635 if( $wgTidyInternal ) {
636 $correctedtext = Parser
::internalTidy( $wrappedtext );
638 $correctedtext = Parser
::externalTidy( $wrappedtext );
640 if( is_null( $correctedtext ) ) {
641 wfDebug( "Tidy error detected!\n" );
642 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
644 return $correctedtext;
648 * Spawn an external HTML tidy process and get corrected markup back from it.
653 function externalTidy( $text ) {
654 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
655 $fname = 'Parser::externalTidy';
656 wfProfileIn( $fname );
661 $descriptorspec = array(
662 0 => array('pipe', 'r'),
663 1 => array('pipe', 'w'),
664 2 => array('file', '/dev/null', 'a')
667 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
668 if (is_resource($process)) {
669 // Theoretically, this style of communication could cause a deadlock
670 // here. If the stdout buffer fills up, then writes to stdin could
671 // block. This doesn't appear to happen with tidy, because tidy only
672 // writes to stdout after it's finished reading from stdin. Search
673 // for tidyParseStdin and tidySaveStdout in console/tidy.c
674 fwrite($pipes[0], $text);
676 while (!feof($pipes[1])) {
677 $cleansource .= fgets($pipes[1], 1024);
680 proc_close($process);
683 wfProfileOut( $fname );
685 if( $cleansource == '' && $text != '') {
686 // Some kind of error happened, so we couldn't get the corrected text.
687 // Just give up; we'll use the source text and append a warning.
695 * Use the HTML tidy PECL extension to use the tidy library in-process,
696 * saving the overhead of spawning a new process. Currently written to
697 * the PHP 4.3.x version of the extension, may not work on PHP 5.
699 * 'pear install tidy' should be able to compile the extension module.
704 function internalTidy( $text ) {
706 $fname = 'Parser::internalTidy';
707 wfProfileIn( $fname );
709 tidy_load_config( $wgTidyConf );
710 tidy_set_encoding( 'utf8' );
711 tidy_parse_string( $text );
713 if( tidy_get_status() == 2 ) {
714 // 2 is magic number for fatal error
715 // http://www.php.net/manual/en/function.tidy-get-status.php
718 $cleansource = tidy_get_output();
720 wfProfileOut( $fname );
725 * parse the wiki syntax used to render tables
729 function doTableStuff ( $t ) {
730 $fname = 'Parser::doTableStuff';
731 wfProfileIn( $fname );
733 $t = explode ( "\n" , $t ) ;
734 $td = array () ; # Is currently a td tag open?
735 $ltd = array () ; # Was it TD or TH?
736 $tr = array () ; # Is currently a tr tag open?
737 $ltr = array () ; # tr attributes
738 $has_opened_tr = array(); # Did this table open a <tr> element?
739 $indent_level = 0; # indent level of the table
740 foreach ( $t AS $k => $x )
743 $fc = substr ( $x , 0 , 1 ) ;
744 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
745 $indent_level = strlen( $matches[1] );
747 $attributes = $this->unstripForHTML( $matches[2] );
749 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
750 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
751 array_push ( $td , false ) ;
752 array_push ( $ltd , '' ) ;
753 array_push ( $tr , false ) ;
754 array_push ( $ltr , '' ) ;
755 array_push ( $has_opened_tr, false );
757 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
758 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
759 $z = "</table>" . substr ( $x , 2);
760 $l = array_pop ( $ltd ) ;
761 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
762 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
763 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
765 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
767 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
768 $x = substr ( $x , 1 ) ;
769 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
771 $l = array_pop ( $ltd ) ;
772 array_pop ( $has_opened_tr );
773 array_push ( $has_opened_tr , true ) ;
774 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
775 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
778 array_push ( $tr , false ) ;
779 array_push ( $td , false ) ;
780 array_push ( $ltd , '' ) ;
781 $attributes = $this->unstripForHTML( $x );
782 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
784 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
786 if ( '|+' == substr ( $x , 0 , 2 ) ) {
788 $x = substr ( $x , 1 ) ;
790 $after = substr ( $x , 1 ) ;
791 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
793 // Split up multiple cells on the same line.
794 // FIXME: This can result in improper nesting of tags processed
795 // by earlier parser steps, but should avoid splitting up eg
796 // attribute values containing literal "||".
797 $after = wfExplodeMarkup( '||', $after );
801 # Loop through each table cell
802 foreach ( $after AS $theline )
807 $tra = array_pop ( $ltr ) ;
808 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
809 array_push ( $tr , true ) ;
810 array_push ( $ltr , '' ) ;
811 array_pop ( $has_opened_tr );
812 array_push ( $has_opened_tr , true ) ;
815 $l = array_pop ( $ltd ) ;
816 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
817 if ( $fc == '|' ) $l = 'td' ;
818 else if ( $fc == '!' ) $l = 'th' ;
819 else if ( $fc == '+' ) $l = 'caption' ;
821 array_push ( $ltd , $l ) ;
824 $y = explode ( '|' , $theline , 2 ) ;
825 # Note that a '|' inside an invalid link should not
826 # be mistaken as delimiting cell parameters
827 if ( strpos( $y[0], '[[' ) !== false ) {
828 $y = array ($theline);
830 if ( count ( $y ) == 1 )
831 $y = "{$z}<{$l}>{$y[0]}" ;
833 $attributes = $this->unstripForHTML( $y[0] );
834 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
837 array_push ( $td , true ) ;
842 # Closing open td, tr && table
843 while ( count ( $td ) > 0 )
845 $l = array_pop ( $ltd ) ;
846 if ( array_pop ( $td ) ) $t[] = '</td>' ;
847 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
848 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
852 $t = implode ( "\n" , $t ) ;
853 # special case: don't return empty table
854 if($t == "<table>\n<tr><td></td></tr>\n</table>")
856 wfProfileOut( $fname );
861 * Helper function for parse() that transforms wiki markup into
862 * HTML. Only called for $mOutputType == OT_HTML.
866 function internalParse( $text ) {
869 $fname = 'Parser::internalParse';
870 wfProfileIn( $fname );
872 # Remove <noinclude> tags and <includeonly> sections
873 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
874 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
875 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
877 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
878 $text = $this->replaceVariables( $text, $args );
880 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
882 $text = $this->doHeadings( $text );
883 if($this->mOptions
->getUseDynamicDates()) {
884 $df =& DateFormatter
::getInstance();
885 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
887 $text = $this->doAllQuotes( $text );
888 $text = $this->replaceInternalLinks( $text );
889 $text = $this->replaceExternalLinks( $text );
891 # replaceInternalLinks may sometimes leave behind
892 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
893 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
895 $text = $this->doMagicLinks( $text );
896 $text = $this->doTableStuff( $text );
897 $text = $this->formatHeadings( $text, $isMain );
899 wfProfileOut( $fname );
904 * Replace special strings like "ISBN xxx" and "RFC xxx" with
905 * magic external links.
909 function &doMagicLinks( &$text ) {
910 $text = $this->magicISBN( $text );
911 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
912 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
917 * Parse headers and return html
921 function doHeadings( $text ) {
922 $fname = 'Parser::doHeadings';
923 wfProfileIn( $fname );
924 for ( $i = 6; $i >= 1; --$i ) {
925 $h = str_repeat( '=', $i );
926 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
927 "<h{$i}>\\1</h{$i}>\\2", $text );
929 wfProfileOut( $fname );
934 * Replace single quotes with HTML markup
936 * @return string the altered text
938 function doAllQuotes( $text ) {
939 $fname = 'Parser::doAllQuotes';
940 wfProfileIn( $fname );
942 $lines = explode( "\n", $text );
943 foreach ( $lines as $line ) {
944 $outtext .= $this->doQuotes ( $line ) . "\n";
946 $outtext = substr($outtext, 0,-1);
947 wfProfileOut( $fname );
952 * Helper function for doAllQuotes()
955 function doQuotes( $text ) {
956 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
957 if ( count( $arr ) == 1 )
961 # First, do some preliminary work. This may shift some apostrophes from
962 # being mark-up to being text. It also counts the number of occurrences
963 # of bold and italics mark-ups.
967 foreach ( $arr as $r )
969 if ( ( $i %
2 ) == 1 )
971 # If there are ever four apostrophes, assume the first is supposed to
972 # be text, and the remaining three constitute mark-up for bold text.
973 if ( strlen( $arr[$i] ) == 4 )
978 # If there are more than 5 apostrophes in a row, assume they're all
979 # text except for the last 5.
980 else if ( strlen( $arr[$i] ) > 5 )
982 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
985 # Count the number of occurrences of bold and italics mark-ups.
986 # We are not counting sequences of five apostrophes.
987 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
988 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
989 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
994 # If there is an odd number of both bold and italics, it is likely
995 # that one of the bold ones was meant to be an apostrophe followed
996 # by italics. Which one we cannot know for certain, but it is more
997 # likely to be one that has a single-letter word before it.
998 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1001 $firstsingleletterword = -1;
1002 $firstmultiletterword = -1;
1004 foreach ( $arr as $r )
1006 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1008 $x1 = substr ($arr[$i-1], -1);
1009 $x2 = substr ($arr[$i-1], -2, 1);
1011 if ($firstspace == -1) $firstspace = $i;
1012 } else if ($x2 == ' ') {
1013 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1015 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1021 # If there is a single-letter word, use it!
1022 if ($firstsingleletterword > -1)
1024 $arr [ $firstsingleletterword ] = "''";
1025 $arr [ $firstsingleletterword-1 ] .= "'";
1027 # If not, but there's a multi-letter word, use that one.
1028 else if ($firstmultiletterword > -1)
1030 $arr [ $firstmultiletterword ] = "''";
1031 $arr [ $firstmultiletterword-1 ] .= "'";
1033 # ... otherwise use the first one that has neither.
1034 # (notice that it is possible for all three to be -1 if, for example,
1035 # there is only one pentuple-apostrophe in the line)
1036 else if ($firstspace > -1)
1038 $arr [ $firstspace ] = "''";
1039 $arr [ $firstspace-1 ] .= "'";
1043 # Now let's actually convert our apostrophic mush to HTML!
1048 foreach ($arr as $r)
1052 if ($state == 'both')
1059 if (strlen ($r) == 2)
1062 { $output .= '</i>'; $state = ''; }
1063 else if ($state == 'bi')
1064 { $output .= '</i>'; $state = 'b'; }
1065 else if ($state == 'ib')
1066 { $output .= '</b></i><b>'; $state = 'b'; }
1067 else if ($state == 'both')
1068 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1069 else # $state can be 'b' or ''
1070 { $output .= '<i>'; $state .= 'i'; }
1072 else if (strlen ($r) == 3)
1075 { $output .= '</b>'; $state = ''; }
1076 else if ($state == 'bi')
1077 { $output .= '</i></b><i>'; $state = 'i'; }
1078 else if ($state == 'ib')
1079 { $output .= '</b>'; $state = 'i'; }
1080 else if ($state == 'both')
1081 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1082 else # $state can be 'i' or ''
1083 { $output .= '<b>'; $state .= 'b'; }
1085 else if (strlen ($r) == 5)
1088 { $output .= '</b><i>'; $state = 'i'; }
1089 else if ($state == 'i')
1090 { $output .= '</i><b>'; $state = 'b'; }
1091 else if ($state == 'bi')
1092 { $output .= '</i></b>'; $state = ''; }
1093 else if ($state == 'ib')
1094 { $output .= '</b></i>'; $state = ''; }
1095 else if ($state == 'both')
1096 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1097 else # ($state == '')
1098 { $buffer = ''; $state = 'both'; }
1103 # Now close all remaining tags. Notice that the order is important.
1104 if ($state == 'b' ||
$state == 'ib')
1106 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1110 if ($state == 'both')
1111 $output .= '<b><i>'.$buffer.'</i></b>';
1117 * Replace external links
1119 * Note: this is all very hackish and the order of execution matters a lot.
1120 * Make sure to run maintenance/parserTests.php if you change this code.
1124 function replaceExternalLinks( $text ) {
1126 $fname = 'Parser::replaceExternalLinks';
1127 wfProfileIn( $fname );
1129 $sk =& $this->mOptions
->getSkin();
1131 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1133 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1136 while ( $i<count( $bits ) ) {
1138 $protocol = $bits[$i++
];
1139 $text = $bits[$i++
];
1140 $trail = $bits[$i++
];
1142 # The characters '<' and '>' (which were escaped by
1143 # removeHTMLtags()) should not be included in
1144 # URLs, per RFC 2396.
1145 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1146 $text = substr($url, $m2[0][1]) . ' ' . $text;
1147 $url = substr($url, 0, $m2[0][1]);
1150 # If the link text is an image URL, replace it with an <img> tag
1151 # This happened by accident in the original parser, but some people used it extensively
1152 $img = $this->maybeMakeExternalImage( $text );
1153 if ( $img !== false ) {
1159 # Set linktype for CSS - if URL==text, link is essentially free
1160 $linktype = ($text == $url) ?
'free' : 'text';
1162 # No link text, e.g. [http://domain.tld/some.link]
1163 if ( $text == '' ) {
1164 # Autonumber if allowed
1165 if ( strpos( HTTP_PROTOCOLS
, str_replace('/','\/', $protocol) ) !== false ) {
1166 $text = '[' . ++
$this->mAutonumber
. ']';
1167 $linktype = 'autonumber';
1169 # Otherwise just use the URL
1170 $text = htmlspecialchars( $url );
1174 # Have link text, e.g. [http://domain.tld/some.link text]s
1176 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1179 $text = $wgContLang->markNoConversion($text);
1181 # Replace & from obsolete syntax with &.
1182 # All HTML entities will be escaped by makeExternalLink()
1183 $url = str_replace( '&', '&', $url );
1185 # Process the trail (i.e. everything after this link up until start of the next link),
1186 # replacing any non-bracketed links
1187 $trail = $this->replaceFreeExternalLinks( $trail );
1189 # Use the encoded URL
1190 # This means that users can paste URLs directly into the text
1191 # Funny characters like ö aren't valid in URLs anyway
1192 # This was changed in August 2004
1193 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1195 # Register link in the output object.
1196 # Replace unnecessary URL escape codes with the referenced character
1197 # This prevents spammers from hiding links from the filters
1198 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1199 $this->mOutput
->addExternalLink( $pasteurized );
1202 wfProfileOut( $fname );
1207 * Replace anything that looks like a URL with a link
1210 function replaceFreeExternalLinks( $text ) {
1212 $fname = 'Parser::replaceFreeExternalLinks';
1213 wfProfileIn( $fname );
1215 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1216 $s = array_shift( $bits );
1219 $sk =& $this->mOptions
->getSkin();
1221 while ( $i < count( $bits ) ){
1222 $protocol = $bits[$i++
];
1223 $remainder = $bits[$i++
];
1225 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1226 # Found some characters after the protocol that look promising
1227 $url = $protocol . $m[1];
1230 # special case: handle urls as url args:
1231 # http://www.example.com/foo?=http://www.example.com/bar
1232 if(strlen($trail) == 0 &&
1234 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1235 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1238 $url .= $bits[$i] . $bits[$i +
1]; # protocol, url as arg to previous link
1243 # The characters '<' and '>' (which were escaped by
1244 # removeHTMLtags()) should not be included in
1245 # URLs, per RFC 2396.
1246 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1247 $trail = substr($url, $m2[0][1]) . $trail;
1248 $url = substr($url, 0, $m2[0][1]);
1251 # Move trailing punctuation to $trail
1253 # If there is no left bracket, then consider right brackets fair game too
1254 if ( strpos( $url, '(' ) === false ) {
1258 $numSepChars = strspn( strrev( $url ), $sep );
1259 if ( $numSepChars ) {
1260 $trail = substr( $url, -$numSepChars ) . $trail;
1261 $url = substr( $url, 0, -$numSepChars );
1264 # Replace & from obsolete syntax with &.
1265 # All HTML entities will be escaped by makeExternalLink()
1266 # or maybeMakeExternalImage()
1267 $url = str_replace( '&', '&', $url );
1269 # Is this an external image?
1270 $text = $this->maybeMakeExternalImage( $url );
1271 if ( $text === false ) {
1272 # Not an image, make a link
1273 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1274 # Register it in the output object...
1275 # Replace unnecessary URL escape codes with their equivalent characters
1276 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1277 $this->mOutput
->addExternalLink( $pasteurized );
1279 $s .= $text . $trail;
1281 $s .= $protocol . $remainder;
1284 wfProfileOut( $fname );
1289 * Replace unusual URL escape codes with their equivalent characters
1293 * @fixme This can merge genuinely required bits in the path or query string,
1294 * breaking legit URLs. A proper fix would treat the various parts of
1295 * the URL differently; as a workaround, just use the output for
1296 * statistical records, not for actual linking/output.
1298 function replaceUnusualEscapes( $url ) {
1299 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1300 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1304 * Callback function used in replaceUnusualEscapes().
1305 * Replaces unusual URL escape codes with their equivalent character
1309 function replaceUnusualEscapesCallback( $matches ) {
1310 $char = urldecode( $matches[0] );
1311 $ord = ord( $char );
1312 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1313 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1314 // No, shouldn't be escaped
1317 // Yes, leave it escaped
1323 * make an image if it's allowed, either through the global
1324 * option or through the exception
1327 function maybeMakeExternalImage( $url ) {
1328 $sk =& $this->mOptions
->getSkin();
1329 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1330 $imagesexception = !empty($imagesfrom);
1332 if ( $this->mOptions
->getAllowExternalImages()
1333 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1334 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1336 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1343 * Process [[ ]] wikilinks
1347 function replaceInternalLinks( $s ) {
1349 static $fname = 'Parser::replaceInternalLinks' ;
1351 wfProfileIn( $fname );
1353 wfProfileIn( $fname.'-setup' );
1355 # the % is needed to support urlencoded titles as well
1356 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1358 $sk =& $this->mOptions
->getSkin();
1360 #split the entire text string on occurences of [[
1361 $a = explode( '[[', ' ' . $s );
1362 #get the first element (all text up to first [[), and remove the space we added
1363 $s = array_shift( $a );
1364 $s = substr( $s, 1 );
1366 # Match a link having the form [[namespace:link|alternate]]trail
1368 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1369 # Match cases where there is no "]]", which might still be images
1370 static $e1_img = FALSE;
1371 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1372 # Match the end of a line for a word that's not followed by whitespace,
1373 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1374 $e2 = wfMsgForContent( 'linkprefix' );
1376 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1378 if( is_null( $this->mTitle
) ) {
1379 wfDebugDieBacktrace( 'nooo' );
1381 $nottalk = !$this->mTitle
->isTalkPage();
1383 if ( $useLinkPrefixExtension ) {
1384 if ( preg_match( $e2, $s, $m ) ) {
1385 $first_prefix = $m[2];
1387 $first_prefix = false;
1393 $selflink = $this->mTitle
->getPrefixedText();
1394 wfProfileOut( $fname.'-setup' );
1396 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1397 $useSubpages = $this->areSubpagesAllowed();
1399 # Loop for each link
1400 for ($k = 0; isset( $a[$k] ); $k++
) {
1402 if ( $useLinkPrefixExtension ) {
1403 wfProfileIn( $fname.'-prefixhandling' );
1404 if ( preg_match( $e2, $s, $m ) ) {
1412 $prefix = $first_prefix;
1413 $first_prefix = false;
1415 wfProfileOut( $fname.'-prefixhandling' );
1418 $might_be_img = false;
1420 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1422 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1423 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1424 # the real problem is with the $e1 regex
1427 # Still some problems for cases where the ] is meant to be outside punctuation,
1428 # and no image is in sight. See bug 2095.
1431 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1432 strpos($text, '[') !== false
1435 $text .= ']'; # so that replaceExternalLinks($text) works later
1438 # fix up urlencoded title texts
1439 if(preg_match('/%/', $m[1] ))
1440 # Should anchors '#' also be rejected?
1441 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1443 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1444 $might_be_img = true;
1446 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1448 } else { # Invalid form; output directly
1449 $s .= $prefix . '[[' . $line ;
1453 # Don't allow internal links to pages containing
1454 # PROTO: where PROTO is a valid URL protocol; these
1455 # should be external links.
1456 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1457 $s .= $prefix . '[[' . $line ;
1461 # Make subpage if necessary
1462 if( $useSubpages ) {
1463 $link = $this->maybeDoSubpageLink( $m[1], $text );
1468 $noforce = (substr($m[1], 0, 1) != ':');
1470 # Strip off leading ':'
1471 $link = substr($link, 1);
1474 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1476 $s .= $prefix . '[[' . $line;
1480 #check other language variants of the link
1481 #if the article does not exist
1482 if( $checkVariantLink
1483 && $nt->getArticleID() == 0 ) {
1484 $wgContLang->findVariantLink($link, $nt);
1487 $ns = $nt->getNamespace();
1488 $iw = $nt->getInterWiki();
1490 if ($might_be_img) { # if this is actually an invalid link
1491 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1493 while (isset ($a[$k+
1]) ) {
1494 #look at the next 'line' to see if we can close it there
1495 $spliced = array_splice( $a, $k +
1, 1 );
1496 $next_line = array_shift( $spliced );
1497 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1498 # the first ]] closes the inner link, the second the image
1500 $text .= '[[' . $m[1];
1503 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1504 #if there's exactly one ]] that's fine, we'll keep looking
1505 $text .= '[[' . $m[0];
1507 #if $next_line is invalid too, we need look no further
1508 $text .= '[[' . $next_line;
1513 # we couldn't find the end of this imageLink, so output it raw
1514 #but don't ignore what might be perfectly normal links in the text we've examined
1515 $text = $this->replaceInternalLinks($text);
1516 $s .= $prefix . '[[' . $link . '|' . $text;
1517 # note: no $trail, because without an end, there *is* no trail
1520 } else { #it's not an image, so output it raw
1521 $s .= $prefix . '[[' . $link . '|' . $text;
1522 # note: no $trail, because without an end, there *is* no trail
1527 $wasblank = ( '' == $text );
1528 if( $wasblank ) $text = $link;
1531 # Link not escaped by : , create the various objects
1535 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1536 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1537 $s = rtrim($s . "\n");
1538 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1542 if ( $ns == NS_IMAGE
) {
1543 wfProfileIn( "$fname-image" );
1544 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1545 # recursively parse links inside the image caption
1546 # actually, this will parse them in any other parameters, too,
1547 # but it might be hard to fix that, and it doesn't matter ATM
1548 $text = $this->replaceExternalLinks($text);
1549 $text = $this->replaceInternalLinks($text);
1551 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1552 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1553 $this->mOutput
->addImage( $nt->getDBkey() );
1555 wfProfileOut( "$fname-image" );
1558 wfProfileOut( "$fname-image" );
1562 if ( $ns == NS_CATEGORY
) {
1563 wfProfileIn( "$fname-category" );
1564 $s = rtrim($s . "\n"); # bug 87
1567 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1568 $sortkey = $this->mTitle
->getText();
1570 $sortkey = $this->mTitle
->getPrefixedText();
1575 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1576 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1577 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1580 * Strip the whitespace Category links produce, see bug 87
1581 * @todo We might want to use trim($tmp, "\n") here.
1583 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1585 wfProfileOut( "$fname-category" );
1590 if( ( $nt->getPrefixedText() === $selflink ) &&
1591 ( $nt->getFragment() === '' ) ) {
1592 # Self-links are handled specially; generally de-link and change to bold.
1593 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1597 # Special and Media are pseudo-namespaces; no pages actually exist in them
1598 if( $ns == NS_MEDIA
) {
1599 $link = $sk->makeMediaLinkObj( $nt, $text );
1600 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1601 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1602 $this->mOutput
->addImage( $nt->getDBkey() );
1604 } elseif( $ns == NS_SPECIAL
) {
1605 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1607 } elseif( $ns == NS_IMAGE
) {
1608 $img = Image
::newFromTitle( $nt );
1609 if( $img->exists() ) {
1610 // Force a blue link if the file exists; may be a remote
1611 // upload on the shared repository, and we want to see its
1612 // auto-generated page.
1613 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1617 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1619 wfProfileOut( $fname );
1624 * Make a link placeholder. The text returned can be later resolved to a real link with
1625 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1626 * parsing of interwiki links, and secondly to allow all extistence checks and
1627 * article length checks (for stub links) to be bundled into a single query.
1630 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1631 if ( ! is_object($nt) ) {
1633 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1635 # Separate the link trail from the rest of the link
1636 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1638 if ( $nt->isExternal() ) {
1639 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1640 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1641 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1643 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1644 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1645 $this->mLinkHolders
['queries'][] = $query;
1646 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1647 $this->mLinkHolders
['titles'][] = $nt;
1649 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1656 * Render a forced-blue link inline; protect against double expansion of
1657 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1658 * Since this little disaster has to split off the trail text to avoid
1659 * breaking URLs in the following text without breaking trails on the
1660 * wiki links, it's been made into a horrible function.
1663 * @param string $text
1664 * @param string $query
1665 * @param string $trail
1666 * @param string $prefix
1667 * @return string HTML-wikitext mix oh yuck
1669 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1670 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1671 $sk =& $this->mOptions
->getSkin();
1672 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1673 return $this->armorLinks( $link ) . $trail;
1677 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1678 * going to go through further parsing steps before inline URL expansion.
1680 * In particular this is important when using action=render, which causes
1681 * full URLs to be included.
1683 * Oh man I hate our multi-layer parser!
1685 * @param string more-or-less HTML
1686 * @return string less-or-more HTML with NOPARSE bits
1688 function armorLinks( $text ) {
1689 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1690 "{$this->mUniqPrefix}NOPARSE$1", $text );
1694 * Return true if subpage links should be expanded on this page.
1697 function areSubpagesAllowed() {
1698 # Some namespaces don't allow subpages
1699 global $wgNamespacesWithSubpages;
1700 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1704 * Handle link to subpage if necessary
1705 * @param string $target the source of the link
1706 * @param string &$text the link text, modified as necessary
1707 * @return string the full name of the link
1710 function maybeDoSubpageLink($target, &$text) {
1713 # :Foobar -- override special treatment of prefix (images, language links)
1714 # /Foobar -- convert to CurrentPage/Foobar
1715 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1716 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1717 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1719 $fname = 'Parser::maybeDoSubpageLink';
1720 wfProfileIn( $fname );
1721 $ret = $target; # default return value is no change
1723 # Some namespaces don't allow subpages,
1724 # so only perform processing if subpages are allowed
1725 if( $this->areSubpagesAllowed() ) {
1726 # Look at the first character
1727 if( $target != '' && $target{0} == '/' ) {
1728 # / at end means we don't want the slash to be shown
1729 if( substr( $target, -1, 1 ) == '/' ) {
1730 $target = substr( $target, 1, -1 );
1733 $noslash = substr( $target, 1 );
1736 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1737 if( '' === $text ) {
1739 } # this might be changed for ugliness reasons
1741 # check for .. subpage backlinks
1743 $nodotdot = $target;
1744 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1746 $nodotdot = substr( $nodotdot, 3 );
1748 if($dotdotcount > 0) {
1749 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1750 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1751 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1752 # / at the end means don't show full path
1753 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1754 $nodotdot = substr( $nodotdot, 0, -1 );
1755 if( '' === $text ) {
1759 $nodotdot = trim( $nodotdot );
1760 if( $nodotdot != '' ) {
1761 $ret .= '/' . $nodotdot;
1768 wfProfileOut( $fname );
1773 * Used by doBlockLevels()
1776 /* private */ function closeParagraph() {
1778 if ( '' != $this->mLastSection
) {
1779 $result = '</' . $this->mLastSection
. ">\n";
1781 $this->mInPre
= false;
1782 $this->mLastSection
= '';
1785 # getCommon() returns the length of the longest common substring
1786 # of both arguments, starting at the beginning of both.
1788 /* private */ function getCommon( $st1, $st2 ) {
1789 $fl = strlen( $st1 );
1790 $shorter = strlen( $st2 );
1791 if ( $fl < $shorter ) { $shorter = $fl; }
1793 for ( $i = 0; $i < $shorter; ++
$i ) {
1794 if ( $st1{$i} != $st2{$i} ) { break; }
1798 # These next three functions open, continue, and close the list
1799 # element appropriate to the prefix character passed into them.
1801 /* private */ function openList( $char ) {
1802 $result = $this->closeParagraph();
1804 if ( '*' == $char ) { $result .= '<ul><li>'; }
1805 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1806 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1807 else if ( ';' == $char ) {
1808 $result .= '<dl><dt>';
1809 $this->mDTopen
= true;
1811 else { $result = '<!-- ERR 1 -->'; }
1816 /* private */ function nextItem( $char ) {
1817 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1818 else if ( ':' == $char ||
';' == $char ) {
1820 if ( $this->mDTopen
) { $close = '</dt>'; }
1821 if ( ';' == $char ) {
1822 $this->mDTopen
= true;
1823 return $close . '<dt>';
1825 $this->mDTopen
= false;
1826 return $close . '<dd>';
1829 return '<!-- ERR 2 -->';
1832 /* private */ function closeList( $char ) {
1833 if ( '*' == $char ) { $text = '</li></ul>'; }
1834 else if ( '#' == $char ) { $text = '</li></ol>'; }
1835 else if ( ':' == $char ) {
1836 if ( $this->mDTopen
) {
1837 $this->mDTopen
= false;
1838 $text = '</dt></dl>';
1840 $text = '</dd></dl>';
1843 else { return '<!-- ERR 3 -->'; }
1849 * Make lists from lines starting with ':', '*', '#', etc.
1852 * @return string the lists rendered as HTML
1854 function doBlockLevels( $text, $linestart ) {
1855 $fname = 'Parser::doBlockLevels';
1856 wfProfileIn( $fname );
1858 # Parsing through the text line by line. The main thing
1859 # happening here is handling of block-level elements p, pre,
1860 # and making lists from lines starting with * # : etc.
1862 $textLines = explode( "\n", $text );
1864 $lastPrefix = $output = '';
1865 $this->mDTopen
= $inBlockElem = false;
1867 $paragraphStack = false;
1869 if ( !$linestart ) {
1870 $output .= array_shift( $textLines );
1872 foreach ( $textLines as $oLine ) {
1873 $lastPrefixLength = strlen( $lastPrefix );
1874 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1875 $preOpenMatch = preg_match('/<pre/i', $oLine );
1876 if ( !$this->mInPre
) {
1877 # Multiple prefixes may abut each other for nested lists.
1878 $prefixLength = strspn( $oLine, '*#:;' );
1879 $pref = substr( $oLine, 0, $prefixLength );
1882 $pref2 = str_replace( ';', ':', $pref );
1883 $t = substr( $oLine, $prefixLength );
1884 $this->mInPre
= !empty($preOpenMatch);
1886 # Don't interpret any other prefixes in preformatted text
1888 $pref = $pref2 = '';
1893 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1894 # Same as the last item, so no need to deal with nesting or opening stuff
1895 $output .= $this->nextItem( substr( $pref, -1 ) );
1896 $paragraphStack = false;
1898 if ( substr( $pref, -1 ) == ';') {
1899 # The one nasty exception: definition lists work like this:
1900 # ; title : definition text
1901 # So we check for : in the remainder text to split up the
1902 # title and definition, without b0rking links.
1904 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1906 $output .= $term . $this->nextItem( ':' );
1909 } elseif( $prefixLength ||
$lastPrefixLength ) {
1910 # Either open or close a level...
1911 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1912 $paragraphStack = false;
1914 while( $commonPrefixLength < $lastPrefixLength ) {
1915 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1916 --$lastPrefixLength;
1918 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1919 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1921 while ( $prefixLength > $commonPrefixLength ) {
1922 $char = substr( $pref, $commonPrefixLength, 1 );
1923 $output .= $this->openList( $char );
1925 if ( ';' == $char ) {
1926 # FIXME: This is dupe of code above
1927 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1929 $output .= $term . $this->nextItem( ':' );
1932 ++
$commonPrefixLength;
1934 $lastPrefix = $pref2;
1936 if( 0 == $prefixLength ) {
1937 wfProfileIn( "$fname-paragraph" );
1938 # No prefix (not in list)--go to paragraph mode
1939 // XXX: use a stack for nestable elements like span, table and div
1940 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1941 $closematch = preg_match(
1942 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1943 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul)/iS', $t );
1944 if ( $openmatch or $closematch ) {
1945 $paragraphStack = false;
1946 $output .= $this->closeParagraph();
1947 if ( $preOpenMatch and !$preCloseMatch ) {
1948 $this->mInPre
= true;
1950 if ( $closematch ) {
1951 $inBlockElem = false;
1953 $inBlockElem = true;
1955 } else if ( !$inBlockElem && !$this->mInPre
) {
1956 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1958 if ($this->mLastSection
!= 'pre') {
1959 $paragraphStack = false;
1960 $output .= $this->closeParagraph().'<pre>';
1961 $this->mLastSection
= 'pre';
1963 $t = substr( $t, 1 );
1966 if ( '' == trim($t) ) {
1967 if ( $paragraphStack ) {
1968 $output .= $paragraphStack.'<br />';
1969 $paragraphStack = false;
1970 $this->mLastSection
= 'p';
1972 if ($this->mLastSection
!= 'p' ) {
1973 $output .= $this->closeParagraph();
1974 $this->mLastSection
= '';
1975 $paragraphStack = '<p>';
1977 $paragraphStack = '</p><p>';
1981 if ( $paragraphStack ) {
1982 $output .= $paragraphStack;
1983 $paragraphStack = false;
1984 $this->mLastSection
= 'p';
1985 } else if ($this->mLastSection
!= 'p') {
1986 $output .= $this->closeParagraph().'<p>';
1987 $this->mLastSection
= 'p';
1992 wfProfileOut( "$fname-paragraph" );
1994 // somewhere above we forget to get out of pre block (bug 785)
1995 if($preCloseMatch && $this->mInPre
) {
1996 $this->mInPre
= false;
1998 if ($paragraphStack === false) {
2002 while ( $prefixLength ) {
2003 $output .= $this->closeList( $pref2{$prefixLength-1} );
2006 if ( '' != $this->mLastSection
) {
2007 $output .= '</' . $this->mLastSection
. '>';
2008 $this->mLastSection
= '';
2011 wfProfileOut( $fname );
2016 * Split up a string on ':', ignoring any occurences inside
2017 * <a>..</a> or <span>...</span>
2018 * @param string $str the string to split
2019 * @param string &$before set to everything before the ':'
2020 * @param string &$after set to everything after the ':'
2021 * return string the position of the ':', or false if none found
2023 function findColonNoLinks($str, &$before, &$after) {
2024 # I wonder if we should make this count all tags, not just <a>
2025 # and <span>. That would prevent us from matching a ':' that
2026 # comes in the middle of italics other such formatting....
2028 $fname = 'Parser::findColonNoLinks';
2029 wfProfileIn( $fname );
2032 $colon = strpos($str, ':', $pos);
2034 if ($colon !== false) {
2035 $before = substr($str, 0, $colon);
2036 $after = substr($str, $colon +
1);
2038 # Skip any ':' within <a> or <span> pairs
2039 $a = substr_count($before, '<a');
2040 $s = substr_count($before, '<span');
2041 $ca = substr_count($before, '</a>');
2042 $cs = substr_count($before, '</span>');
2044 if ($a <= $ca and $s <= $cs) {
2045 # Tags are balanced before ':'; ok
2050 } while ($colon !== false);
2051 wfProfileOut( $fname );
2056 * Return value of a magic variable (like PAGENAME)
2060 function getVariableValue( $index ) {
2061 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2064 * Some of these require message or data lookups and can be
2065 * expensive to check many times.
2067 static $varCache = array();
2068 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2069 if ( isset( $varCache[$index] ) )
2070 return $varCache[$index];
2073 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2076 case MAG_CURRENTMONTH
:
2077 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2078 case MAG_CURRENTMONTHNAME
:
2079 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2080 case MAG_CURRENTMONTHNAMEGEN
:
2081 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2082 case MAG_CURRENTMONTHABBREV
:
2083 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2084 case MAG_CURRENTDAY
:
2085 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2086 case MAG_CURRENTDAY2
:
2087 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2089 return $this->mTitle
->getText();
2091 return $this->mTitle
->getPartialURL();
2092 case MAG_FULLPAGENAME
:
2093 return $this->mTitle
->getPrefixedText();
2094 case MAG_FULLPAGENAMEE
:
2095 return $this->mTitle
->getPrefixedURL();
2096 case MAG_SUBPAGENAME
:
2097 return $this->mTitle
->getSubpageText();
2098 case MAG_SUBPAGENAMEE
:
2099 return $this->mTitle
->getSubpageUrlForm();
2100 case MAG_REVISIONID
:
2101 return $this->mRevisionId
;
2103 return $wgContLang->getNsText( $this->mTitle
->getNamespace() );
2104 case MAG_NAMESPACEE
:
2105 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2106 case MAG_CURRENTDAYNAME
:
2107 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2108 case MAG_CURRENTYEAR
:
2109 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2110 case MAG_CURRENTTIME
:
2111 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2112 case MAG_CURRENTWEEK
:
2113 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2114 // int to remove the padding
2115 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2116 case MAG_CURRENTDOW
:
2117 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2118 case MAG_NUMBEROFARTICLES
:
2119 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2120 case MAG_NUMBEROFFILES
:
2121 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2126 case MAG_SERVERNAME
:
2127 return $wgServerName;
2128 case MAG_SCRIPTPATH
:
2129 return $wgScriptPath;
2132 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2140 * initialise the magic variables (like CURRENTMONTHNAME)
2144 function initialiseVariables() {
2145 $fname = 'Parser::initialiseVariables';
2146 wfProfileIn( $fname );
2147 global $wgVariableIDs;
2148 $this->mVariables
= array();
2149 foreach ( $wgVariableIDs as $id ) {
2150 $mw =& MagicWord
::get( $id );
2151 $mw->addToArray( $this->mVariables
, $id );
2153 wfProfileOut( $fname );
2157 * parse any parentheses in format ((title|part|part))
2158 * and call callbacks to get a replacement text for any found piece
2160 * @param string $text The text to parse
2161 * @param array $callbacks rules in form:
2162 * '{' => array( # opening parentheses
2163 * 'end' => '}', # closing parentheses
2164 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2165 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2170 function replace_callback ($text, $callbacks) {
2171 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2172 $lastOpeningBrace = -1; # last not closed parentheses
2174 for ($i = 0; $i < strlen($text); $i++
) {
2175 # check for any opening brace
2178 foreach ($callbacks as $key => $value) {
2179 $pos = strpos ($text, $key, $i);
2180 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2186 if ($lastOpeningBrace >= 0) {
2187 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2189 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2194 $pos = strpos ($text, '|', $i);
2196 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2207 # found openning brace, lets add it to parentheses stack
2208 if (null != $rule) {
2209 $piece = array('brace' => $text[$i],
2210 'braceEnd' => $rule['end'],
2215 # count openning brace characters
2216 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2221 $piece['startAt'] = $i+
1;
2222 $piece['partStart'] = $i+
1;
2224 # we need to add to stack only if openning brace count is enough for any given rule
2225 foreach ($rule['cb'] as $cnt => $fn) {
2226 if ($piece['count'] >= $cnt) {
2227 $lastOpeningBrace ++
;
2228 $openingBraceStack[$lastOpeningBrace] = $piece;
2235 else if ($lastOpeningBrace >= 0) {
2236 # first check if it is a closing brace
2237 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2238 # lets check if it is enough characters for closing brace
2240 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2243 # if there are more closing parentheses than opening ones, we parse less
2244 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2245 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2247 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2249 $matchingCallback = null;
2250 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2251 if ($count >= $cnt && $matchingCount < $cnt) {
2252 $matchingCount = $cnt;
2253 $matchingCallback = $fn;
2257 if ($matchingCount == 0) {
2262 # lets set a title or last part (if '|' was found)
2263 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2264 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2266 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2268 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2269 $pieceEnd = $i +
$matchingCount;
2271 if( is_callable( $matchingCallback ) ) {
2273 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2274 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2275 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2276 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2278 # finally we can call a user callback and replace piece of text
2279 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2280 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2281 $i = $pieceStart +
strlen($replaceWith) - 1;
2284 # null value for callback means that parentheses should be parsed, but not replaced
2285 $i +
= $matchingCount - 1;
2288 # reset last openning parentheses, but keep it in case there are unused characters
2289 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2290 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2291 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2294 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2295 $openingBraceStack[$lastOpeningBrace--] = null;
2297 if ($matchingCount < $piece['count']) {
2298 $piece['count'] -= $matchingCount;
2299 $piece['startAt'] -= $matchingCount;
2300 $piece['partStart'] = $piece['startAt'];
2301 # do we still qualify for any callback with remaining count?
2302 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2303 if ($piece['count'] >= $cnt) {
2304 $lastOpeningBrace ++
;
2305 $openingBraceStack[$lastOpeningBrace] = $piece;
2313 # lets set a title if it is a first separator, or next part otherwise
2314 if ($text[$i] == '|') {
2315 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2316 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2317 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2320 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2322 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2331 * Replace magic variables, templates, and template arguments
2332 * with the appropriate text. Templates are substituted recursively,
2333 * taking care to avoid infinite loops.
2335 * Note that the substitution depends on value of $mOutputType:
2336 * OT_WIKI: only {{subst:}} templates
2337 * OT_MSG: only magic variables
2338 * OT_HTML: all templates and magic variables
2340 * @param string $tex The text to transform
2341 * @param array $args Key-value pairs representing template parameters to substitute
2342 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2345 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2346 # Prevent too big inclusions
2347 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2351 $fname = 'Parser::replaceVariables';
2352 wfProfileIn( $fname );
2354 # This function is called recursively. To keep track of arguments we need a stack:
2355 array_push( $this->mArgStack
, $args );
2357 $braceCallbacks = array();
2359 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2361 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2362 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2364 $callbacks = array();
2365 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2366 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2367 $text = $this->replace_callback ($text, $callbacks);
2369 array_pop( $this->mArgStack
);
2371 wfProfileOut( $fname );
2376 * Replace magic variables
2379 function variableSubstitution( $matches ) {
2380 $fname = 'Parser::variableSubstitution';
2381 $varname = $matches[1];
2382 wfProfileIn( $fname );
2383 if ( !$this->mVariables
) {
2384 $this->initialiseVariables();
2387 if ( $this->mOutputType
== OT_WIKI
) {
2388 # Do only magic variables prefixed by SUBST
2389 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2390 if (!$mwSubst->matchStartAndRemove( $varname ))
2392 # Note that if we don't substitute the variable below,
2393 # we don't remove the {{subst:}} magic word, in case
2394 # it is a template rather than a magic variable.
2396 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2397 $id = $this->mVariables
[$varname];
2398 $text = $this->getVariableValue( $id );
2399 $this->mOutput
->mContainsOldMagic
= true;
2401 $text = $matches[0];
2403 wfProfileOut( $fname );
2407 # Split template arguments
2408 function getTemplateArgs( $argsString ) {
2409 if ( $argsString === '' ) {
2413 $args = explode( '|', substr( $argsString, 1 ) );
2415 # If any of the arguments contains a '[[' but no ']]', it needs to be
2416 # merged with the next arg because the '|' character between belongs
2417 # to the link syntax and not the template parameter syntax.
2418 $argc = count($args);
2420 for ( $i = 0; $i < $argc-1; $i++
) {
2421 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2422 $args[$i] .= '|'.$args[$i+
1];
2423 array_splice($args, $i+
1, 1);
2433 * Return the text of a template, after recursively
2434 * replacing any variables or templates within the template.
2436 * @param array $piece The parts of the template
2437 * $piece['text']: matched text
2438 * $piece['title']: the title, i.e. the part before the |
2439 * $piece['parts']: the parameter array
2440 * @return string the text of the template
2443 function braceSubstitution( $piece ) {
2445 $fname = 'Parser::braceSubstitution';
2446 wfProfileIn( $fname );
2449 $found = false; # $text has been filled
2450 $nowiki = false; # wiki markup in $text should be escaped
2451 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2452 $noargs = false; # Don't replace triple-brace arguments in $text
2453 $replaceHeadings = false; # Make the edit section links go to the template not the article
2454 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2455 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2457 # Title object, where $text came from
2462 # $part1 is the bit before the first |, and must contain only title characters
2463 # $args is a list of arguments, starting from index 0, not including $part1
2465 $part1 = $piece['title'];
2466 # If the third subpattern matched anything, it will start with |
2468 if (null == $piece['parts']) {
2469 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2470 if ($replaceWith != $piece['text']) {
2471 $text = $replaceWith;
2478 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2479 $argc = count( $args );
2483 $mwSubst =& MagicWord
::get( MAG_SUBST
);
2484 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2485 # One of two possibilities is true:
2486 # 1) Found SUBST but not in the PST phase
2487 # 2) Didn't find SUBST and in the PST phase
2488 # In either case, return without further processing
2489 $text = $piece['text'];
2496 # MSG, MSGNW, INT and RAW
2499 $mwMsgnw =& MagicWord
::get( MAG_MSGNW
);
2500 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2503 # Remove obsolete MSG:
2504 $mwMsg =& MagicWord
::get( MAG_MSG
);
2505 $mwMsg->matchStartAndRemove( $part1 );
2509 $mwRaw =& MagicWord
::get( MAG_RAW
);
2510 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2511 $forceRawInterwiki = true;
2514 # Check if it is an internal message
2515 $mwInt =& MagicWord
::get( MAG_INT
);
2516 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2517 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2518 $text = $linestart . wfMsgReal( $part1, $args, true );
2526 # Check for NS: (namespace expansion)
2527 $mwNs = MagicWord
::get( MAG_NS
);
2528 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2529 if ( intval( $part1 ) ||
$part1 == "0" ) {
2530 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2533 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2534 if ( !is_null( $index ) ) {
2535 $text = $linestart . $wgContLang->getNsText( $index );
2542 # LCFIRST, UCFIRST, LC and UC
2544 $lcfirst =& MagicWord
::get( MAG_LCFIRST
);
2545 $ucfirst =& MagicWord
::get( MAG_UCFIRST
);
2546 $lc =& MagicWord
::get( MAG_LC
);
2547 $uc =& MagicWord
::get( MAG_UC
);
2548 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2549 $text = $linestart . $wgContLang->lcfirst( $part1 );
2551 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2552 $text = $linestart . $wgContLang->ucfirst( $part1 );
2554 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2555 $text = $linestart . $wgContLang->lc( $part1 );
2557 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2558 $text = $linestart . $wgContLang->uc( $part1 );
2563 # LOCALURL and FULLURL
2565 $mwLocal =& MagicWord
::get( MAG_LOCALURL
);
2566 $mwLocalE =& MagicWord
::get( MAG_LOCALURLE
);
2567 $mwFull =& MagicWord
::get( MAG_FULLURL
);
2568 $mwFullE =& MagicWord
::get( MAG_FULLURLE
);
2571 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2572 $func = 'getLocalURL';
2573 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2574 $func = 'escapeLocalURL';
2575 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2576 $func = 'getFullURL';
2577 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2578 $func = 'escapeFullURL';
2583 if ( $func !== false ) {
2584 $title = Title
::newFromText( $part1 );
2585 if ( !is_null( $title ) ) {
2587 $text = $linestart . $title->$func( $args[0] );
2589 $text = $linestart . $title->$func();
2597 if ( !$found && $argc == 1 ) {
2598 $mwGrammar =& MagicWord
::get( MAG_GRAMMAR
);
2599 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2600 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2606 if ( !$found && $argc >= 2 ) {
2607 $mwPluralForm =& MagicWord
::get( MAG_PLURAL
);
2608 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2609 if ($argc==2) {$args[2]=$args[1];}
2610 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2617 $colonPos = strpos( $part1, ':' );
2618 if ( $colonPos !== false ) {
2619 $function = strtolower( substr( $part1, 0, $colonPos ) );
2620 if ( isset( $this->mFunctionHooks
[$function] ) ) {
2621 $funcArgs = array_merge( array( &$this, substr( $part1, $colonPos +
1 ) ), $args );
2622 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2624 if ( is_array( $result ) ) {
2625 $text = $linestart . $result[0];
2626 unset( $result[0] );
2628 // Extract flags into the local scope
2629 // This allows callers to set flags such as nowiki, noparse, found, etc.
2632 $text = $linestart . $result;
2638 # Template table test
2640 # Did we encounter this template already? If yes, it is in the cache
2641 # and we need to check for loops.
2642 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2645 # Infinite loop test
2646 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2650 $text = $linestart .
2651 '{{' . $part1 . '}}' .
2652 '<!-- WARNING: template loop detected -->';
2653 wfDebug( "$fname: template loop broken at '$part1'\n" );
2655 # set $text to cached message.
2656 $text = $linestart . $this->mTemplates
[$piece['title']];
2660 # Load from database
2661 $lastPathLevel = $this->mTemplatePath
;
2664 # declaring $subpage directly in the function call
2665 # does not work correctly with references and breaks
2666 # {{/subpage}}-style inclusions
2668 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2669 if ($subpage !== '') {
2670 $ns = $this->mTitle
->getNamespace();
2672 $title = Title
::newFromText( $part1, $ns );
2674 if ( !is_null( $title ) ) {
2675 if ( !$title->isExternal() ) {
2676 # Check for excessive inclusion
2677 $dbk = $title->getPrefixedDBkey();
2678 if ( $this->incrementIncludeCount( $dbk ) ) {
2679 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() ) {
2680 # Capture special page output
2681 $text = SpecialPage
::capturePath( $title );
2682 if ( is_string( $text ) ) {
2687 $this->disableCache();
2690 $articleContent = $this->fetchTemplate( $title );
2691 if ( $articleContent !== false ) {
2693 $text = $articleContent;
2694 $replaceHeadings = true;
2699 # If the title is valid but undisplayable, make a link to it
2700 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2701 $text = '[['.$title->getPrefixedText().']]';
2704 } elseif ( $title->isTrans() ) {
2705 // Interwiki transclusion
2706 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2707 $text = $this->interwikiTransclude( $title, 'render' );
2711 $text = $this->interwikiTransclude( $title, 'raw' );
2712 $replaceHeadings = true;
2717 # Template cache array insertion
2718 # Use the original $piece['title'] not the mangled $part1, so that
2719 # modifiers such as RAW: produce separate cache entries
2721 $this->mTemplates
[$piece['title']] = $text;
2722 $text = $linestart . $text;
2727 # Recursive parsing, escaping and link table handling
2728 # Only for HTML output
2729 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2730 $text = wfEscapeWikiText( $text );
2731 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2733 # Clean up argument array
2734 $assocArgs = array();
2736 foreach( $args as $arg ) {
2737 $eqpos = strpos( $arg, '=' );
2738 if ( $eqpos === false ) {
2739 $assocArgs[$index++
] = $arg;
2741 $name = trim( substr( $arg, 0, $eqpos ) );
2742 $value = trim( substr( $arg, $eqpos+
1 ) );
2743 if ( $value === false ) {
2746 if ( $name !== false ) {
2747 $assocArgs[$name] = $value;
2752 # Add a new element to the templace recursion path
2753 $this->mTemplatePath
[$part1] = 1;
2757 # If there are any <onlyinclude> tags, only include them
2758 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2759 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2761 foreach ($m[1] as $piece)
2764 # Remove <noinclude> sections and <includeonly> tags
2765 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2766 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2768 if( $this->mOutputType
== OT_HTML
) {
2769 # Strip <nowiki>, <pre>, etc.
2770 $text = $this->strip( $text, $this->mStripState
);
2771 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2773 $text = $this->replaceVariables( $text, $assocArgs );
2775 # If the template begins with a table or block-level
2776 # element, it should be treated as beginning a new line.
2777 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2778 $text = "\n" . $text;
2780 } elseif ( !$noargs ) {
2781 # $noparse and !$noargs
2782 # Just replace the arguments, not any double-brace items
2783 # This is used for rendered interwiki transclusion
2784 $text = $this->replaceVariables( $text, $assocArgs, true );
2787 # Prune lower levels off the recursion check path
2788 $this->mTemplatePath
= $lastPathLevel;
2791 wfProfileOut( $fname );
2792 return $piece['text'];
2795 # Replace raw HTML by a placeholder
2796 # Add a blank line preceding, to prevent it from mucking up
2797 # immediately preceding headings
2798 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2800 # replace ==section headers==
2801 # XXX this needs to go away once we have a better parser.
2802 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2803 if( !is_null( $title ) )
2804 $encodedname = base64_encode($title->getPrefixedDBkey());
2806 $encodedname = base64_encode("");
2807 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2808 PREG_SPLIT_DELIM_CAPTURE
);
2811 for( $i = 0; $i < count($m); $i +
= 2 ) {
2813 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2815 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2819 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2820 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2821 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2829 # Prune lower levels off the recursion check path
2830 $this->mTemplatePath
= $lastPathLevel;
2833 wfProfileOut( $fname );
2834 return $piece['text'];
2836 wfProfileOut( $fname );
2842 * Fetch the unparsed text of a template and register a reference to it.
2844 function fetchTemplate( $title ) {
2846 // Loop to fetch the article, with up to 1 redirect
2847 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2848 $rev = Revision
::newFromTitle( $title );
2849 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2853 $text = $rev->getText();
2854 if ( $text === false ) {
2858 $title = Title
::newFromRedirect( $text );
2864 * Transclude an interwiki link.
2866 function interwikiTransclude( $title, $action ) {
2867 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2869 if (!$wgEnableScaryTranscluding)
2870 return wfMsg('scarytranscludedisabled');
2872 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2873 // But we'll handle it generally anyway
2874 if ( $title->getNamespace() ) {
2875 // Use the canonical namespace, which should work anywhere
2876 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2878 $articleName = $title->getDBkey();
2881 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
2882 $url .= "?action=$action";
2883 if (strlen($url) > 255)
2884 return wfMsg('scarytranscludetoolong');
2885 return $this->fetchScaryTemplateMaybeFromCache($url);
2888 function fetchScaryTemplateMaybeFromCache($url) {
2889 global $wgTranscludeCacheExpiry;
2890 $dbr =& wfGetDB(DB_SLAVE
);
2891 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2892 array('tc_url' => $url));
2894 $time = $obj->tc_time
;
2895 $text = $obj->tc_contents
;
2896 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
2901 $text = wfGetHTTP($url);
2903 return wfMsg('scarytranscludefailed', $url);
2905 $dbw =& wfGetDB(DB_MASTER
);
2906 $dbw->replace('transcache', array('tc_url'), array(
2908 'tc_time' => time(),
2909 'tc_contents' => $text));
2915 * Triple brace replacement -- used for template arguments
2918 function argSubstitution( $matches ) {
2919 $arg = trim( $matches['title'] );
2920 $text = $matches['text'];
2921 $inputArgs = end( $this->mArgStack
);
2923 if ( array_key_exists( $arg, $inputArgs ) ) {
2924 $text = $inputArgs[$arg];
2925 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
2926 $text = $matches['parts'][0];
2933 * Returns true if the function is allowed to include this entity
2936 function incrementIncludeCount( $dbk ) {
2937 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
2938 $this->mIncludeCount
[$dbk] = 0;
2940 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
2948 * This function accomplishes several tasks:
2949 * 1) Auto-number headings if that option is enabled
2950 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2951 * 3) Add a Table of contents on the top for users who have enabled the option
2952 * 4) Auto-anchor headings
2954 * It loops through all headlines, collects the necessary data, then splits up the
2955 * string and re-inserts the newly formatted headlines.
2957 * @param string $text
2958 * @param boolean $isMain
2961 function formatHeadings( $text, $isMain=true ) {
2962 global $wgMaxTocLevel, $wgContLang;
2964 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
2966 $forceTocHere = false;
2967 if( !$this->mTitle
->userCanEdit() ) {
2970 $showEditLink = $this->mOptions
->getEditSection();
2973 # Inhibit editsection links if requested in the page
2974 $esw =& MagicWord
::get( MAG_NOEDITSECTION
);
2975 if( $esw->matchAndRemove( $text ) ) {
2978 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2980 $mw =& MagicWord
::get( MAG_NOTOC
);
2981 if( $mw->matchAndRemove( $text ) ) {
2985 # Get all headlines for numbering them and adding funky stuff like [edit]
2986 # links - this is for later, but we need the number of headlines right now
2987 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2989 # if there are fewer than 4 headlines in the article, do not show TOC
2990 if( $numMatches < 4 ) {
2994 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2995 # override above conditions and always show TOC at that place
2997 $mw =& MagicWord
::get( MAG_TOC
);
2998 if($mw->match( $text ) ) {
3000 $forceTocHere = true;
3002 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3003 # override above conditions and always show TOC above first header
3004 $mw =& MagicWord
::get( MAG_FORCETOC
);
3005 if ($mw->matchAndRemove( $text ) ) {
3010 # Never ever show TOC if no headers
3011 if( $numMatches < 1 ) {
3015 # We need this to perform operations on the HTML
3016 $sk =& $this->mOptions
->getSkin();
3020 $sectionCount = 0; # headlineCount excluding template sections
3022 # Ugh .. the TOC should have neat indentation levels which can be
3023 # passed to the skin functions. These are determined here
3027 $sublevelCount = array();
3028 $levelCount = array();
3035 foreach( $matches[3] as $headline ) {
3037 $templatetitle = '';
3038 $templatesection = 0;
3041 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3043 $templatetitle = base64_decode($mat[1]);
3044 $templatesection = 1 +
(int)base64_decode($mat[2]);
3045 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3049 $prevlevel = $level;
3050 $prevtoclevel = $toclevel;
3052 $level = $matches[1][$headlineCount];
3054 if( $doNumberHeadings ||
$doShowToc ) {
3056 if ( $level > $prevlevel ) {
3057 # Increase TOC level
3059 $sublevelCount[$toclevel] = 0;
3060 $toc .= $sk->tocIndent();
3062 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3063 # Decrease TOC level, find level to jump to
3065 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3066 # Can only go down to level 1
3069 for ($i = $toclevel; $i > 0; $i--) {
3070 if ( $levelCount[$i] == $level ) {
3071 # Found last matching level
3075 elseif ( $levelCount[$i] < $level ) {
3076 # Found first matching level below current level
3083 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3086 # No change in level, end TOC line
3087 $toc .= $sk->tocLineEnd();
3090 $levelCount[$toclevel] = $level;
3092 # count number of headlines for each level
3093 @$sublevelCount[$toclevel]++
;
3095 for( $i = 1; $i <= $toclevel; $i++
) {
3096 if( !empty( $sublevelCount[$i] ) ) {
3100 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3106 # The canonized header is a version of the header text safe to use for links
3107 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3108 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3109 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3111 # Remove link placeholders by the link text.
3112 # <!--LINK number-->
3114 # link text with suffix
3115 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3116 "\$this->mLinkHolders['texts'][\$1]",
3117 $canonized_headline );
3118 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3119 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3120 $canonized_headline );
3123 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3124 $tocline = trim( $canonized_headline );
3125 # Save headline for section edit hint before it's escaped
3126 $headline_hint = trim( $canonized_headline );
3127 $canonized_headline = Sanitizer
::escapeId( $tocline );
3128 $refers[$headlineCount] = $canonized_headline;
3130 # count how many in assoc. array so we can track dupes in anchors
3131 @$refers[$canonized_headline]++
;
3132 $refcount[$headlineCount]=$refers[$canonized_headline];
3134 # Don't number the heading if it is the only one (looks silly)
3135 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3136 # the two are different if the line contains a link
3137 $headline=$numbering . ' ' . $headline;
3140 # Create the anchor for linking from the TOC to the section
3141 $anchor = $canonized_headline;
3142 if($refcount[$headlineCount] > 1 ) {
3143 $anchor .= '_' . $refcount[$headlineCount];
3145 if( $doShowToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3146 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3148 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3149 if ( empty( $head[$headlineCount] ) ) {
3150 $head[$headlineCount] = '';
3153 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3155 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3158 # give headline the correct <h#> tag
3159 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3167 $toc .= $sk->tocUnindent( $toclevel - 1 );
3168 $toc = $sk->tocList( $toc );
3171 # split up and insert constructed headlines
3173 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3176 foreach( $blocks as $block ) {
3177 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3178 # This is the [edit] link that appears for the top block of text when
3179 # section editing is enabled
3181 # Disabled because it broke block formatting
3182 # For example, a bullet point in the top line
3183 # $full .= $sk->editSectionLink(0);
3186 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3187 # Top anchor now in skin
3191 if( !empty( $head[$i] ) ) {
3197 $mw =& MagicWord
::get( MAG_TOC
);
3198 return $mw->replace( $toc, $full );
3205 * Return an HTML link for the "ISBN 123456" text
3208 function magicISBN( $text ) {
3209 $fname = 'Parser::magicISBN';
3210 wfProfileIn( $fname );
3212 $a = split( 'ISBN ', ' '.$text );
3213 if ( count ( $a ) < 2 ) {
3214 wfProfileOut( $fname );
3217 $text = substr( array_shift( $a ), 1);
3218 $valid = '0123456789-Xx';
3220 foreach ( $a as $x ) {
3221 # hack: don't replace inside thumbnail title/alt
3223 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3228 $isbn = $blank = '' ;
3229 while ( ' ' == $x{0} ) {
3231 $x = substr( $x, 1 );
3233 if ( $x == '' ) { # blank isbn
3234 $text .= "ISBN $blank";
3237 while ( strstr( $valid, $x{0} ) != false ) {
3239 $x = substr( $x, 1 );
3241 $num = str_replace( '-', '', $isbn );
3242 $num = str_replace( ' ', '', $num );
3243 $num = str_replace( 'x', 'X', $num );
3246 $text .= "ISBN $blank$x";
3248 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3249 $text .= '<a href="' .
3250 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3251 "\" class=\"internal\">ISBN $isbn</a>";
3255 wfProfileOut( $fname );
3260 * Return an HTML link for the "RFC 1234" text
3263 * @param string $text Text to be processed
3264 * @param string $keyword Magic keyword to use (default RFC)
3265 * @param string $urlmsg Interface message to use (default rfcurl)
3268 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3270 $valid = '0123456789';
3273 $a = split( $keyword, ' '.$text );
3274 if ( count ( $a ) < 2 ) {
3277 $text = substr( array_shift( $a ), 1);
3279 /* Check if keyword is preceed by [[.
3280 * This test is made here cause of the array_shift above
3281 * that prevent the test to be done in the foreach.
3283 if ( substr( $text, -2 ) == '[[' ) {
3287 foreach ( $a as $x ) {
3288 /* token might be empty if we have RFC RFC 1234 */
3294 # hack: don't replace inside thumbnail title/alt
3296 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3297 $text .= $keyword . $x;
3303 /** remove and save whitespaces in $blank */
3304 while ( $x{0} == ' ' ) {
3306 $x = substr( $x, 1 );
3309 /** remove and save the rfc number in $id */
3310 while ( strstr( $valid, $x{0} ) != false ) {
3312 $x = substr( $x, 1 );
3316 /* call back stripped spaces*/
3317 $text .= $keyword.$blank.$x;
3318 } elseif( $internal ) {
3320 $text .= $keyword.$id.$x;
3322 /* build the external link*/
3323 $url = wfMsg( $urlmsg, $id);
3324 $sk =& $this->mOptions
->getSkin();
3325 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3326 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3329 /* Check if the next RFC keyword is preceed by [[ */
3330 $internal = ( substr($x,-2) == '[[' );
3336 * Transform wiki markup when saving a page by doing \r\n -> \n
3337 * conversion, substitting signatures, {{subst:}} templates, etc.
3339 * @param string $text the text to transform
3340 * @param Title &$title the Title object for the current article
3341 * @param User &$user the User object describing the current user
3342 * @param ParserOptions $options parsing options
3343 * @param bool $clearState whether to clear the parser state first
3344 * @return string the altered wiki markup
3347 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3348 $this->mOptions
= $options;
3349 $this->mTitle
=& $title;
3350 $this->mOutputType
= OT_WIKI
;
3352 if ( $clearState ) {
3353 $this->clearState();
3356 $stripState = false;
3360 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3361 $text = $this->strip( $text, $stripState, true );
3362 $text = $this->pstPass2( $text, $user );
3363 $text = $this->unstrip( $text, $stripState );
3364 $text = $this->unstripNoWiki( $text, $stripState );
3369 * Pre-save transform helper function
3372 function pstPass2( $text, &$user ) {
3373 global $wgContLang, $wgLocaltimezone;
3375 /* Note: This is the timestamp saved as hardcoded wikitext to
3376 * the database, we use $wgContLang here in order to give
3377 * everyone the same signiture and use the default one rather
3378 * than the one selected in each users preferences.
3380 if ( isset( $wgLocaltimezone ) ) {
3381 $oldtz = getenv( 'TZ' );
3382 putenv( 'TZ='.$wgLocaltimezone );
3384 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3385 ' (' . date( 'T' ) . ')';
3386 if ( isset( $wgLocaltimezone ) ) {
3387 putenv( 'TZ='.$oldtz );
3390 # Variable replacement
3391 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3392 $text = $this->replaceVariables( $text );
3395 $sigText = $this->getUserSig( $user );
3396 $text = strtr( $text, array(
3398 '~~~~' => "$sigText $d",
3402 # Context links: [[|name]] and [[name (context)|]]
3404 global $wgLegalTitleChars;
3405 $tc = "[$wgLegalTitleChars]";
3406 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3408 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3409 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3411 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3412 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3413 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3414 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3416 $t = $this->mTitle
->getText();
3417 if ( preg_match( $conpat, $t, $m ) ) {
3420 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3421 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3422 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3424 if ( '' == $context ) {
3425 $text = preg_replace( $p2, '[[\\1]]', $text );
3427 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3430 # Trim trailing whitespace
3431 # MAG_END (__END__) tag allows for trailing
3432 # whitespace to be deliberately included
3433 $text = rtrim( $text );
3434 $mw =& MagicWord
::get( MAG_END
);
3435 $mw->matchAndRemove( $text );
3441 * Fetch the user's signature text, if any, and normalize to
3442 * validated, ready-to-insert wikitext.
3448 function getUserSig( &$user ) {
3449 $username = $user->getName();
3450 $nickname = $user->getOption( 'nickname' );
3451 $nickname = $nickname === '' ?
$username : $nickname;
3453 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3454 # Sig. might contain markup; validate this
3455 if( $this->validateSig( $nickname ) !== false ) {
3456 # Validated; clean up (if needed) and return it
3457 return( $this->cleanSig( $nickname ) );
3459 # Failed to validate; fall back to the default
3460 $nickname = $username;
3461 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3465 # If we're still here, make it a link to the user page
3466 $userpage = $user->getUserPage();
3467 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3471 * Check that the user's signature contains no bad XML
3473 * @param string $text
3474 * @return mixed An expanded string, or false if invalid.
3476 function validateSig( $text ) {
3477 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3481 * Clean up signature text
3483 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3484 * 2) Substitute all transclusions
3486 * @param string $text
3487 * @return string Signature text
3489 function cleanSig( $text ) {
3490 $substWord = MagicWord
::get( MAG_SUBST
);
3491 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3492 $substText = '{{' . $substWord->getSynonym( 0 );
3494 $text = preg_replace( $substRegex, $substText, $text );
3495 $text = preg_replace( '/~{3,5}/', '', $text );
3496 $text = $this->replaceVariables( $text );
3502 * Set up some variables which are usually set up in parse()
3503 * so that an external function can call some class members with confidence
3506 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3507 $this->mTitle
=& $title;
3508 $this->mOptions
= $options;
3509 $this->mOutputType
= $outputType;
3510 if ( $clearState ) {
3511 $this->clearState();
3516 * Transform a MediaWiki message by replacing magic variables.
3518 * @param string $text the text to transform
3519 * @param ParserOptions $options options
3520 * @return string the text with variables substituted
3523 function transformMsg( $text, $options ) {
3525 static $executing = false;
3527 $fname = "Parser::transformMsg";
3529 # Guard against infinite recursion
3535 wfProfileIn($fname);
3537 $this->mTitle
= $wgTitle;
3538 $this->mOptions
= $options;
3539 $this->mOutputType
= OT_MSG
;
3540 $this->clearState();
3541 $text = $this->replaceVariables( $text );
3544 wfProfileOut($fname);
3549 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3550 * The callback should have the following form:
3551 * function myParserHook( $text, $params, &$parser ) { ... }
3553 * Transform and return $text. Use $parser for any required context, e.g. use
3554 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3558 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3559 * @param mixed $callback The callback function (and object) to use for the tag
3561 * @return The old value of the mTagHooks array associated with the hook
3563 function setHook( $tag, $callback ) {
3564 $oldVal = @$this->mTagHooks
[$tag];
3565 $this->mTagHooks
[$tag] = $callback;
3571 * Create a function, e.g. {{sum:1|2|3}}
3572 * The callback function should have the form:
3573 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3575 * The callback may either return the text result of the function, or an array with the text
3576 * in element 0, and a number of flags in the other elements. The names of the flags are
3577 * specified in the keys. Valid flags are:
3578 * found The text returned is valid, stop processing the template. This
3580 * nowiki Wiki markup in the return value should be escaped
3581 * noparse Unsafe HTML tags should not be stripped, etc.
3582 * noargs Don't replace triple-brace arguments in the return value
3583 * isHTML The returned text is HTML, armour it against wikitext transformation
3587 * @param string $name The function name. Function names are case-insensitive.
3588 * @param mixed $callback The callback function (and object) to use
3590 * @return The old callback function for this name, if any
3592 function setFunctionHook( $name, $callback ) {
3593 $name = strtolower( $name );
3594 $oldVal = @$this->mFunctionHooks
[$name];
3595 $this->mFunctionHooks
[$name] = $callback;
3600 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3601 * Placeholders created in Skin::makeLinkObj()
3602 * Returns an array of links found, indexed by PDBK:
3606 * $options is a bit field, RLH_FOR_UPDATE to select for update
3608 function replaceLinkHolders( &$text, $options = 0 ) {
3610 global $wgOutputReplace;
3612 $fname = 'Parser::replaceLinkHolders';
3613 wfProfileIn( $fname );
3617 $sk =& $this->mOptions
->getSkin();
3618 $linkCache =& LinkCache
::singleton();
3620 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3621 wfProfileIn( $fname.'-check' );
3622 $dbr =& wfGetDB( DB_SLAVE
);
3623 $page = $dbr->tableName( 'page' );
3624 $threshold = $wgUser->getOption('stubthreshold');
3627 asort( $this->mLinkHolders
['namespaces'] );
3631 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3633 $title = $this->mLinkHolders
['titles'][$key];
3635 # Skip invalid entries.
3636 # Result will be ugly, but prevents crash.
3637 if ( is_null( $title ) ) {
3640 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3642 # Check if it's a static known link, e.g. interwiki
3643 if ( $title->isAlwaysKnown() ) {
3644 $colours[$pdbk] = 1;
3645 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3646 $colours[$pdbk] = 1;
3647 $this->mOutput
->addLink( $title, $id );
3648 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3649 $colours[$pdbk] = 0;
3651 # Not in the link cache, add it to the query
3652 if ( !isset( $current ) ) {
3654 $query = "SELECT page_id, page_namespace, page_title";
3655 if ( $threshold > 0 ) {
3656 $query .= ', page_len, page_is_redirect';
3658 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3659 } elseif ( $current != $ns ) {
3661 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3666 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3671 if ( $options & RLH_FOR_UPDATE
) {
3672 $query .= ' FOR UPDATE';
3675 $res = $dbr->query( $query, $fname );
3677 # Fetch data and form into an associative array
3678 # non-existent = broken
3681 while ( $s = $dbr->fetchObject($res) ) {
3682 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3683 $pdbk = $title->getPrefixedDBkey();
3684 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3685 $this->mOutput
->addLink( $title, $s->page_id
);
3687 if ( $threshold > 0 ) {
3688 $size = $s->page_len
;
3689 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3690 $colours[$pdbk] = 1;
3692 $colours[$pdbk] = 2;
3695 $colours[$pdbk] = 1;
3699 wfProfileOut( $fname.'-check' );
3701 # Construct search and replace arrays
3702 wfProfileIn( $fname.'-construct' );
3703 $wgOutputReplace = array();
3704 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3705 $pdbk = $pdbks[$key];
3706 $searchkey = "<!--LINK $key-->";
3707 $title = $this->mLinkHolders
['titles'][$key];
3708 if ( empty( $colours[$pdbk] ) ) {
3709 $linkCache->addBadLinkObj( $title );
3710 $colours[$pdbk] = 0;
3711 $this->mOutput
->addLink( $title, 0 );
3712 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3713 $this->mLinkHolders
['texts'][$key],
3714 $this->mLinkHolders
['queries'][$key] );
3715 } elseif ( $colours[$pdbk] == 1 ) {
3716 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3717 $this->mLinkHolders
['texts'][$key],
3718 $this->mLinkHolders
['queries'][$key] );
3719 } elseif ( $colours[$pdbk] == 2 ) {
3720 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3721 $this->mLinkHolders
['texts'][$key],
3722 $this->mLinkHolders
['queries'][$key] );
3725 wfProfileOut( $fname.'-construct' );
3728 wfProfileIn( $fname.'-replace' );
3730 $text = preg_replace_callback(
3731 '/(<!--LINK .*?-->)/',
3732 "wfOutputReplaceMatches",
3735 wfProfileOut( $fname.'-replace' );
3738 # Now process interwiki link holders
3739 # This is quite a bit simpler than internal links
3740 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3741 wfProfileIn( $fname.'-interwiki' );
3742 # Make interwiki link HTML
3743 $wgOutputReplace = array();
3744 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3745 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3746 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3749 $text = preg_replace_callback(
3750 '/<!--IWLINK (.*?)-->/',
3751 "wfOutputReplaceMatches",
3753 wfProfileOut( $fname.'-interwiki' );
3756 wfProfileOut( $fname );
3761 * Replace <!--LINK--> link placeholders with plain text of links
3762 * (not HTML-formatted).
3763 * @param string $text
3766 function replaceLinkHoldersText( $text ) {
3767 $fname = 'Parser::replaceLinkHoldersText';
3768 wfProfileIn( $fname );
3770 $text = preg_replace_callback(
3771 '/<!--(LINK|IWLINK) (.*?)-->/',
3772 array( &$this, 'replaceLinkHoldersTextCallback' ),
3775 wfProfileOut( $fname );
3780 * @param array $matches
3784 function replaceLinkHoldersTextCallback( $matches ) {
3785 $type = $matches[1];
3787 if( $type == 'LINK' ) {
3788 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3789 return $this->mLinkHolders
['texts'][$key];
3791 } elseif( $type == 'IWLINK' ) {
3792 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3793 return $this->mInterwikiLinkHolders
['texts'][$key];
3800 * Renders an image gallery from a text with one line per image.
3801 * text labels may be given by using |-style alternative text. E.g.
3802 * Image:one.jpg|The number "1"
3803 * Image:tree.jpg|A tree
3804 * given as text will return the HTML of a gallery with two images,
3805 * labeled 'The number "1"' and
3808 function renderImageGallery( $text ) {
3810 $parserOptions = new ParserOptions
;
3811 $localParser = new Parser();
3813 $ig = new ImageGallery();
3814 $ig->setShowBytes( false );
3815 $ig->setShowFilename( false );
3816 $lines = explode( "\n", $text );
3818 foreach ( $lines as $line ) {
3819 # match lines like these:
3820 # Image:someimage.jpg|This is some image
3821 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3823 if ( count( $matches ) == 0 ) {
3826 $nt =& Title
::newFromText( $matches[1] );
3827 if( is_null( $nt ) ) {
3828 # Bogus title. Ignore these so we don't bomb out later.
3831 if ( isset( $matches[3] ) ) {
3832 $label = $matches[3];
3837 $pout = $localParser->parse( $label , $this->mTitle
, $parserOptions );
3838 $html = $pout->getText();
3840 $ig->add( new Image( $nt ), $html );
3841 $this->mOutput
->addImage( $nt->getDBkey() );
3843 return $ig->toHTML();
3847 * Parse image options text and use it to make an image
3849 function makeImage( &$nt, $options ) {
3850 global $wgUseImageResize;
3854 # Check if the options text is of the form "options|alt text"
3856 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3857 # * left no resizing, just left align. label is used for alt= only
3858 # * right same, but right aligned
3859 # * none same, but not aligned
3860 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3861 # * center center the image
3862 # * framed Keep original image size, no magnify-button.
3864 $part = explode( '|', $options);
3866 $mwThumb =& MagicWord
::get( MAG_IMG_THUMBNAIL
);
3867 $mwManualThumb =& MagicWord
::get( MAG_IMG_MANUALTHUMB
);
3868 $mwLeft =& MagicWord
::get( MAG_IMG_LEFT
);
3869 $mwRight =& MagicWord
::get( MAG_IMG_RIGHT
);
3870 $mwNone =& MagicWord
::get( MAG_IMG_NONE
);
3871 $mwWidth =& MagicWord
::get( MAG_IMG_WIDTH
);
3872 $mwCenter =& MagicWord
::get( MAG_IMG_CENTER
);
3873 $mwFramed =& MagicWord
::get( MAG_IMG_FRAMED
);
3876 $width = $height = $framed = $thumb = false;
3877 $manual_thumb = '' ;
3879 foreach( $part as $key => $val ) {
3880 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3882 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3883 # use manually specified thumbnail
3885 $manual_thumb = $match;
3886 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3887 # remember to set an alignment, don't render immediately
3889 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3890 # remember to set an alignment, don't render immediately
3892 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3893 # remember to set an alignment, don't render immediately
3895 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3896 # remember to set an alignment, don't render immediately
3898 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3899 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3900 # $match is the image width in pixels
3901 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3902 $width = intval( $m[1] );
3903 $height = intval( $m[2] );
3905 $width = intval($match);
3907 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3913 # Strip bad stuff out of the alt text
3914 $alt = $this->replaceLinkHoldersText( $caption );
3916 # make sure there are no placeholders in thumbnail attributes
3917 # that are later expanded to html- so expand them now and
3919 $alt = $this->unstrip($alt, $this->mStripState
);
3920 $alt = Sanitizer
::stripAllTags( $alt );
3922 # Linker does the rest
3923 $sk =& $this->mOptions
->getSkin();
3924 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3928 * Set a flag in the output object indicating that the content is dynamic and
3929 * shouldn't be cached.
3931 function disableCache() {
3932 $this->mOutput
->mCacheTime
= -1;
3936 * Callback from the Sanitizer for expanding items found in HTML attribute
3937 * values, so they can be safely tested and escaped.
3938 * @param string $text
3939 * @param array $args
3943 function attributeStripCallback( &$text, $args ) {
3944 $text = $this->replaceVariables( $text, $args );
3945 $text = $this->unstripForHTML( $text );
3949 function unstripForHTML( $text ) {
3950 $text = $this->unstrip( $text, $this->mStripState
);
3951 $text = $this->unstripNoWiki( $text, $this->mStripState
);
3959 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
3960 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
3961 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
3967 function getTags() { return array_keys( $this->mTagHooks
); }
3973 * @package MediaWiki
3977 var $mText, # The output text
3978 $mLanguageLinks, # List of the full text of language links, in the order they appear
3979 $mCategories, # Map of category names to sort keys
3980 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3981 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
3982 $mVersion, # Compatibility check
3983 $mTitleText, # title text of the chosen language variant
3984 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3985 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3986 $mImages, # DB keys of the images used, in the array key only
3987 $mExternalLinks; # External link URLs, in the key only
3989 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3990 $containsOldMagic = false, $titletext = '' )
3992 $this->mText
= $text;
3993 $this->mLanguageLinks
= $languageLinks;
3994 $this->mCategories
= $categoryLinks;
3995 $this->mContainsOldMagic
= $containsOldMagic;
3996 $this->mCacheTime
= '';
3997 $this->mVersion
= MW_PARSER_VERSION
;
3998 $this->mTitleText
= $titletext;
3999 $this->mLinks
= array();
4000 $this->mTemplates
= array();
4001 $this->mImages
= array();
4002 $this->mExternalLinks
= array();
4005 function getText() { return $this->mText
; }
4006 function getLanguageLinks() { return $this->mLanguageLinks
; }
4007 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4008 function &getCategories() { return $this->mCategories
; }
4009 function getCacheTime() { return $this->mCacheTime
; }
4010 function getTitleText() { return $this->mTitleText
; }
4011 function &getLinks() { return $this->mLinks
; }
4012 function &getTemplates() { return $this->mTemplates
; }
4013 function &getImages() { return $this->mImages
; }
4014 function &getExternalLinks() { return $this->mExternalLinks
; }
4016 function containsOldMagic() { return $this->mContainsOldMagic
; }
4017 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4018 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4019 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4020 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4021 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4022 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4024 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4025 function addImage( $name ) { $this->mImages
[$name] = 1; }
4026 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4027 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4029 function addLink( $title, $id ) {
4030 $ns = $title->getNamespace();
4031 $dbk = $title->getDBkey();
4032 if ( !isset( $this->mLinks
[$ns] ) ) {
4033 $this->mLinks
[$ns] = array();
4035 $this->mLinks
[$ns][$dbk] = $id;
4038 function addTemplate( $title, $id ) {
4039 $ns = $title->getNamespace();
4040 $dbk = $title->getDBkey();
4041 if ( !isset( $this->mTemplates
[$ns] ) ) {
4042 $this->mTemplates
[$ns] = array();
4044 $this->mTemplates
[$ns][$dbk] = $id;
4051 function merge( $other ) {
4052 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
4053 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
4054 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
4058 * Return true if this cached output object predates the global or
4059 * per-article cache invalidation timestamps, or if it comes from
4060 * an incompatible older version.
4062 * @param string $touched the affected article's last touched timestamp
4066 function expired( $touched ) {
4067 global $wgCacheEpoch;
4068 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4069 $this->getCacheTime() < $touched ||
4070 $this->getCacheTime() <= $wgCacheEpoch ||
4071 !isset( $this->mVersion
) ||
4072 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4077 * Set options of the Parser
4079 * @package MediaWiki
4083 # All variables are private
4084 var $mUseTeX; # Use texvc to expand <math> tags
4085 var $mUseDynamicDates; # Use DateFormatter to format dates
4086 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4087 var $mAllowExternalImages; # Allow external images inline
4088 var $mAllowExternalImagesFrom; # If not, any exception?
4089 var $mSkin; # Reference to the preferred skin
4090 var $mDateFormat; # Date format index
4091 var $mEditSection; # Create "edit section" links
4092 var $mNumberHeadings; # Automatically number headings
4093 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4094 var $mTidy; # Ask for tidy cleanup
4096 function getUseTeX() { return $this->mUseTeX
; }
4097 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4098 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4099 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4100 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4101 function &getSkin() { return $this->mSkin
; }
4102 function getDateFormat() { return $this->mDateFormat
; }
4103 function getEditSection() { return $this->mEditSection
; }
4104 function getNumberHeadings() { return $this->mNumberHeadings
; }
4105 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4106 function getTidy() { return $this->mTidy
; }
4108 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4109 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4110 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4111 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4112 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4113 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4114 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4115 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4116 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4117 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4118 function setSkin( &$x ) { $this->mSkin
=& $x; }
4120 function ParserOptions() {
4122 $this->initialiseFromUser( $wgUser );
4126 * Get parser options
4129 function newFromUser( &$user ) {
4130 $popts = new ParserOptions
;
4131 $popts->initialiseFromUser( $user );
4135 /** Get user options */
4136 function initialiseFromUser( &$userInput ) {
4137 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4138 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4139 $fname = 'ParserOptions::initialiseFromUser';
4140 wfProfileIn( $fname );
4141 if ( !$userInput ) {
4143 $user->setLoaded( true );
4145 $user =& $userInput;
4148 $this->mUseTeX
= $wgUseTeX;
4149 $this->mUseDynamicDates
= $wgUseDynamicDates;
4150 $this->mInterwikiMagic
= $wgInterwikiMagic;
4151 $this->mAllowExternalImages
= $wgAllowExternalImages;
4152 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4153 wfProfileIn( $fname.'-skin' );
4154 $this->mSkin
=& $user->getSkin();
4155 wfProfileOut( $fname.'-skin' );
4156 $this->mDateFormat
= $user->getOption( 'date' );
4157 $this->mEditSection
= true;
4158 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4159 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4160 $this->mTidy
= false;
4161 wfProfileOut( $fname );
4166 * Callback function used by Parser::replaceLinkHolders()
4167 * to substitute link placeholders.
4169 function &wfOutputReplaceMatches( $matches ) {
4170 global $wgOutputReplace;
4171 return $wgOutputReplace[$matches[1]];
4175 * Return the total number of articles
4177 function wfNumberOfArticles() {
4178 global $wgNumberOfArticles;
4181 return $wgNumberOfArticles;
4185 * Return the number of files
4187 function wfNumberOfFiles() {
4188 $fname = 'wfNumberOfFiles';
4190 wfProfileIn( $fname );
4191 $dbr =& wfGetDB( DB_SLAVE
);
4192 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4193 wfProfileOut( $fname );
4199 * Get various statistics from the database
4202 function wfLoadSiteStats() {
4203 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4204 $fname = 'wfLoadSiteStats';
4206 if ( -1 != $wgNumberOfArticles ) return;
4207 $dbr =& wfGetDB( DB_SLAVE
);
4208 $s = $dbr->selectRow( 'site_stats',
4209 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4210 array( 'ss_row_id' => 1 ), $fname
4213 if ( $s === false ) {
4216 $wgTotalViews = $s->ss_total_views
;
4217 $wgTotalEdits = $s->ss_total_edits
;
4218 $wgNumberOfArticles = $s->ss_good_articles
;
4224 * Basically replacing " > and < with HTML entities ( ", >, <)
4226 * @param string $in Text that might contain HTML tags
4227 * @return string Escaped string
4229 function wfEscapeHTMLTagsOnly( $in ) {
4231 array( '"', '>', '<' ),
4232 array( '"', '>', '<' ),