3 * File for Parser and related classes
10 * Update this version number when the ParserOutput format
11 * changes in an incompatible way, so the parser cache
12 * can automatically discard old data.
14 define( 'MW_PARSER_VERSION', '1.6.1' );
17 * Variable substitution O(N^2) attack
19 * Without countermeasures, it would be possible to attack the parser by saving
20 * a page filled with a large number of inclusions of large pages. The size of
21 * the generated page would be proportional to the square of the input size.
22 * Hence, we limit the number of inclusions of any given page, thus bringing any
23 * attack back to O(N).
26 define( 'MAX_INCLUDE_REPEAT', 100 );
27 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
29 define( 'RLH_FOR_UPDATE', 1 );
31 # Allowed values for $mOutputType
32 define( 'OT_HTML', 1 );
33 define( 'OT_WIKI', 2 );
34 define( 'OT_MSG' , 3 );
36 # Flags for setFunctionHook
37 define( 'SFH_NO_HASH', 1 );
39 # string parameter for extractTags which will cause it
40 # to strip HTML comments in addition to regular
41 # <XML>-style tags. This should not be anything we
42 # may want to use in wikisyntax
43 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45 # Constants needed for external link processing
46 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
47 # Everything except bracket, space, or control characters
48 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
49 # Including space, but excluding newlines
50 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
51 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
52 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
53 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
54 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
61 // State constants for the definition list colon extraction
62 define( 'MW_COLON_STATE_TEXT', 0 );
63 define( 'MW_COLON_STATE_TAG', 1 );
64 define( 'MW_COLON_STATE_TAGSTART', 2 );
65 define( 'MW_COLON_STATE_CLOSETAG', 3 );
66 define( 'MW_COLON_STATE_TAGSLASH', 4 );
67 define( 'MW_COLON_STATE_COMMENT', 5 );
68 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
69 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
74 * Processes wiki markup
77 * There are three main entry points into the Parser class:
79 * produces HTML output
81 * produces altered wiki markup.
83 * performs brace substitution on MediaWiki messages
86 * objects: $wgLang, $wgContLang
88 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
91 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
92 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
93 * $wgLocaltimezone, $wgAllowSpecialInclusion*
95 * * only within ParserOptions
106 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
108 # Cleared with clearState():
109 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
110 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
111 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
112 var $mTemplates, // cache of already loaded templates, avoids
113 // multiple SQL queries for the same string
114 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
115 // in this path. Used for loop detection.
118 # These are variables reset at least once per parse regardless of $clearState
119 var $mOptions, // ParserOptions object
120 $mTitle, // Title context, used for self-link rendering and similar things
121 $mOutputType, // Output type, one of the OT_xxx constants
122 $mRevisionId; // ID to display in {{REVISIONID}} tags
132 $this->mTagHooks
= array();
133 $this->mFunctionHooks
= array();
134 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
135 $this->mFirstCall
= true;
139 * Do various kinds of initialisation on the first call of the parser
141 function firstCallInit() {
142 if ( !$this->mFirstCall
) {
146 wfProfileIn( __METHOD__
);
147 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
149 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
151 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH
);
152 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH
);
153 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH
);
154 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH
);
155 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH
);
156 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH
);
157 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH
);
158 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH
);
159 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH
);
160 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH
);
161 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH
);
162 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH
);
163 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH
);
164 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH
);
165 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH
);
166 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH
);
167 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH
);
168 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH
);
169 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH
);
171 if ( $wgAllowDisplayTitle ) {
172 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH
);
174 if ( $wgAllowSlowParserFunctions ) {
175 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH
);
178 $this->initialiseVariables();
180 $this->mFirstCall
= false;
181 wfProfileOut( __METHOD__
);
189 function clearState() {
190 wfProfileIn( __METHOD__
);
191 if ( $this->mFirstCall
) {
192 $this->firstCallInit();
194 $this->mOutput
= new ParserOutput
;
195 $this->mAutonumber
= 0;
196 $this->mLastSection
= '';
197 $this->mDTopen
= false;
198 $this->mIncludeCount
= array();
199 $this->mStripState
= array();
200 $this->mArgStack
= array();
201 $this->mInPre
= false;
202 $this->mInterwikiLinkHolders
= array(
206 $this->mLinkHolders
= array(
207 'namespaces' => array(),
209 'queries' => array(),
213 $this->mRevisionId
= null;
216 * Prefix for temporary replacement strings for the multipass parser.
217 * \x07 should never appear in input as it's disallowed in XML.
218 * Using it at the front also gives us a little extra robustness
219 * since it shouldn't match when butted up against identifier-like
222 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
224 # Clear these on every parse, bug 4549
225 $this->mTemplates
= array();
226 $this->mTemplatePath
= array();
228 $this->mShowToc
= true;
229 $this->mForceTocPosition
= false;
231 wfRunHooks( 'ParserClearState', array( &$this ) );
232 wfProfileOut( __METHOD__
);
236 * Accessor for mUniqPrefix.
240 function uniqPrefix() {
241 return $this->mUniqPrefix
;
245 * Convert wikitext to HTML
246 * Do not call this function recursively.
249 * @param string $text Text we want to parse
250 * @param Title &$title A title object
251 * @param array $options
252 * @param boolean $linestart
253 * @param boolean $clearState
254 * @param int $revid number to pass in {{REVISIONID}}
255 * @return ParserOutput a ParserOutput
257 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
259 * First pass--just handle <nowiki> sections, pass the rest off
260 * to internalParse() which does all the real work.
263 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
264 $fname = 'Parser::parse';
265 wfProfileIn( $fname );
271 $this->mOptions
= $options;
272 $this->mTitle
=& $title;
273 $oldRevisionId = $this->mRevisionId
;
274 if( $revid !== null ) {
275 $this->mRevisionId
= $revid;
277 $this->mOutputType
= OT_HTML
;
279 //$text = $this->strip( $text, $this->mStripState );
280 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
281 $x =& $this->mStripState
;
283 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
284 $text = $this->strip( $text, $x );
285 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
287 $text = $this->internalParse( $text );
289 $text = $this->unstrip( $text, $this->mStripState
);
291 # Clean up special characters, only run once, next-to-last before doBlockLevels
293 # french spaces, last one Guillemet-left
294 # only if there is something before the space
295 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
296 # french spaces, Guillemet-right
297 '/(\\302\\253) /' => '\\1 ',
299 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
302 $text = $this->doBlockLevels( $text, $linestart );
304 $this->replaceLinkHolders( $text );
306 # the position of the parserConvert() call should not be changed. it
307 # assumes that the links are all replaced and the only thing left
308 # is the <nowiki> mark.
309 # Side-effects: this calls $this->mOutput->setTitleText()
310 $text = $wgContLang->parserConvert( $text, $this );
312 $text = $this->unstripNoWiki( $text, $this->mStripState
);
314 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
316 $text = Sanitizer
::normalizeCharReferences( $text );
318 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
319 $text = Parser
::tidy($text);
321 # attempt to sanitize at least some nesting problems
322 # (bug #2702 and quite a few others)
324 # ''Something [http://www.cool.com cool''] -->
325 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
326 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
327 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
328 # fix up an anchor inside another anchor, only
329 # at least for a single single nested link (bug 3695)
330 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
331 '\\1\\2</a>\\3</a>\\1\\4</a>',
332 # fix div inside inline elements- doBlockLevels won't wrap a line which
333 # contains a div, so fix it up here; replace
334 # div with escaped text
335 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
336 '\\1\\3<div\\5>\\6</div>\\8\\9',
337 # remove empty italic or bold tag pairs, some
338 # introduced by rules above
339 '/<([bi])><\/\\1>/' => '',
342 $text = preg_replace(
343 array_keys( $tidyregs ),
344 array_values( $tidyregs ),
348 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
350 $this->mOutput
->setText( $text );
351 $this->mRevisionId
= $oldRevisionId;
352 wfProfileOut( $fname );
354 return $this->mOutput
;
358 * Recursive parser entry point that can be called from an extension tag
361 function recursiveTagParse( $text ) {
362 wfProfileIn( __METHOD__
);
363 $x =& $this->mStripState
;
364 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
365 $text = $this->strip( $text, $x );
366 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
367 $text = $this->internalParse( $text );
368 wfProfileOut( __METHOD__
);
373 * Get a random string
378 function getRandomString() {
379 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
382 function &getTitle() { return $this->mTitle
; }
383 function getOptions() { return $this->mOptions
; }
385 function getFunctionLang() {
386 global $wgLang, $wgContLang;
387 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
391 * Replaces all occurrences of HTML-style comments and the given tags
392 * in the text with a random marker and returns teh next text. The output
393 * parameter $matches will be an associative array filled with data in
395 * 'UNIQ-xxxxx' => array(
398 * array( 'param' => 'x' ),
399 * '<element param="x">tag content</element>' ) )
401 * @param $elements list of element names. Comments are always extracted.
402 * @param $text Source text string.
403 * @param $uniq_prefix
408 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
413 $taglist = implode( '|', $elements );
414 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
416 while ( '' != $text ) {
417 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
419 if( count( $p ) < 5 ) {
422 if( count( $p ) > 5 ) {
436 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . '-QINU';
437 $stripped .= $marker;
439 if ( $close === '/>' ) {
440 // Empty element tag, <tag />
445 if( $element == '!--' ) {
448 $end = "/(<\\/$element\\s*>)/i";
450 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
452 if( count( $q ) < 3 ) {
453 # No end tag -- let it run out to the end of the text.
462 $matches[$marker] = array( $element,
464 Sanitizer
::decodeTagAttributes( $attributes ),
465 "<$element$attributes$close$content$tail" );
471 * Strips and renders nowiki, pre, math, hiero
472 * If $render is set, performs necessary rendering operations on plugins
473 * Returns the text, and fills an array with data needed in unstrip()
474 * If the $state is already a valid strip state, it adds to the state
476 * @param bool $stripcomments when set, HTML comments <!-- like this -->
477 * will be stripped in addition to other tags. This is important
478 * for section editing, where these comments cause confusion when
479 * counting the sections in the wikisource
481 * @param array dontstrip contains tags which should not be stripped;
482 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
486 function strip( $text, &$state, $stripcomments = false , $dontstrip = array () ) {
487 wfProfileIn( __METHOD__
);
488 $render = ($this->mOutputType
== OT_HTML
);
490 # Replace any instances of the placeholders
491 $uniq_prefix = $this->mUniqPrefix
;
492 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
493 $commentState = array();
495 $elements = array_merge(
496 array( 'nowiki', 'gallery' ),
497 array_keys( $this->mTagHooks
) );
500 $elements[] = 'html';
502 if( $this->mOptions
->getUseTeX() ) {
503 $elements[] = 'math';
506 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
507 foreach ( $elements AS $k => $v ) {
508 if ( !in_array ( $v , $dontstrip ) ) continue;
509 unset ( $elements[$k] );
513 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
515 foreach( $matches as $marker => $data ) {
516 list( $element, $content, $params, $tag ) = $data;
518 $tagName = strtolower( $element );
519 wfProfileIn( __METHOD__
."-render-$tagName" );
523 if( substr( $tag, -3 ) == '-->' ) {
526 // Unclosed comment in input.
527 // Close it so later stripping can remove it
536 // Shouldn't happen otherwise. :)
538 $output = wfEscapeHTMLTagsOnly( $content );
541 $output = MathRenderer
::renderMath( $content );
544 $output = $this->renderImageGallery( $content, $params );
547 if( isset( $this->mTagHooks
[$tagName] ) ) {
548 $output = call_user_func_array( $this->mTagHooks
[$tagName],
549 array( $content, $params, $this ) );
551 throw new MWException( "Invalid call hook $element" );
554 wfProfileOut( __METHOD__
."-render-$tagName" );
556 // Just stripping tags; keep the source
560 // Unstrip the output, because unstrip() is no longer recursive so
561 // it won't do it itself
562 $output = $this->unstrip( $output, $state );
564 if( !$stripcomments && $element == '!--' ) {
565 $commentState[$marker] = $output;
566 } elseif ( $element == 'html' ||
$element == 'nowiki' ) {
567 $state['nowiki'][$marker] = $output;
569 $state['general'][$marker] = $output;
573 # Unstrip comments unless explicitly told otherwise.
574 # (The comments are always stripped prior to this point, so as to
575 # not invoke any extension tags / parser hooks contained within
577 if ( !$stripcomments ) {
578 // Put them all back and forget them
579 $text = strtr( $text, $commentState );
582 wfProfileOut( __METHOD__
);
587 * Restores pre, math, and other extensions removed by strip()
589 * always call unstripNoWiki() after this one
592 function unstrip( $text, &$state ) {
593 if ( !isset( $state['general'] ) ) {
597 wfProfileIn( __METHOD__
);
598 # TODO: good candidate for FSS
599 $text = strtr( $text, $state['general'] );
600 wfProfileOut( __METHOD__
);
605 * Always call this after unstrip() to preserve the order
609 function unstripNoWiki( $text, &$state ) {
610 if ( !isset( $state['nowiki'] ) ) {
614 wfProfileIn( __METHOD__
);
615 # TODO: good candidate for FSS
616 $text = strtr( $text, $state['nowiki'] );
617 wfProfileOut( __METHOD__
);
623 * Add an item to the strip state
624 * Returns the unique tag which must be inserted into the stripped text
625 * The tag will be replaced with the original text in unstrip()
629 function insertStripItem( $text, &$state ) {
630 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
634 $state['general'][$rnd] = $text;
639 * Interface with html tidy, used if $wgUseTidy = true.
640 * If tidy isn't able to correct the markup, the original will be
641 * returned in all its glory with a warning comment appended.
643 * Either the external tidy program or the in-process tidy extension
644 * will be used depending on availability. Override the default
645 * $wgTidyInternal setting to disable the internal if it's not working.
647 * @param string $text Hideous HTML input
648 * @return string Corrected HTML output
652 function tidy( $text ) {
653 global $wgTidyInternal;
654 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
655 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
656 '<head><title>test</title></head><body>'.$text.'</body></html>';
657 if( $wgTidyInternal ) {
658 $correctedtext = Parser
::internalTidy( $wrappedtext );
660 $correctedtext = Parser
::externalTidy( $wrappedtext );
662 if( is_null( $correctedtext ) ) {
663 wfDebug( "Tidy error detected!\n" );
664 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
666 return $correctedtext;
670 * Spawn an external HTML tidy process and get corrected markup back from it.
675 function externalTidy( $text ) {
676 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
677 $fname = 'Parser::externalTidy';
678 wfProfileIn( $fname );
683 $descriptorspec = array(
684 0 => array('pipe', 'r'),
685 1 => array('pipe', 'w'),
686 2 => array('file', '/dev/null', 'a')
689 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
690 if (is_resource($process)) {
691 // Theoretically, this style of communication could cause a deadlock
692 // here. If the stdout buffer fills up, then writes to stdin could
693 // block. This doesn't appear to happen with tidy, because tidy only
694 // writes to stdout after it's finished reading from stdin. Search
695 // for tidyParseStdin and tidySaveStdout in console/tidy.c
696 fwrite($pipes[0], $text);
698 while (!feof($pipes[1])) {
699 $cleansource .= fgets($pipes[1], 1024);
702 proc_close($process);
705 wfProfileOut( $fname );
707 if( $cleansource == '' && $text != '') {
708 // Some kind of error happened, so we couldn't get the corrected text.
709 // Just give up; we'll use the source text and append a warning.
717 * Use the HTML tidy PECL extension to use the tidy library in-process,
718 * saving the overhead of spawning a new process. Currently written to
719 * the PHP 4.3.x version of the extension, may not work on PHP 5.
721 * 'pear install tidy' should be able to compile the extension module.
726 function internalTidy( $text ) {
728 $fname = 'Parser::internalTidy';
729 wfProfileIn( $fname );
731 tidy_load_config( $wgTidyConf );
732 tidy_set_encoding( 'utf8' );
733 tidy_parse_string( $text );
735 if( tidy_get_status() == 2 ) {
736 // 2 is magic number for fatal error
737 // http://www.php.net/manual/en/function.tidy-get-status.php
740 $cleansource = tidy_get_output();
742 wfProfileOut( $fname );
747 * parse the wiki syntax used to render tables
751 function doTableStuff ( $t ) {
752 $fname = 'Parser::doTableStuff';
753 wfProfileIn( $fname );
755 $t = explode ( "\n" , $t ) ;
756 $td = array () ; # Is currently a td tag open?
757 $ltd = array () ; # Was it TD or TH?
758 $tr = array () ; # Is currently a tr tag open?
759 $ltr = array () ; # tr attributes
760 $has_opened_tr = array(); # Did this table open a <tr> element?
761 $indent_level = 0; # indent level of the table
762 foreach ( $t AS $k => $x )
765 $fc = substr ( $x , 0 , 1 ) ;
766 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
767 $indent_level = strlen( $matches[1] );
769 $attributes = $this->unstripForHTML( $matches[2] );
771 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
772 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
773 array_push ( $td , false ) ;
774 array_push ( $ltd , '' ) ;
775 array_push ( $tr , false ) ;
776 array_push ( $ltr , '' ) ;
777 array_push ( $has_opened_tr, false );
779 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
780 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
781 $z = "</table>" . substr ( $x , 2);
782 $l = array_pop ( $ltd ) ;
783 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
784 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
785 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
787 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
789 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
790 $x = substr ( $x , 1 ) ;
791 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
793 $l = array_pop ( $ltd ) ;
794 array_pop ( $has_opened_tr );
795 array_push ( $has_opened_tr , true ) ;
796 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
797 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
800 array_push ( $tr , false ) ;
801 array_push ( $td , false ) ;
802 array_push ( $ltd , '' ) ;
803 $attributes = $this->unstripForHTML( $x );
804 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
806 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
808 if ( '|+' == substr ( $x , 0 , 2 ) ) {
810 $x = substr ( $x , 1 ) ;
812 $after = substr ( $x , 1 ) ;
813 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
815 // Split up multiple cells on the same line.
816 // FIXME: This can result in improper nesting of tags processed
817 // by earlier parser steps, but should avoid splitting up eg
818 // attribute values containing literal "||".
819 $after = wfExplodeMarkup( '||', $after );
823 # Loop through each table cell
824 foreach ( $after AS $theline )
829 $tra = array_pop ( $ltr ) ;
830 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
831 array_push ( $tr , true ) ;
832 array_push ( $ltr , '' ) ;
833 array_pop ( $has_opened_tr );
834 array_push ( $has_opened_tr , true ) ;
837 $l = array_pop ( $ltd ) ;
838 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
839 if ( $fc == '|' ) $l = 'td' ;
840 else if ( $fc == '!' ) $l = 'th' ;
841 else if ( $fc == '+' ) $l = 'caption' ;
843 array_push ( $ltd , $l ) ;
846 $y = explode ( '|' , $theline , 2 ) ;
847 # Note that a '|' inside an invalid link should not
848 # be mistaken as delimiting cell parameters
849 if ( strpos( $y[0], '[[' ) !== false ) {
850 $y = array ($theline);
852 if ( count ( $y ) == 1 )
853 $y = "{$z}<{$l}>{$y[0]}" ;
855 $attributes = $this->unstripForHTML( $y[0] );
856 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
859 array_push ( $td , true ) ;
864 # Closing open td, tr && table
865 while ( count ( $td ) > 0 )
867 $l = array_pop ( $ltd ) ;
868 if ( array_pop ( $td ) ) $t[] = '</td>' ;
869 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
870 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
874 $t = implode ( "\n" , $t ) ;
875 # special case: don't return empty table
876 if($t == "<table>\n<tr><td></td></tr>\n</table>")
878 wfProfileOut( $fname );
883 * Helper function for parse() that transforms wiki markup into
884 * HTML. Only called for $mOutputType == OT_HTML.
888 function internalParse( $text ) {
891 $fname = 'Parser::internalParse';
892 wfProfileIn( $fname );
894 # Hook to suspend the parser in this state
895 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
896 wfProfileOut( $fname );
900 # Remove <noinclude> tags and <includeonly> sections
901 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
902 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
903 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
905 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
907 $text = $this->replaceVariables( $text, $args );
909 // Tables need to come after variable replacement for things to work
910 // properly; putting them before other transformations should keep
911 // exciting things like link expansions from showing up in surprising
913 $text = $this->doTableStuff( $text );
915 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
917 $text = $this->stripToc( $text );
918 $this->stripNoGallery( $text );
919 $text = $this->doHeadings( $text );
920 if($this->mOptions
->getUseDynamicDates()) {
921 $df =& DateFormatter
::getInstance();
922 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
924 $text = $this->doAllQuotes( $text );
925 $text = $this->replaceInternalLinks( $text );
926 $text = $this->replaceExternalLinks( $text );
928 # replaceInternalLinks may sometimes leave behind
929 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
930 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
932 $text = $this->doMagicLinks( $text );
933 $text = $this->formatHeadings( $text, $isMain );
935 wfProfileOut( $fname );
940 * Replace special strings like "ISBN xxx" and "RFC xxx" with
941 * magic external links.
945 function &doMagicLinks( &$text ) {
946 wfProfileIn( __METHOD__
);
947 $text = preg_replace_callback(
949 <a.*?</a> # Skip link text
950 <.*?> | # Skip stuff inside HTML elements
951 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
952 ISBN\s+([0-9Xx-]+) # ISBN, capture number as m[2]
953 )!x', array( &$this, 'magicLinkCallback' ), $text );
954 wfProfileOut( __METHOD__
);
958 function magicLinkCallback( $m ) {
959 if ( substr( $m[0], 0, 1 ) == '<' ) {
962 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
964 $num = strtr( $isbn, array(
969 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
970 $text = '<a href="' .
971 $titleObj->escapeLocalUrl( "isbn=$num" ) .
972 "\" class=\"internal\">ISBN $isbn</a>";
974 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
978 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
980 $urlmsg = 'pubmedurl';
983 throw new MWException( __METHOD__
.': unrecognised match type "' .
984 substr($m[0], 0, 20 ) . '"' );
987 $url = wfMsg( $urlmsg, $id);
988 $sk =& $this->mOptions
->getSkin();
989 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
990 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
996 * Parse headers and return html
1000 function doHeadings( $text ) {
1001 $fname = 'Parser::doHeadings';
1002 wfProfileIn( $fname );
1003 for ( $i = 6; $i >= 1; --$i ) {
1004 $h = str_repeat( '=', $i );
1005 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1006 "<h{$i}>\\1</h{$i}>\\2", $text );
1008 wfProfileOut( $fname );
1013 * Replace single quotes with HTML markup
1015 * @return string the altered text
1017 function doAllQuotes( $text ) {
1018 $fname = 'Parser::doAllQuotes';
1019 wfProfileIn( $fname );
1021 $lines = explode( "\n", $text );
1022 foreach ( $lines as $line ) {
1023 $outtext .= $this->doQuotes ( $line ) . "\n";
1025 $outtext = substr($outtext, 0,-1);
1026 wfProfileOut( $fname );
1031 * Helper function for doAllQuotes()
1034 function doQuotes( $text ) {
1035 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1036 if ( count( $arr ) == 1 )
1040 # First, do some preliminary work. This may shift some apostrophes from
1041 # being mark-up to being text. It also counts the number of occurrences
1042 # of bold and italics mark-ups.
1046 foreach ( $arr as $r )
1048 if ( ( $i %
2 ) == 1 )
1050 # If there are ever four apostrophes, assume the first is supposed to
1051 # be text, and the remaining three constitute mark-up for bold text.
1052 if ( strlen( $arr[$i] ) == 4 )
1057 # If there are more than 5 apostrophes in a row, assume they're all
1058 # text except for the last 5.
1059 else if ( strlen( $arr[$i] ) > 5 )
1061 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1064 # Count the number of occurrences of bold and italics mark-ups.
1065 # We are not counting sequences of five apostrophes.
1066 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
1067 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
1068 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1073 # If there is an odd number of both bold and italics, it is likely
1074 # that one of the bold ones was meant to be an apostrophe followed
1075 # by italics. Which one we cannot know for certain, but it is more
1076 # likely to be one that has a single-letter word before it.
1077 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1080 $firstsingleletterword = -1;
1081 $firstmultiletterword = -1;
1083 foreach ( $arr as $r )
1085 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1087 $x1 = substr ($arr[$i-1], -1);
1088 $x2 = substr ($arr[$i-1], -2, 1);
1090 if ($firstspace == -1) $firstspace = $i;
1091 } else if ($x2 == ' ') {
1092 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1094 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1100 # If there is a single-letter word, use it!
1101 if ($firstsingleletterword > -1)
1103 $arr [ $firstsingleletterword ] = "''";
1104 $arr [ $firstsingleletterword-1 ] .= "'";
1106 # If not, but there's a multi-letter word, use that one.
1107 else if ($firstmultiletterword > -1)
1109 $arr [ $firstmultiletterword ] = "''";
1110 $arr [ $firstmultiletterword-1 ] .= "'";
1112 # ... otherwise use the first one that has neither.
1113 # (notice that it is possible for all three to be -1 if, for example,
1114 # there is only one pentuple-apostrophe in the line)
1115 else if ($firstspace > -1)
1117 $arr [ $firstspace ] = "''";
1118 $arr [ $firstspace-1 ] .= "'";
1122 # Now let's actually convert our apostrophic mush to HTML!
1127 foreach ($arr as $r)
1131 if ($state == 'both')
1138 if (strlen ($r) == 2)
1141 { $output .= '</i>'; $state = ''; }
1142 else if ($state == 'bi')
1143 { $output .= '</i>'; $state = 'b'; }
1144 else if ($state == 'ib')
1145 { $output .= '</b></i><b>'; $state = 'b'; }
1146 else if ($state == 'both')
1147 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1148 else # $state can be 'b' or ''
1149 { $output .= '<i>'; $state .= 'i'; }
1151 else if (strlen ($r) == 3)
1154 { $output .= '</b>'; $state = ''; }
1155 else if ($state == 'bi')
1156 { $output .= '</i></b><i>'; $state = 'i'; }
1157 else if ($state == 'ib')
1158 { $output .= '</b>'; $state = 'i'; }
1159 else if ($state == 'both')
1160 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1161 else # $state can be 'i' or ''
1162 { $output .= '<b>'; $state .= 'b'; }
1164 else if (strlen ($r) == 5)
1167 { $output .= '</b><i>'; $state = 'i'; }
1168 else if ($state == 'i')
1169 { $output .= '</i><b>'; $state = 'b'; }
1170 else if ($state == 'bi')
1171 { $output .= '</i></b>'; $state = ''; }
1172 else if ($state == 'ib')
1173 { $output .= '</b></i>'; $state = ''; }
1174 else if ($state == 'both')
1175 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1176 else # ($state == '')
1177 { $buffer = ''; $state = 'both'; }
1182 # Now close all remaining tags. Notice that the order is important.
1183 if ($state == 'b' ||
$state == 'ib')
1185 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1189 if ($state == 'both')
1190 $output .= '<b><i>'.$buffer.'</i></b>';
1196 * Replace external links
1198 * Note: this is all very hackish and the order of execution matters a lot.
1199 * Make sure to run maintenance/parserTests.php if you change this code.
1203 function replaceExternalLinks( $text ) {
1205 $fname = 'Parser::replaceExternalLinks';
1206 wfProfileIn( $fname );
1208 $sk =& $this->mOptions
->getSkin();
1210 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1212 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1215 while ( $i<count( $bits ) ) {
1217 $protocol = $bits[$i++
];
1218 $text = $bits[$i++
];
1219 $trail = $bits[$i++
];
1221 # The characters '<' and '>' (which were escaped by
1222 # removeHTMLtags()) should not be included in
1223 # URLs, per RFC 2396.
1224 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1225 $text = substr($url, $m2[0][1]) . ' ' . $text;
1226 $url = substr($url, 0, $m2[0][1]);
1229 # If the link text is an image URL, replace it with an <img> tag
1230 # This happened by accident in the original parser, but some people used it extensively
1231 $img = $this->maybeMakeExternalImage( $text );
1232 if ( $img !== false ) {
1238 # Set linktype for CSS - if URL==text, link is essentially free
1239 $linktype = ($text == $url) ?
'free' : 'text';
1241 # No link text, e.g. [http://domain.tld/some.link]
1242 if ( $text == '' ) {
1243 # Autonumber if allowed. See bug #5918
1244 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1245 $text = '[' . ++
$this->mAutonumber
. ']';
1246 $linktype = 'autonumber';
1248 # Otherwise just use the URL
1249 $text = htmlspecialchars( $url );
1253 # Have link text, e.g. [http://domain.tld/some.link text]s
1255 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1258 $text = $wgContLang->markNoConversion($text);
1260 $url = Sanitizer
::cleanUrl( $url );
1262 # Process the trail (i.e. everything after this link up until start of the next link),
1263 # replacing any non-bracketed links
1264 $trail = $this->replaceFreeExternalLinks( $trail );
1266 # Use the encoded URL
1267 # This means that users can paste URLs directly into the text
1268 # Funny characters like ö aren't valid in URLs anyway
1269 # This was changed in August 2004
1270 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1272 # Register link in the output object.
1273 # Replace unnecessary URL escape codes with the referenced character
1274 # This prevents spammers from hiding links from the filters
1275 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1276 $this->mOutput
->addExternalLink( $pasteurized );
1279 wfProfileOut( $fname );
1284 * Replace anything that looks like a URL with a link
1287 function replaceFreeExternalLinks( $text ) {
1289 $fname = 'Parser::replaceFreeExternalLinks';
1290 wfProfileIn( $fname );
1292 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1293 $s = array_shift( $bits );
1296 $sk =& $this->mOptions
->getSkin();
1298 while ( $i < count( $bits ) ){
1299 $protocol = $bits[$i++
];
1300 $remainder = $bits[$i++
];
1302 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1303 # Found some characters after the protocol that look promising
1304 $url = $protocol . $m[1];
1307 # special case: handle urls as url args:
1308 # http://www.example.com/foo?=http://www.example.com/bar
1309 if(strlen($trail) == 0 &&
1311 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1312 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1315 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1320 # The characters '<' and '>' (which were escaped by
1321 # removeHTMLtags()) should not be included in
1322 # URLs, per RFC 2396.
1323 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1324 $trail = substr($url, $m2[0][1]) . $trail;
1325 $url = substr($url, 0, $m2[0][1]);
1328 # Move trailing punctuation to $trail
1330 # If there is no left bracket, then consider right brackets fair game too
1331 if ( strpos( $url, '(' ) === false ) {
1335 $numSepChars = strspn( strrev( $url ), $sep );
1336 if ( $numSepChars ) {
1337 $trail = substr( $url, -$numSepChars ) . $trail;
1338 $url = substr( $url, 0, -$numSepChars );
1341 $url = Sanitizer
::cleanUrl( $url );
1343 # Is this an external image?
1344 $text = $this->maybeMakeExternalImage( $url );
1345 if ( $text === false ) {
1346 # Not an image, make a link
1347 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1348 # Register it in the output object...
1349 # Replace unnecessary URL escape codes with their equivalent characters
1350 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1351 $this->mOutput
->addExternalLink( $pasteurized );
1353 $s .= $text . $trail;
1355 $s .= $protocol . $remainder;
1358 wfProfileOut( $fname );
1363 * Replace unusual URL escape codes with their equivalent characters
1367 * @fixme This can merge genuinely required bits in the path or query string,
1368 * breaking legit URLs. A proper fix would treat the various parts of
1369 * the URL differently; as a workaround, just use the output for
1370 * statistical records, not for actual linking/output.
1372 static function replaceUnusualEscapes( $url ) {
1373 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1374 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1378 * Callback function used in replaceUnusualEscapes().
1379 * Replaces unusual URL escape codes with their equivalent character
1383 private static function replaceUnusualEscapesCallback( $matches ) {
1384 $char = urldecode( $matches[0] );
1385 $ord = ord( $char );
1386 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1387 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1388 // No, shouldn't be escaped
1391 // Yes, leave it escaped
1397 * make an image if it's allowed, either through the global
1398 * option or through the exception
1401 function maybeMakeExternalImage( $url ) {
1402 $sk =& $this->mOptions
->getSkin();
1403 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1404 $imagesexception = !empty($imagesfrom);
1406 if ( $this->mOptions
->getAllowExternalImages()
1407 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1408 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1410 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1417 * Process [[ ]] wikilinks
1421 function replaceInternalLinks( $s ) {
1423 static $fname = 'Parser::replaceInternalLinks' ;
1425 wfProfileIn( $fname );
1427 wfProfileIn( $fname.'-setup' );
1429 # the % is needed to support urlencoded titles as well
1430 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1432 $sk =& $this->mOptions
->getSkin();
1434 #split the entire text string on occurences of [[
1435 $a = explode( '[[', ' ' . $s );
1436 #get the first element (all text up to first [[), and remove the space we added
1437 $s = array_shift( $a );
1438 $s = substr( $s, 1 );
1440 # Match a link having the form [[namespace:link|alternate]]trail
1442 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1443 # Match cases where there is no "]]", which might still be images
1444 static $e1_img = FALSE;
1445 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1446 # Match the end of a line for a word that's not followed by whitespace,
1447 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1448 $e2 = wfMsgForContent( 'linkprefix' );
1450 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1452 if( is_null( $this->mTitle
) ) {
1453 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1455 $nottalk = !$this->mTitle
->isTalkPage();
1457 if ( $useLinkPrefixExtension ) {
1458 if ( preg_match( $e2, $s, $m ) ) {
1459 $first_prefix = $m[2];
1461 $first_prefix = false;
1467 $selflink = $this->mTitle
->getPrefixedText();
1468 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1469 $useSubpages = $this->areSubpagesAllowed();
1470 wfProfileOut( $fname.'-setup' );
1472 # Loop for each link
1473 for ($k = 0; isset( $a[$k] ); $k++
) {
1475 if ( $useLinkPrefixExtension ) {
1476 wfProfileIn( $fname.'-prefixhandling' );
1477 if ( preg_match( $e2, $s, $m ) ) {
1485 $prefix = $first_prefix;
1486 $first_prefix = false;
1488 wfProfileOut( $fname.'-prefixhandling' );
1491 $might_be_img = false;
1493 wfProfileIn( "$fname-e1" );
1494 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1496 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1497 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1498 # the real problem is with the $e1 regex
1501 # Still some problems for cases where the ] is meant to be outside punctuation,
1502 # and no image is in sight. See bug 2095.
1505 substr( $m[3], 0, 1 ) === ']' &&
1506 strpos($text, '[') !== false
1509 $text .= ']'; # so that replaceExternalLinks($text) works later
1510 $m[3] = substr( $m[3], 1 );
1512 # fix up urlencoded title texts
1513 if( strpos( $m[1], '%' ) !== false ) {
1514 # Should anchors '#' also be rejected?
1515 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1518 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1519 $might_be_img = true;
1521 if ( strpos( $m[1], '%' ) !== false ) {
1522 $m[1] = urldecode($m[1]);
1525 } else { # Invalid form; output directly
1526 $s .= $prefix . '[[' . $line ;
1527 wfProfileOut( "$fname-e1" );
1530 wfProfileOut( "$fname-e1" );
1531 wfProfileIn( "$fname-misc" );
1533 # Don't allow internal links to pages containing
1534 # PROTO: where PROTO is a valid URL protocol; these
1535 # should be external links.
1536 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1537 $s .= $prefix . '[[' . $line ;
1541 # Make subpage if necessary
1542 if( $useSubpages ) {
1543 $link = $this->maybeDoSubpageLink( $m[1], $text );
1548 $noforce = (substr($m[1], 0, 1) != ':');
1550 # Strip off leading ':'
1551 $link = substr($link, 1);
1554 wfProfileOut( "$fname-misc" );
1555 wfProfileIn( "$fname-title" );
1556 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1558 $s .= $prefix . '[[' . $line;
1559 wfProfileOut( "$fname-title" );
1563 #check other language variants of the link
1564 #if the article does not exist
1565 if( $checkVariantLink
1566 && $nt->getArticleID() == 0 ) {
1567 $wgContLang->findVariantLink($link, $nt);
1570 $ns = $nt->getNamespace();
1571 $iw = $nt->getInterWiki();
1572 wfProfileOut( "$fname-title" );
1574 if ($might_be_img) { # if this is actually an invalid link
1575 wfProfileIn( "$fname-might_be_img" );
1576 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1578 while (isset ($a[$k+
1]) ) {
1579 #look at the next 'line' to see if we can close it there
1580 $spliced = array_splice( $a, $k +
1, 1 );
1581 $next_line = array_shift( $spliced );
1582 $m = explode( ']]', $next_line, 3 );
1583 if ( count( $m ) == 3 ) {
1584 # the first ]] closes the inner link, the second the image
1586 $text .= "[[{$m[0]}]]{$m[1]}";
1589 } elseif ( count( $m ) == 2 ) {
1590 #if there's exactly one ]] that's fine, we'll keep looking
1591 $text .= "[[{$m[0]}]]{$m[1]}";
1593 #if $next_line is invalid too, we need look no further
1594 $text .= '[[' . $next_line;
1599 # we couldn't find the end of this imageLink, so output it raw
1600 #but don't ignore what might be perfectly normal links in the text we've examined
1601 $text = $this->replaceInternalLinks($text);
1602 $s .= "{$prefix}[[$link|$text";
1603 # note: no $trail, because without an end, there *is* no trail
1604 wfProfileOut( "$fname-might_be_img" );
1607 } else { #it's not an image, so output it raw
1608 $s .= "{$prefix}[[$link|$text";
1609 # note: no $trail, because without an end, there *is* no trail
1610 wfProfileOut( "$fname-might_be_img" );
1613 wfProfileOut( "$fname-might_be_img" );
1616 $wasblank = ( '' == $text );
1617 if( $wasblank ) $text = $link;
1619 # Link not escaped by : , create the various objects
1623 wfProfileIn( "$fname-interwiki" );
1624 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1625 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1626 $s = rtrim($s . "\n");
1627 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1628 wfProfileOut( "$fname-interwiki" );
1631 wfProfileOut( "$fname-interwiki" );
1633 if ( $ns == NS_IMAGE
) {
1634 wfProfileIn( "$fname-image" );
1635 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1636 # recursively parse links inside the image caption
1637 # actually, this will parse them in any other parameters, too,
1638 # but it might be hard to fix that, and it doesn't matter ATM
1639 $text = $this->replaceExternalLinks($text);
1640 $text = $this->replaceInternalLinks($text);
1642 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1643 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1644 $this->mOutput
->addImage( $nt->getDBkey() );
1646 wfProfileOut( "$fname-image" );
1649 # We still need to record the image's presence on the page
1650 $this->mOutput
->addImage( $nt->getDBkey() );
1652 wfProfileOut( "$fname-image" );
1656 if ( $ns == NS_CATEGORY
) {
1657 wfProfileIn( "$fname-category" );
1658 $s = rtrim($s . "\n"); # bug 87
1661 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1662 $sortkey = $this->mTitle
->getText();
1664 $sortkey = $this->mTitle
->getPrefixedText();
1669 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1670 $sortkey = str_replace( "\n", '', $sortkey );
1671 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1672 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1675 * Strip the whitespace Category links produce, see bug 87
1676 * @todo We might want to use trim($tmp, "\n") here.
1678 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1680 wfProfileOut( "$fname-category" );
1685 if( ( $nt->getPrefixedText() === $selflink ) &&
1686 ( $nt->getFragment() === '' ) ) {
1687 # Self-links are handled specially; generally de-link and change to bold.
1688 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1692 # Special and Media are pseudo-namespaces; no pages actually exist in them
1693 if( $ns == NS_MEDIA
) {
1694 $link = $sk->makeMediaLinkObj( $nt, $text );
1695 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1696 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1697 $this->mOutput
->addImage( $nt->getDBkey() );
1699 } elseif( $ns == NS_SPECIAL
) {
1700 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1702 } elseif( $ns == NS_IMAGE
) {
1703 $img = new Image( $nt );
1704 if( $img->exists() ) {
1705 // Force a blue link if the file exists; may be a remote
1706 // upload on the shared repository, and we want to see its
1707 // auto-generated page.
1708 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1712 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1714 wfProfileOut( $fname );
1719 * Make a link placeholder. The text returned can be later resolved to a real link with
1720 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1721 * parsing of interwiki links, and secondly to allow all existence checks and
1722 * article length checks (for stub links) to be bundled into a single query.
1725 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1726 wfProfileIn( __METHOD__
);
1727 if ( ! is_object($nt) ) {
1729 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1731 # Separate the link trail from the rest of the link
1732 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1734 if ( $nt->isExternal() ) {
1735 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1736 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1737 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1739 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1740 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1741 $this->mLinkHolders
['queries'][] = $query;
1742 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1743 $this->mLinkHolders
['titles'][] = $nt;
1745 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1748 wfProfileOut( __METHOD__
);
1753 * Render a forced-blue link inline; protect against double expansion of
1754 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1755 * Since this little disaster has to split off the trail text to avoid
1756 * breaking URLs in the following text without breaking trails on the
1757 * wiki links, it's been made into a horrible function.
1760 * @param string $text
1761 * @param string $query
1762 * @param string $trail
1763 * @param string $prefix
1764 * @return string HTML-wikitext mix oh yuck
1766 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1767 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1768 $sk =& $this->mOptions
->getSkin();
1769 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1770 return $this->armorLinks( $link ) . $trail;
1774 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1775 * going to go through further parsing steps before inline URL expansion.
1777 * In particular this is important when using action=render, which causes
1778 * full URLs to be included.
1780 * Oh man I hate our multi-layer parser!
1782 * @param string more-or-less HTML
1783 * @return string less-or-more HTML with NOPARSE bits
1785 function armorLinks( $text ) {
1786 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1787 "{$this->mUniqPrefix}NOPARSE$1", $text );
1791 * Return true if subpage links should be expanded on this page.
1794 function areSubpagesAllowed() {
1795 # Some namespaces don't allow subpages
1796 global $wgNamespacesWithSubpages;
1797 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1801 * Handle link to subpage if necessary
1802 * @param string $target the source of the link
1803 * @param string &$text the link text, modified as necessary
1804 * @return string the full name of the link
1807 function maybeDoSubpageLink($target, &$text) {
1810 # :Foobar -- override special treatment of prefix (images, language links)
1811 # /Foobar -- convert to CurrentPage/Foobar
1812 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1813 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1814 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1816 $fname = 'Parser::maybeDoSubpageLink';
1817 wfProfileIn( $fname );
1818 $ret = $target; # default return value is no change
1820 # Some namespaces don't allow subpages,
1821 # so only perform processing if subpages are allowed
1822 if( $this->areSubpagesAllowed() ) {
1823 # Look at the first character
1824 if( $target != '' && $target{0} == '/' ) {
1825 # / at end means we don't want the slash to be shown
1826 if( substr( $target, -1, 1 ) == '/' ) {
1827 $target = substr( $target, 1, -1 );
1830 $noslash = substr( $target, 1 );
1833 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1834 if( '' === $text ) {
1836 } # this might be changed for ugliness reasons
1838 # check for .. subpage backlinks
1840 $nodotdot = $target;
1841 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1843 $nodotdot = substr( $nodotdot, 3 );
1845 if($dotdotcount > 0) {
1846 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1847 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1848 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1849 # / at the end means don't show full path
1850 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1851 $nodotdot = substr( $nodotdot, 0, -1 );
1852 if( '' === $text ) {
1856 $nodotdot = trim( $nodotdot );
1857 if( $nodotdot != '' ) {
1858 $ret .= '/' . $nodotdot;
1865 wfProfileOut( $fname );
1870 * Used by doBlockLevels()
1873 /* private */ function closeParagraph() {
1875 if ( '' != $this->mLastSection
) {
1876 $result = '</' . $this->mLastSection
. ">\n";
1878 $this->mInPre
= false;
1879 $this->mLastSection
= '';
1882 # getCommon() returns the length of the longest common substring
1883 # of both arguments, starting at the beginning of both.
1885 /* private */ function getCommon( $st1, $st2 ) {
1886 $fl = strlen( $st1 );
1887 $shorter = strlen( $st2 );
1888 if ( $fl < $shorter ) { $shorter = $fl; }
1890 for ( $i = 0; $i < $shorter; ++
$i ) {
1891 if ( $st1{$i} != $st2{$i} ) { break; }
1895 # These next three functions open, continue, and close the list
1896 # element appropriate to the prefix character passed into them.
1898 /* private */ function openList( $char ) {
1899 $result = $this->closeParagraph();
1901 if ( '*' == $char ) { $result .= '<ul><li>'; }
1902 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1903 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1904 else if ( ';' == $char ) {
1905 $result .= '<dl><dt>';
1906 $this->mDTopen
= true;
1908 else { $result = '<!-- ERR 1 -->'; }
1913 /* private */ function nextItem( $char ) {
1914 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1915 else if ( ':' == $char ||
';' == $char ) {
1917 if ( $this->mDTopen
) { $close = '</dt>'; }
1918 if ( ';' == $char ) {
1919 $this->mDTopen
= true;
1920 return $close . '<dt>';
1922 $this->mDTopen
= false;
1923 return $close . '<dd>';
1926 return '<!-- ERR 2 -->';
1929 /* private */ function closeList( $char ) {
1930 if ( '*' == $char ) { $text = '</li></ul>'; }
1931 else if ( '#' == $char ) { $text = '</li></ol>'; }
1932 else if ( ':' == $char ) {
1933 if ( $this->mDTopen
) {
1934 $this->mDTopen
= false;
1935 $text = '</dt></dl>';
1937 $text = '</dd></dl>';
1940 else { return '<!-- ERR 3 -->'; }
1946 * Make lists from lines starting with ':', '*', '#', etc.
1949 * @return string the lists rendered as HTML
1951 function doBlockLevels( $text, $linestart ) {
1952 $fname = 'Parser::doBlockLevels';
1953 wfProfileIn( $fname );
1955 # Parsing through the text line by line. The main thing
1956 # happening here is handling of block-level elements p, pre,
1957 # and making lists from lines starting with * # : etc.
1959 $textLines = explode( "\n", $text );
1961 $lastPrefix = $output = '';
1962 $this->mDTopen
= $inBlockElem = false;
1964 $paragraphStack = false;
1966 if ( !$linestart ) {
1967 $output .= array_shift( $textLines );
1969 foreach ( $textLines as $oLine ) {
1970 $lastPrefixLength = strlen( $lastPrefix );
1971 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1972 $preOpenMatch = preg_match('/<pre/i', $oLine );
1973 if ( !$this->mInPre
) {
1974 # Multiple prefixes may abut each other for nested lists.
1975 $prefixLength = strspn( $oLine, '*#:;' );
1976 $pref = substr( $oLine, 0, $prefixLength );
1979 $pref2 = str_replace( ';', ':', $pref );
1980 $t = substr( $oLine, $prefixLength );
1981 $this->mInPre
= !empty($preOpenMatch);
1983 # Don't interpret any other prefixes in preformatted text
1985 $pref = $pref2 = '';
1990 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1991 # Same as the last item, so no need to deal with nesting or opening stuff
1992 $output .= $this->nextItem( substr( $pref, -1 ) );
1993 $paragraphStack = false;
1995 if ( substr( $pref, -1 ) == ';') {
1996 # The one nasty exception: definition lists work like this:
1997 # ; title : definition text
1998 # So we check for : in the remainder text to split up the
1999 # title and definition, without b0rking links.
2001 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2003 $output .= $term . $this->nextItem( ':' );
2006 } elseif( $prefixLength ||
$lastPrefixLength ) {
2007 # Either open or close a level...
2008 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2009 $paragraphStack = false;
2011 while( $commonPrefixLength < $lastPrefixLength ) {
2012 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2013 --$lastPrefixLength;
2015 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2016 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2018 while ( $prefixLength > $commonPrefixLength ) {
2019 $char = substr( $pref, $commonPrefixLength, 1 );
2020 $output .= $this->openList( $char );
2022 if ( ';' == $char ) {
2023 # FIXME: This is dupe of code above
2024 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2026 $output .= $term . $this->nextItem( ':' );
2029 ++
$commonPrefixLength;
2031 $lastPrefix = $pref2;
2033 if( 0 == $prefixLength ) {
2034 wfProfileIn( "$fname-paragraph" );
2035 # No prefix (not in list)--go to paragraph mode
2036 // XXX: use a stack for nestable elements like span, table and div
2037 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
2038 $closematch = preg_match(
2039 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2040 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
2041 if ( $openmatch or $closematch ) {
2042 $paragraphStack = false;
2043 #Â TODO bug 5718: paragraph closed
2044 $output .= $this->closeParagraph();
2045 if ( $preOpenMatch and !$preCloseMatch ) {
2046 $this->mInPre
= true;
2048 if ( $closematch ) {
2049 $inBlockElem = false;
2051 $inBlockElem = true;
2053 } else if ( !$inBlockElem && !$this->mInPre
) {
2054 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
2056 if ($this->mLastSection
!= 'pre') {
2057 $paragraphStack = false;
2058 $output .= $this->closeParagraph().'<pre>';
2059 $this->mLastSection
= 'pre';
2061 $t = substr( $t, 1 );
2064 if ( '' == trim($t) ) {
2065 if ( $paragraphStack ) {
2066 $output .= $paragraphStack.'<br />';
2067 $paragraphStack = false;
2068 $this->mLastSection
= 'p';
2070 if ($this->mLastSection
!= 'p' ) {
2071 $output .= $this->closeParagraph();
2072 $this->mLastSection
= '';
2073 $paragraphStack = '<p>';
2075 $paragraphStack = '</p><p>';
2079 if ( $paragraphStack ) {
2080 $output .= $paragraphStack;
2081 $paragraphStack = false;
2082 $this->mLastSection
= 'p';
2083 } else if ($this->mLastSection
!= 'p') {
2084 $output .= $this->closeParagraph().'<p>';
2085 $this->mLastSection
= 'p';
2090 wfProfileOut( "$fname-paragraph" );
2092 // somewhere above we forget to get out of pre block (bug 785)
2093 if($preCloseMatch && $this->mInPre
) {
2094 $this->mInPre
= false;
2096 if ($paragraphStack === false) {
2100 while ( $prefixLength ) {
2101 $output .= $this->closeList( $pref2{$prefixLength-1} );
2104 if ( '' != $this->mLastSection
) {
2105 $output .= '</' . $this->mLastSection
. '>';
2106 $this->mLastSection
= '';
2109 wfProfileOut( $fname );
2114 * Split up a string on ':', ignoring any occurences inside tags
2115 * to prevent illegal overlapping.
2116 * @param string $str the string to split
2117 * @param string &$before set to everything before the ':'
2118 * @param string &$after set to everything after the ':'
2119 * return string the position of the ':', or false if none found
2121 function findColonNoLinks($str, &$before, &$after) {
2122 $fname = 'Parser::findColonNoLinks';
2123 wfProfileIn( $fname );
2125 $pos = strpos( $str, ':' );
2126 if( $pos === false ) {
2128 wfProfileOut( $fname );
2132 $lt = strpos( $str, '<' );
2133 if( $lt === false ||
$lt > $pos ) {
2134 // Easy; no tag nesting to worry about
2135 $before = substr( $str, 0, $pos );
2136 $after = substr( $str, $pos+
1 );
2137 wfProfileOut( $fname );
2141 // Ugly state machine to walk through avoiding tags.
2142 $state = MW_COLON_STATE_TEXT
;
2144 $len = strlen( $str );
2145 for( $i = 0; $i < $len; $i++
) {
2149 // (Using the number is a performance hack for common cases)
2150 case 0: // MW_COLON_STATE_TEXT:
2153 // Could be either a <start> tag or an </end> tag
2154 $state = MW_COLON_STATE_TAGSTART
;
2159 $before = substr( $str, 0, $i );
2160 $after = substr( $str, $i +
1 );
2161 wfProfileOut( $fname );
2164 // Embedded in a tag; don't break it.
2167 // Skip ahead looking for something interesting
2168 $colon = strpos( $str, ':', $i );
2169 if( $colon === false ) {
2170 // Nothing else interesting
2171 wfProfileOut( $fname );
2174 $lt = strpos( $str, '<', $i );
2175 if( $stack === 0 ) {
2176 if( $lt === false ||
$colon < $lt ) {
2178 $before = substr( $str, 0, $colon );
2179 $after = substr( $str, $colon +
1 );
2180 wfProfileOut( $fname );
2184 if( $lt === false ) {
2185 // Nothing else interesting to find; abort!
2186 // We're nested, but there's no close tags left. Abort!
2189 // Skip ahead to next tag start
2191 $state = MW_COLON_STATE_TAGSTART
;
2194 case 1: // MW_COLON_STATE_TAG:
2199 $state = MW_COLON_STATE_TEXT
;
2202 // Slash may be followed by >?
2203 $state = MW_COLON_STATE_TAGSLASH
;
2209 case 2: // MW_COLON_STATE_TAGSTART:
2212 $state = MW_COLON_STATE_CLOSETAG
;
2215 $state = MW_COLON_STATE_COMMENT
;
2218 // Illegal early close? This shouldn't happen D:
2219 $state = MW_COLON_STATE_TEXT
;
2222 $state = MW_COLON_STATE_TAG
;
2225 case 3: // MW_COLON_STATE_CLOSETAG:
2230 wfDebug( "Invalid input in $fname; too many close tags\n" );
2231 wfProfileOut( $fname );
2234 $state = MW_COLON_STATE_TEXT
;
2237 case MW_COLON_STATE_TAGSLASH
:
2239 // Yes, a self-closed tag <blah/>
2240 $state = MW_COLON_STATE_TEXT
;
2242 // Probably we're jumping the gun, and this is an attribute
2243 $state = MW_COLON_STATE_TAG
;
2246 case 5: // MW_COLON_STATE_COMMENT:
2248 $state = MW_COLON_STATE_COMMENTDASH
;
2251 case MW_COLON_STATE_COMMENTDASH
:
2253 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2255 $state = MW_COLON_STATE_COMMENT
;
2258 case MW_COLON_STATE_COMMENTDASHDASH
:
2260 $state = MW_COLON_STATE_TEXT
;
2262 $state = MW_COLON_STATE_COMMENT
;
2266 throw new MWException( "State machine error in $fname" );
2270 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2273 wfProfileOut( $fname );
2278 * Return value of a magic variable (like PAGENAME)
2282 function getVariableValue( $index ) {
2283 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2286 * Some of these require message or data lookups and can be
2287 * expensive to check many times.
2289 static $varCache = array();
2290 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2291 if ( isset( $varCache[$index] ) )
2292 return $varCache[$index];
2295 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2298 case 'currentmonth':
2299 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2300 case 'currentmonthname':
2301 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2302 case 'currentmonthnamegen':
2303 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2304 case 'currentmonthabbrev':
2305 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2307 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2309 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2311 return $this->mTitle
->getText();
2313 return $this->mTitle
->getPartialURL();
2314 case 'fullpagename':
2315 return $this->mTitle
->getPrefixedText();
2316 case 'fullpagenamee':
2317 return $this->mTitle
->getPrefixedURL();
2319 return $this->mTitle
->getSubpageText();
2320 case 'subpagenamee':
2321 return $this->mTitle
->getSubpageUrlForm();
2322 case 'basepagename':
2323 return $this->mTitle
->getBaseText();
2324 case 'basepagenamee':
2325 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2326 case 'talkpagename':
2327 if( $this->mTitle
->canTalk() ) {
2328 $talkPage = $this->mTitle
->getTalkPage();
2329 return $talkPage->getPrefixedText();
2333 case 'talkpagenamee':
2334 if( $this->mTitle
->canTalk() ) {
2335 $talkPage = $this->mTitle
->getTalkPage();
2336 return $talkPage->getPrefixedUrl();
2340 case 'subjectpagename':
2341 $subjPage = $this->mTitle
->getSubjectPage();
2342 return $subjPage->getPrefixedText();
2343 case 'subjectpagenamee':
2344 $subjPage = $this->mTitle
->getSubjectPage();
2345 return $subjPage->getPrefixedUrl();
2347 return $this->mRevisionId
;
2349 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2351 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2353 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2355 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2356 case 'subjectspace':
2357 return $this->mTitle
->getSubjectNsText();
2358 case 'subjectspacee':
2359 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2360 case 'currentdayname':
2361 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2363 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2365 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2367 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2368 // int to remove the padding
2369 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2371 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2372 case 'numberofarticles':
2373 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2374 case 'numberoffiles':
2375 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2376 case 'numberofusers':
2377 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2378 case 'numberofpages':
2379 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2380 case 'numberofadmins':
2381 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2382 case 'currenttimestamp':
2383 return $varCache[$index] = wfTimestampNow();
2384 case 'currentversion':
2392 return $wgServerName;
2394 return $wgScriptPath;
2395 case 'directionmark':
2396 return $wgContLang->getDirMark();
2397 case 'contentlanguage':
2398 global $wgContLanguageCode;
2399 return $wgContLanguageCode;
2402 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2410 * initialise the magic variables (like CURRENTMONTHNAME)
2414 function initialiseVariables() {
2415 $fname = 'Parser::initialiseVariables';
2416 wfProfileIn( $fname );
2417 $variableIDs = MagicWord
::getVariableIDs();
2419 $this->mVariables
= array();
2420 foreach ( $variableIDs as $id ) {
2421 $mw =& MagicWord
::get( $id );
2422 $mw->addToArray( $this->mVariables
, $id );
2424 wfProfileOut( $fname );
2428 * parse any parentheses in format ((title|part|part))
2429 * and call callbacks to get a replacement text for any found piece
2431 * @param string $text The text to parse
2432 * @param array $callbacks rules in form:
2433 * '{' => array( # opening parentheses
2434 * 'end' => '}', # closing parentheses
2435 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2436 * 3 => callback # replacement callback to call if {{{..}}} is found
2439 * 'min' => 2, # Minimum parenthesis count in cb
2440 * 'max' => 3, # Maximum parenthesis count in cb
2443 function replace_callback ($text, $callbacks) {
2444 wfProfileIn( __METHOD__
);
2445 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2446 $lastOpeningBrace = -1; # last not closed parentheses
2448 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2451 while ( $i < strlen( $text ) ) {
2452 # Find next opening brace, closing brace or pipe
2453 if ( $lastOpeningBrace == -1 ) {
2454 $currentClosing = '';
2455 $search = $validOpeningBraces;
2457 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2458 $search = $validOpeningBraces . '|' . $currentClosing;
2461 $i +
= strcspn( $text, $search, $i );
2462 if ( $i < strlen( $text ) ) {
2463 if ( $text[$i] == '|' ) {
2465 } elseif ( $text[$i] == $currentClosing ) {
2469 $rule = $callbacks[$text[$i]];
2476 if ( $found == 'open' ) {
2477 # found opening brace, let's add it to parentheses stack
2478 $piece = array('brace' => $text[$i],
2479 'braceEnd' => $rule['end'],
2483 # count opening brace characters
2484 $piece['count'] = strspn( $text, $piece['brace'], $i );
2485 $piece['startAt'] = $piece['partStart'] = $i +
$piece['count'];
2486 $i +
= $piece['count'];
2488 # we need to add to stack only if opening brace count is enough for one of the rules
2489 if ( $piece['count'] >= $rule['min'] ) {
2490 $lastOpeningBrace ++
;
2491 $openingBraceStack[$lastOpeningBrace] = $piece;
2493 } elseif ( $found == 'close' ) {
2494 # lets check if it is enough characters for closing brace
2495 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2496 $count = strspn( $text, $text[$i], $i, $maxCount );
2498 # check for maximum matching characters (if there are 5 closing
2499 # characters, we will probably need only 3 - depending on the rules)
2501 $matchingCallback = null;
2502 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2503 if ( $count > $cbType['max'] ) {
2504 # The specified maximum exists in the callback array, unless the caller
2506 $matchingCount = $cbType['max'];
2508 # Count is less than the maximum
2509 # Skip any gaps in the callback array to find the true largest match
2510 # Need to use array_key_exists not isset because the callback can be null
2511 $matchingCount = $count;
2512 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2517 if ($matchingCount <= 0) {
2521 $matchingCallback = $cbType['cb'][$matchingCount];
2523 # let's set a title or last part (if '|' was found)
2524 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2525 $openingBraceStack[$lastOpeningBrace]['title'] =
2526 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2527 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2529 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2530 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2531 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2534 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2535 $pieceEnd = $i +
$matchingCount;
2537 if( is_callable( $matchingCallback ) ) {
2539 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2540 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2541 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2542 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2544 # finally we can call a user callback and replace piece of text
2545 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2546 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2547 $i = $pieceStart +
strlen($replaceWith);
2549 # null value for callback means that parentheses should be parsed, but not replaced
2550 $i +
= $matchingCount;
2553 # reset last opening parentheses, but keep it in case there are unused characters
2554 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2555 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2556 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2559 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2560 $openingBraceStack[$lastOpeningBrace--] = null;
2562 if ($matchingCount < $piece['count']) {
2563 $piece['count'] -= $matchingCount;
2564 $piece['startAt'] -= $matchingCount;
2565 $piece['partStart'] = $piece['startAt'];
2566 # do we still qualify for any callback with remaining count?
2567 $currentCbList = $callbacks[$piece['brace']]['cb'];
2568 while ( $piece['count'] ) {
2569 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2570 $lastOpeningBrace++
;
2571 $openingBraceStack[$lastOpeningBrace] = $piece;
2577 } elseif ( $found == 'pipe' ) {
2578 # lets set a title if it is a first separator, or next part otherwise
2579 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2580 $openingBraceStack[$lastOpeningBrace]['title'] =
2581 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2582 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2583 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2585 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2586 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2587 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2589 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++
$i;
2593 wfProfileOut( __METHOD__
);
2598 * Replace magic variables, templates, and template arguments
2599 * with the appropriate text. Templates are substituted recursively,
2600 * taking care to avoid infinite loops.
2602 * Note that the substitution depends on value of $mOutputType:
2603 * OT_WIKI: only {{subst:}} templates
2604 * OT_MSG: only magic variables
2605 * OT_HTML: all templates and magic variables
2607 * @param string $tex The text to transform
2608 * @param array $args Key-value pairs representing template parameters to substitute
2609 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2612 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2613 # Prevent too big inclusions
2614 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2618 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2619 wfProfileIn( $fname );
2621 # This function is called recursively. To keep track of arguments we need a stack:
2622 array_push( $this->mArgStack
, $args );
2624 $braceCallbacks = array();
2626 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2628 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2629 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2631 if ( $braceCallbacks ) {
2635 'cb' => $braceCallbacks,
2636 'min' => $argsOnly ?
3 : 2,
2637 'max' => isset( $braceCallbacks[3] ) ?
3 : 2,
2641 'cb' => array(2=>null),
2646 $text = $this->replace_callback ($text, $callbacks);
2648 array_pop( $this->mArgStack
);
2650 wfProfileOut( $fname );
2655 * Replace magic variables
2658 function variableSubstitution( $matches ) {
2659 $fname = 'Parser::variableSubstitution';
2660 $varname = $matches[1];
2661 wfProfileIn( $fname );
2663 if ( $this->mOutputType
== OT_WIKI
) {
2664 # Do only magic variables prefixed by SUBST
2665 $mwSubst =& MagicWord
::get( 'subst' );
2666 if (!$mwSubst->matchStartAndRemove( $varname ))
2668 # Note that if we don't substitute the variable below,
2669 # we don't remove the {{subst:}} magic word, in case
2670 # it is a template rather than a magic variable.
2672 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2673 $id = $this->mVariables
[$varname];
2674 $text = $this->getVariableValue( $id );
2675 $this->mOutput
->mContainsOldMagic
= true;
2677 $text = $matches[0];
2679 wfProfileOut( $fname );
2683 # Split template arguments
2684 function getTemplateArgs( $argsString ) {
2685 if ( $argsString === '' ) {
2689 $args = explode( '|', substr( $argsString, 1 ) );
2691 # If any of the arguments contains a '[[' but no ']]', it needs to be
2692 # merged with the next arg because the '|' character between belongs
2693 # to the link syntax and not the template parameter syntax.
2694 $argc = count($args);
2696 for ( $i = 0; $i < $argc-1; $i++
) {
2697 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2698 $args[$i] .= '|'.$args[$i+
1];
2699 array_splice($args, $i+
1, 1);
2709 * Return the text of a template, after recursively
2710 * replacing any variables or templates within the template.
2712 * @param array $piece The parts of the template
2713 * $piece['text']: matched text
2714 * $piece['title']: the title, i.e. the part before the |
2715 * $piece['parts']: the parameter array
2716 * @return string the text of the template
2719 function braceSubstitution( $piece ) {
2720 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2721 $fname = __METHOD__
/*. '-L' . count( $this->mArgStack )*/;
2722 wfProfileIn( $fname );
2723 wfProfileIn( __METHOD__
.'-setup' );
2726 $found = false; # $text has been filled
2727 $nowiki = false; # wiki markup in $text should be escaped
2728 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2729 $noargs = false; # Don't replace triple-brace arguments in $text
2730 $replaceHeadings = false; # Make the edit section links go to the template not the article
2731 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2732 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2734 # Title object, where $text came from
2739 # $part1 is the bit before the first |, and must contain only title characters
2740 # $args is a list of arguments, starting from index 0, not including $part1
2742 $part1 = $piece['title'];
2743 # If the third subpattern matched anything, it will start with |
2745 if (null == $piece['parts']) {
2746 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2747 if ($replaceWith != $piece['text']) {
2748 $text = $replaceWith;
2755 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2756 $argc = count( $args );
2757 wfProfileOut( __METHOD__
.'-setup' );
2760 wfProfileIn( __METHOD__
.'-modifiers' );
2762 $mwSubst =& MagicWord
::get( 'subst' );
2763 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2764 # One of two possibilities is true:
2765 # 1) Found SUBST but not in the PST phase
2766 # 2) Didn't find SUBST and in the PST phase
2767 # In either case, return without further processing
2768 $text = $piece['text'];
2775 # MSG, MSGNW, INT and RAW
2778 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2779 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2782 # Remove obsolete MSG:
2783 $mwMsg =& MagicWord
::get( 'msg' );
2784 $mwMsg->matchStartAndRemove( $part1 );
2788 $mwRaw =& MagicWord
::get( 'raw' );
2789 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2790 $forceRawInterwiki = true;
2793 # Check if it is an internal message
2794 $mwInt =& MagicWord
::get( 'int' );
2795 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2796 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2797 $text = $linestart . wfMsgReal( $part1, $args, true );
2802 wfProfileOut( __METHOD__
.'-modifiers' );
2806 wfProfileIn( __METHOD__
. '-pfunc' );
2808 $colonPos = strpos( $part1, ':' );
2809 if ( $colonPos !== false ) {
2810 # Case sensitive functions
2811 $function = substr( $part1, 0, $colonPos );
2812 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2813 $function = $this->mFunctionSynonyms
[1][$function];
2815 # Case insensitive functions
2816 $function = strtolower( $function );
2817 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2818 $function = $this->mFunctionSynonyms
[0][$function];
2824 $funcArgs = array_map( 'trim', $args );
2825 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2826 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2829 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2833 if ( is_array( $result ) ) {
2834 if ( isset( $result[0] ) ) {
2835 $text = $linestart . $result[0];
2836 unset( $result[0] );
2839 // Extract flags into the local scope
2840 // This allows callers to set flags such as nowiki, noparse, found, etc.
2843 $text = $linestart . $result;
2847 wfProfileOut( __METHOD__
. '-pfunc' );
2850 # Template table test
2852 # Did we encounter this template already? If yes, it is in the cache
2853 # and we need to check for loops.
2854 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2857 # Infinite loop test
2858 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2862 $text = $linestart .
2863 '{{' . $part1 . '}}' .
2864 '<!-- WARNING: template loop detected -->';
2865 wfDebug( __METHOD__
.": template loop broken at '$part1'\n" );
2867 # set $text to cached message.
2868 $text = $linestart . $this->mTemplates
[$piece['title']];
2872 # Load from database
2873 $lastPathLevel = $this->mTemplatePath
;
2875 wfProfileIn( __METHOD__
. '-loadtpl' );
2877 # declaring $subpage directly in the function call
2878 # does not work correctly with references and breaks
2879 # {{/subpage}}-style inclusions
2881 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2882 if ($subpage !== '') {
2883 $ns = $this->mTitle
->getNamespace();
2885 $title = Title
::newFromText( $part1, $ns );
2888 if ( !is_null( $title ) ) {
2889 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2890 # Check for language variants if the template is not found
2891 if($checkVariantLink && $title->getArticleID() == 0){
2892 $wgContLang->findVariantLink($part1, $title);
2895 if ( !$title->isExternal() ) {
2896 # Check for excessive inclusion
2897 $dbk = $title->getPrefixedDBkey();
2898 if ( $this->incrementIncludeCount( $dbk ) ) {
2899 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2900 $text = SpecialPage
::capturePath( $title );
2901 if ( is_string( $text ) ) {
2906 $this->disableCache();
2909 $articleContent = $this->fetchTemplate( $title );
2910 if ( $articleContent !== false ) {
2912 $text = $articleContent;
2913 $replaceHeadings = true;
2918 # If the title is valid but undisplayable, make a link to it
2919 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2920 $text = '[['.$title->getPrefixedText().']]';
2923 } elseif ( $title->isTrans() ) {
2924 // Interwiki transclusion
2925 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2926 $text = $this->interwikiTransclude( $title, 'render' );
2930 $text = $this->interwikiTransclude( $title, 'raw' );
2931 $replaceHeadings = true;
2936 # Template cache array insertion
2937 # Use the original $piece['title'] not the mangled $part1, so that
2938 # modifiers such as RAW: produce separate cache entries
2941 // A special page; don't store it in the template cache.
2943 $this->mTemplates
[$piece['title']] = $text;
2945 $text = $linestart . $text;
2948 wfProfileOut( __METHOD__
. '-loadtpl' );
2951 # Recursive parsing, escaping and link table handling
2952 # Only for HTML output
2953 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2954 $text = wfEscapeWikiText( $text );
2955 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2957 $assocArgs = array();
2959 # Clean up argument array
2960 $assocArgs = array();
2962 foreach( $args as $arg ) {
2963 $eqpos = strpos( $arg, '=' );
2964 if ( $eqpos === false ) {
2965 $assocArgs[$index++
] = $arg;
2967 $name = trim( substr( $arg, 0, $eqpos ) );
2968 $value = trim( substr( $arg, $eqpos+
1 ) );
2969 if ( $value === false ) {
2972 if ( $name !== false ) {
2973 $assocArgs[$name] = $value;
2978 # Add a new element to the templace recursion path
2979 $this->mTemplatePath
[$part1] = 1;
2983 # If there are any <onlyinclude> tags, only include them
2984 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2985 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2987 foreach ($m[1] as $piece)
2990 # Remove <noinclude> sections and <includeonly> tags
2991 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2992 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2994 if( $this->mOutputType
== OT_HTML
) {
2995 # Strip <nowiki>, <pre>, etc.
2996 $text = $this->strip( $text, $this->mStripState
);
2997 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2999 $text = $this->replaceVariables( $text, $assocArgs );
3001 # If the template begins with a table or block-level
3002 # element, it should be treated as beginning a new line.
3003 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
3004 $text = "\n" . $text;
3006 } elseif ( !$noargs ) {
3007 # $noparse and !$noargs
3008 # Just replace the arguments, not any double-brace items
3009 # This is used for rendered interwiki transclusion
3010 $text = $this->replaceVariables( $text, $assocArgs, true );
3013 # Prune lower levels off the recursion check path
3014 $this->mTemplatePath
= $lastPathLevel;
3017 wfProfileOut( $fname );
3018 return $piece['text'];
3020 wfProfileIn( __METHOD__
. '-placeholders' );
3022 # Replace raw HTML by a placeholder
3023 # Add a blank line preceding, to prevent it from mucking up
3024 # immediately preceding headings
3025 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
3027 # replace ==section headers==
3028 # XXX this needs to go away once we have a better parser.
3029 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
3030 if( !is_null( $title ) )
3031 $encodedname = base64_encode($title->getPrefixedDBkey());
3033 $encodedname = base64_encode("");
3034 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3035 PREG_SPLIT_DELIM_CAPTURE
);
3038 for( $i = 0; $i < count($m); $i +
= 2 ) {
3040 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
3042 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3046 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3047 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3048 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3054 wfProfileOut( __METHOD__
. '-placeholders' );
3057 # Prune lower levels off the recursion check path
3058 $this->mTemplatePath
= $lastPathLevel;
3061 wfProfileOut( $fname );
3062 return $piece['text'];
3064 wfProfileOut( $fname );
3070 * Fetch the unparsed text of a template and register a reference to it.
3072 function fetchTemplate( $title ) {
3074 // Loop to fetch the article, with up to 1 redirect
3075 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3076 $rev = Revision
::newFromTitle( $title );
3077 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
3081 $text = $rev->getText();
3082 if ( $text === false ) {
3086 $title = Title
::newFromRedirect( $text );
3092 * Transclude an interwiki link.
3094 function interwikiTransclude( $title, $action ) {
3095 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3097 if (!$wgEnableScaryTranscluding)
3098 return wfMsg('scarytranscludedisabled');
3100 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3101 // But we'll handle it generally anyway
3102 if ( $title->getNamespace() ) {
3103 // Use the canonical namespace, which should work anywhere
3104 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3106 $articleName = $title->getDBkey();
3109 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3110 $url .= "?action=$action";
3111 if (strlen($url) > 255)
3112 return wfMsg('scarytranscludetoolong');
3113 return $this->fetchScaryTemplateMaybeFromCache($url);
3116 function fetchScaryTemplateMaybeFromCache($url) {
3117 global $wgTranscludeCacheExpiry;
3118 $dbr =& wfGetDB(DB_SLAVE
);
3119 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3120 array('tc_url' => $url));
3122 $time = $obj->tc_time
;
3123 $text = $obj->tc_contents
;
3124 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3129 $text = Http
::get($url);
3131 return wfMsg('scarytranscludefailed', $url);
3133 $dbw =& wfGetDB(DB_MASTER
);
3134 $dbw->replace('transcache', array('tc_url'), array(
3136 'tc_time' => time(),
3137 'tc_contents' => $text));
3143 * Triple brace replacement -- used for template arguments
3146 function argSubstitution( $matches ) {
3147 $arg = trim( $matches['title'] );
3148 $text = $matches['text'];
3149 $inputArgs = end( $this->mArgStack
);
3151 if ( array_key_exists( $arg, $inputArgs ) ) {
3152 $text = $inputArgs[$arg];
3153 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3154 $text = $matches['parts'][0];
3161 * Returns true if the function is allowed to include this entity
3164 function incrementIncludeCount( $dbk ) {
3165 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3166 $this->mIncludeCount
[$dbk] = 0;
3168 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3176 * Detect __NOGALLERY__ magic word and set a placeholder
3178 function stripNoGallery( &$text ) {
3179 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3181 $mw = MagicWord
::get( 'nogallery' );
3182 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3186 * Detect __TOC__ magic word and set a placeholder
3188 function stripToc( $text ) {
3189 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3191 $mw = MagicWord
::get( 'notoc' );
3192 if( $mw->matchAndRemove( $text ) ) {
3193 $this->mShowToc
= false;
3196 $mw = MagicWord
::get( 'toc' );
3197 if( $mw->match( $text ) ) {
3198 $this->mShowToc
= true;
3199 $this->mForceTocPosition
= true;
3201 // Set a placeholder. At the end we'll fill it in with the TOC.
3202 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3204 // Only keep the first one.
3205 $text = $mw->replace( '', $text );
3211 * This function accomplishes several tasks:
3212 * 1) Auto-number headings if that option is enabled
3213 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3214 * 3) Add a Table of contents on the top for users who have enabled the option
3215 * 4) Auto-anchor headings
3217 * It loops through all headlines, collects the necessary data, then splits up the
3218 * string and re-inserts the newly formatted headlines.
3220 * @param string $text
3221 * @param boolean $isMain
3224 function formatHeadings( $text, $isMain=true ) {
3225 global $wgMaxTocLevel, $wgContLang;
3227 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3228 if( !$this->mTitle
->userCanEdit() ) {
3231 $showEditLink = $this->mOptions
->getEditSection();
3234 # Inhibit editsection links if requested in the page
3235 $esw =& MagicWord
::get( 'noeditsection' );
3236 if( $esw->matchAndRemove( $text ) ) {
3240 # Get all headlines for numbering them and adding funky stuff like [edit]
3241 # links - this is for later, but we need the number of headlines right now
3242 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3244 # if there are fewer than 4 headlines in the article, do not show TOC
3245 # unless it's been explicitly enabled.
3246 $enoughToc = $this->mShowToc
&&
3247 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3249 # Allow user to stipulate that a page should have a "new section"
3250 # link added via __NEWSECTIONLINK__
3251 $mw =& MagicWord
::get( 'newsectionlink' );
3252 if( $mw->matchAndRemove( $text ) )
3253 $this->mOutput
->setNewSection( true );
3255 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3256 # override above conditions and always show TOC above first header
3257 $mw =& MagicWord
::get( 'forcetoc' );
3258 if ($mw->matchAndRemove( $text ) ) {
3259 $this->mShowToc
= true;
3263 # Never ever show TOC if no headers
3264 if( $numMatches < 1 ) {
3268 # We need this to perform operations on the HTML
3269 $sk =& $this->mOptions
->getSkin();
3273 $sectionCount = 0; # headlineCount excluding template sections
3275 # Ugh .. the TOC should have neat indentation levels which can be
3276 # passed to the skin functions. These are determined here
3280 $sublevelCount = array();
3281 $levelCount = array();
3288 foreach( $matches[3] as $headline ) {
3290 $templatetitle = '';
3291 $templatesection = 0;
3294 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3296 $templatetitle = base64_decode($mat[1]);
3297 $templatesection = 1 +
(int)base64_decode($mat[2]);
3298 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3302 $prevlevel = $level;
3303 $prevtoclevel = $toclevel;
3305 $level = $matches[1][$headlineCount];
3307 if( $doNumberHeadings ||
$enoughToc ) {
3309 if ( $level > $prevlevel ) {
3310 # Increase TOC level
3312 $sublevelCount[$toclevel] = 0;
3313 if( $toclevel<$wgMaxTocLevel ) {
3314 $toc .= $sk->tocIndent();
3317 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3318 # Decrease TOC level, find level to jump to
3320 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3321 # Can only go down to level 1
3324 for ($i = $toclevel; $i > 0; $i--) {
3325 if ( $levelCount[$i] == $level ) {
3326 # Found last matching level
3330 elseif ( $levelCount[$i] < $level ) {
3331 # Found first matching level below current level
3337 if( $toclevel<$wgMaxTocLevel ) {
3338 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3342 # No change in level, end TOC line
3343 if( $toclevel<$wgMaxTocLevel ) {
3344 $toc .= $sk->tocLineEnd();
3348 $levelCount[$toclevel] = $level;
3350 # count number of headlines for each level
3351 @$sublevelCount[$toclevel]++
;
3353 for( $i = 1; $i <= $toclevel; $i++
) {
3354 if( !empty( $sublevelCount[$i] ) ) {
3358 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3364 # The canonized header is a version of the header text safe to use for links
3365 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3366 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3367 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3369 # Remove link placeholders by the link text.
3370 # <!--LINK number-->
3372 # link text with suffix
3373 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3374 "\$this->mLinkHolders['texts'][\$1]",
3375 $canonized_headline );
3376 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3377 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3378 $canonized_headline );
3381 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3382 $tocline = trim( $canonized_headline );
3383 # Save headline for section edit hint before it's escaped
3384 $headline_hint = trim( $canonized_headline );
3385 $canonized_headline = Sanitizer
::escapeId( $tocline );
3386 $refers[$headlineCount] = $canonized_headline;
3388 # count how many in assoc. array so we can track dupes in anchors
3389 @$refers[$canonized_headline]++
;
3390 $refcount[$headlineCount]=$refers[$canonized_headline];
3392 # Don't number the heading if it is the only one (looks silly)
3393 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3394 # the two are different if the line contains a link
3395 $headline=$numbering . ' ' . $headline;
3398 # Create the anchor for linking from the TOC to the section
3399 $anchor = $canonized_headline;
3400 if($refcount[$headlineCount] > 1 ) {
3401 $anchor .= '_' . $refcount[$headlineCount];
3403 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3404 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3406 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3407 if ( empty( $head[$headlineCount] ) ) {
3408 $head[$headlineCount] = '';
3411 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3413 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3416 # give headline the correct <h#> tag
3417 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3425 if( $toclevel<$wgMaxTocLevel ) {
3426 $toc .= $sk->tocUnindent( $toclevel - 1 );
3428 $toc = $sk->tocList( $toc );
3431 # split up and insert constructed headlines
3433 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3436 foreach( $blocks as $block ) {
3437 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3438 # This is the [edit] link that appears for the top block of text when
3439 # section editing is enabled
3441 # Disabled because it broke block formatting
3442 # For example, a bullet point in the top line
3443 # $full .= $sk->editSectionLink(0);
3446 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3447 # Top anchor now in skin
3451 if( !empty( $head[$i] ) ) {
3456 if( $this->mForceTocPosition
) {
3457 return str_replace( '<!--MWTOC-->', $toc, $full );
3464 * Transform wiki markup when saving a page by doing \r\n -> \n
3465 * conversion, substitting signatures, {{subst:}} templates, etc.
3467 * @param string $text the text to transform
3468 * @param Title &$title the Title object for the current article
3469 * @param User &$user the User object describing the current user
3470 * @param ParserOptions $options parsing options
3471 * @param bool $clearState whether to clear the parser state first
3472 * @return string the altered wiki markup
3475 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3476 $this->mOptions
= $options;
3477 $this->mTitle
=& $title;
3478 $this->mOutputType
= OT_WIKI
;
3480 if ( $clearState ) {
3481 $this->clearState();
3484 $stripState = false;
3488 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3489 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3490 $text = $this->pstPass2( $text, $stripState, $user );
3491 $text = $this->unstrip( $text, $stripState );
3492 $text = $this->unstripNoWiki( $text, $stripState );
3497 * Pre-save transform helper function
3500 function pstPass2( $text, &$stripState, &$user ) {
3501 global $wgContLang, $wgLocaltimezone;
3503 /* Note: This is the timestamp saved as hardcoded wikitext to
3504 * the database, we use $wgContLang here in order to give
3505 * everyone the same signature and use the default one rather
3506 * than the one selected in each user's preferences.
3508 if ( isset( $wgLocaltimezone ) ) {
3509 $oldtz = getenv( 'TZ' );
3510 putenv( 'TZ='.$wgLocaltimezone );
3512 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3513 ' (' . date( 'T' ) . ')';
3514 if ( isset( $wgLocaltimezone ) ) {
3515 putenv( 'TZ='.$oldtz );
3518 # Variable replacement
3519 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3520 $text = $this->replaceVariables( $text );
3522 # Strip out <nowiki> etc. added via replaceVariables
3523 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3526 $sigText = $this->getUserSig( $user );
3527 $text = strtr( $text, array(
3529 '~~~~' => "$sigText $d",
3533 # Context links: [[|name]] and [[name (context)|]]
3535 global $wgLegalTitleChars;
3536 $tc = "[$wgLegalTitleChars]";
3538 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3539 $conpat = "/^{$tc}+?( \\({$tc}+\\)|)$/";
3541 $p1 = "/\[\[(:?$namespacechar+:|:|)({$tc}+?)( \\({$tc}+\\)|)\\|]]/"; # [[ns:page (context)|]]
3542 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3544 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3546 $t = $this->mTitle
->getText();
3547 if ( preg_match( $conpat, $t, $m ) && '' != $m[1] ) {
3548 $text = preg_replace( $p2, "[[\\1{$m[1]}|\\1]]", $text );
3550 # if $m[1] is empty, don't bother duplicating the title
3551 $text = preg_replace( $p2, '[[\\1]]', $text );
3554 # Trim trailing whitespace
3555 # __END__ tag allows for trailing
3556 # whitespace to be deliberately included
3557 $text = rtrim( $text );
3558 $mw =& MagicWord
::get( 'end' );
3559 $mw->matchAndRemove( $text );
3565 * Fetch the user's signature text, if any, and normalize to
3566 * validated, ready-to-insert wikitext.
3572 function getUserSig( &$user ) {
3573 $username = $user->getName();
3574 $nickname = $user->getOption( 'nickname' );
3575 $nickname = $nickname === '' ?
$username : $nickname;
3577 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3578 # Sig. might contain markup; validate this
3579 if( $this->validateSig( $nickname ) !== false ) {
3580 # Validated; clean up (if needed) and return it
3581 return $this->cleanSig( $nickname, true );
3583 # Failed to validate; fall back to the default
3584 $nickname = $username;
3585 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3589 // Make sure nickname doesnt get a sig in a sig
3590 $nickname = $this->cleanSigInSig( $nickname );
3592 # If we're still here, make it a link to the user page
3593 $userpage = $user->getUserPage();
3594 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3598 * Check that the user's signature contains no bad XML
3600 * @param string $text
3601 * @return mixed An expanded string, or false if invalid.
3603 function validateSig( $text ) {
3604 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3608 * Clean up signature text
3610 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3611 * 2) Substitute all transclusions
3613 * @param string $text
3614 * @param $parsing Whether we're cleaning (preferences save) or parsing
3615 * @return string Signature text
3617 function cleanSig( $text, $parsing = false ) {
3619 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3621 $substWord = MagicWord
::get( 'subst' );
3622 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3623 $substText = '{{' . $substWord->getSynonym( 0 );
3625 $text = preg_replace( $substRegex, $substText, $text );
3626 $text = $this->cleanSigInSig( $text );
3627 $text = $this->replaceVariables( $text );
3629 $this->clearState();
3634 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3635 * @param string $text
3636 * @return string Signature text with /~{3,5}/ removed
3638 function cleanSigInSig( $text ) {
3639 $text = preg_replace( '/~{3,5}/', '', $text );
3644 * Set up some variables which are usually set up in parse()
3645 * so that an external function can call some class members with confidence
3648 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3649 $this->mTitle
=& $title;
3650 $this->mOptions
= $options;
3651 $this->mOutputType
= $outputType;
3652 if ( $clearState ) {
3653 $this->clearState();
3658 * Transform a MediaWiki message by replacing magic variables.
3660 * @param string $text the text to transform
3661 * @param ParserOptions $options options
3662 * @return string the text with variables substituted
3665 function transformMsg( $text, $options ) {
3667 static $executing = false;
3669 $fname = "Parser::transformMsg";
3671 # Guard against infinite recursion
3677 wfProfileIn($fname);
3679 $this->mTitle
= $wgTitle;
3680 $this->mOptions
= $options;
3681 $this->mOutputType
= OT_MSG
;
3682 $this->clearState();
3683 $text = $this->replaceVariables( $text );
3686 wfProfileOut($fname);
3691 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3692 * The callback should have the following form:
3693 * function myParserHook( $text, $params, &$parser ) { ... }
3695 * Transform and return $text. Use $parser for any required context, e.g. use
3696 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3700 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3701 * @param mixed $callback The callback function (and object) to use for the tag
3703 * @return The old value of the mTagHooks array associated with the hook
3705 function setHook( $tag, $callback ) {
3706 $tag = strtolower( $tag );
3707 $oldVal = @$this->mTagHooks
[$tag];
3708 $this->mTagHooks
[$tag] = $callback;
3714 * Create a function, e.g. {{sum:1|2|3}}
3715 * The callback function should have the form:
3716 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3718 * The callback may either return the text result of the function, or an array with the text
3719 * in element 0, and a number of flags in the other elements. The names of the flags are
3720 * specified in the keys. Valid flags are:
3721 * found The text returned is valid, stop processing the template. This
3723 * nowiki Wiki markup in the return value should be escaped
3724 * noparse Unsafe HTML tags should not be stripped, etc.
3725 * noargs Don't replace triple-brace arguments in the return value
3726 * isHTML The returned text is HTML, armour it against wikitext transformation
3730 * @param string $id The magic word ID
3731 * @param mixed $callback The callback function (and object) to use
3732 * @param integer $flags a combination of the following flags:
3733 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3735 * @return The old callback function for this name, if any
3737 function setFunctionHook( $id, $callback, $flags = 0 ) {
3738 $oldVal = @$this->mFunctionHooks
[$id];
3739 $this->mFunctionHooks
[$id] = $callback;
3741 # Add to function cache
3742 $mw = MagicWord
::get( $id );
3744 throw new MWException( 'The calling convention to Parser::setFunctionHook() has changed, ' .
3745 'it is now required to pass a MagicWord ID as the first parameter.' );
3748 $synonyms = $mw->getSynonyms();
3749 $sensitive = intval( $mw->isCaseSensitive() );
3751 foreach ( $synonyms as $syn ) {
3753 if ( !$sensitive ) {
3754 $syn = strtolower( $syn );
3757 if ( !( $flags & SFH_NO_HASH
) ) {
3760 # Remove trailing colon
3761 if ( substr( $syn, -1, 1 ) == ':' ) {
3762 $syn = substr( $syn, 0, -1 );
3764 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3770 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3771 * Placeholders created in Skin::makeLinkObj()
3772 * Returns an array of links found, indexed by PDBK:
3776 * $options is a bit field, RLH_FOR_UPDATE to select for update
3778 function replaceLinkHolders( &$text, $options = 0 ) {
3780 global $wgOutputReplace;
3782 $fname = 'Parser::replaceLinkHolders';
3783 wfProfileIn( $fname );
3787 $sk =& $this->mOptions
->getSkin();
3788 $linkCache =& LinkCache
::singleton();
3790 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3791 wfProfileIn( $fname.'-check' );
3792 $dbr =& wfGetDB( DB_SLAVE
);
3793 $page = $dbr->tableName( 'page' );
3794 $threshold = $wgUser->getOption('stubthreshold');
3797 asort( $this->mLinkHolders
['namespaces'] );
3801 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3803 $title = $this->mLinkHolders
['titles'][$key];
3805 # Skip invalid entries.
3806 # Result will be ugly, but prevents crash.
3807 if ( is_null( $title ) ) {
3810 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3812 # Check if it's a static known link, e.g. interwiki
3813 if ( $title->isAlwaysKnown() ) {
3814 $colours[$pdbk] = 1;
3815 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3816 $colours[$pdbk] = 1;
3817 $this->mOutput
->addLink( $title, $id );
3818 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3819 $colours[$pdbk] = 0;
3821 # Not in the link cache, add it to the query
3822 if ( !isset( $current ) ) {
3824 $query = "SELECT page_id, page_namespace, page_title";
3825 if ( $threshold > 0 ) {
3826 $query .= ', page_len, page_is_redirect';
3828 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3829 } elseif ( $current != $ns ) {
3831 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3836 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3841 if ( $options & RLH_FOR_UPDATE
) {
3842 $query .= ' FOR UPDATE';
3845 $res = $dbr->query( $query, $fname );
3847 # Fetch data and form into an associative array
3848 # non-existent = broken
3851 while ( $s = $dbr->fetchObject($res) ) {
3852 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3853 $pdbk = $title->getPrefixedDBkey();
3854 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3855 $this->mOutput
->addLink( $title, $s->page_id
);
3857 if ( $threshold > 0 ) {
3858 $size = $s->page_len
;
3859 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3860 $colours[$pdbk] = 1;
3862 $colours[$pdbk] = 2;
3865 $colours[$pdbk] = 1;
3869 wfProfileOut( $fname.'-check' );
3871 # Construct search and replace arrays
3872 wfProfileIn( $fname.'-construct' );
3873 $wgOutputReplace = array();
3874 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3875 $pdbk = $pdbks[$key];
3876 $searchkey = "<!--LINK $key-->";
3877 $title = $this->mLinkHolders
['titles'][$key];
3878 if ( empty( $colours[$pdbk] ) ) {
3879 $linkCache->addBadLinkObj( $title );
3880 $colours[$pdbk] = 0;
3881 $this->mOutput
->addLink( $title, 0 );
3882 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3883 $this->mLinkHolders
['texts'][$key],
3884 $this->mLinkHolders
['queries'][$key] );
3885 } elseif ( $colours[$pdbk] == 1 ) {
3886 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3887 $this->mLinkHolders
['texts'][$key],
3888 $this->mLinkHolders
['queries'][$key] );
3889 } elseif ( $colours[$pdbk] == 2 ) {
3890 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3891 $this->mLinkHolders
['texts'][$key],
3892 $this->mLinkHolders
['queries'][$key] );
3895 wfProfileOut( $fname.'-construct' );
3898 wfProfileIn( $fname.'-replace' );
3900 $text = preg_replace_callback(
3901 '/(<!--LINK .*?-->)/',
3902 "wfOutputReplaceMatches",
3905 wfProfileOut( $fname.'-replace' );
3908 # Now process interwiki link holders
3909 # This is quite a bit simpler than internal links
3910 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3911 wfProfileIn( $fname.'-interwiki' );
3912 # Make interwiki link HTML
3913 $wgOutputReplace = array();
3914 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3915 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3916 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3919 $text = preg_replace_callback(
3920 '/<!--IWLINK (.*?)-->/',
3921 "wfOutputReplaceMatches",
3923 wfProfileOut( $fname.'-interwiki' );
3926 wfProfileOut( $fname );
3931 * Replace <!--LINK--> link placeholders with plain text of links
3932 * (not HTML-formatted).
3933 * @param string $text
3936 function replaceLinkHoldersText( $text ) {
3937 $fname = 'Parser::replaceLinkHoldersText';
3938 wfProfileIn( $fname );
3940 $text = preg_replace_callback(
3941 '/<!--(LINK|IWLINK) (.*?)-->/',
3942 array( &$this, 'replaceLinkHoldersTextCallback' ),
3945 wfProfileOut( $fname );
3950 * @param array $matches
3954 function replaceLinkHoldersTextCallback( $matches ) {
3955 $type = $matches[1];
3957 if( $type == 'LINK' ) {
3958 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
3959 return $this->mLinkHolders
['texts'][$key];
3961 } elseif( $type == 'IWLINK' ) {
3962 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
3963 return $this->mInterwikiLinkHolders
['texts'][$key];
3970 * Tag hook handler for 'pre'.
3972 function renderPreTag( $text, $attribs, $parser ) {
3973 // Backwards-compatibility hack
3974 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
3976 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
3977 return wfOpenElement( 'pre', $attribs ) .
3978 wfEscapeHTMLTagsOnly( $content ) .
3983 * Renders an image gallery from a text with one line per image.
3984 * text labels may be given by using |-style alternative text. E.g.
3985 * Image:one.jpg|The number "1"
3986 * Image:tree.jpg|A tree
3987 * given as text will return the HTML of a gallery with two images,
3988 * labeled 'The number "1"' and
3991 function renderImageGallery( $text, $params ) {
3992 $ig = new ImageGallery();
3993 $ig->setShowBytes( false );
3994 $ig->setShowFilename( false );
3996 $ig->useSkin( $this->mOptions
->getSkin() );
3998 if( isset( $params['caption'] ) )
3999 $ig->setCaption( $params['caption'] );
4001 $lines = explode( "\n", $text );
4002 foreach ( $lines as $line ) {
4003 # match lines like these:
4004 # Image:someimage.jpg|This is some image
4005 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4007 if ( count( $matches ) == 0 ) {
4010 $tp = Title
::newFromText( $matches[1] );
4012 if( is_null( $nt ) ) {
4013 # Bogus title. Ignore these so we don't bomb out later.
4016 if ( isset( $matches[3] ) ) {
4017 $label = $matches[3];
4022 $pout = $this->parse( $label,
4025 false, // Strip whitespace...?
4026 false // Don't clear state!
4028 $html = $pout->getText();
4030 $ig->add( new Image( $nt ), $html );
4032 # Only add real images (bug #5586)
4033 if ( $nt->getNamespace() == NS_IMAGE
) {
4034 $this->mOutput
->addImage( $nt->getDBkey() );
4037 return $ig->toHTML();
4041 * Parse image options text and use it to make an image
4043 function makeImage( &$nt, $options ) {
4044 global $wgUseImageResize;
4048 # Check if the options text is of the form "options|alt text"
4050 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4051 # * left no resizing, just left align. label is used for alt= only
4052 # * right same, but right aligned
4053 # * none same, but not aligned
4054 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4055 # * center center the image
4056 # * framed Keep original image size, no magnify-button.
4058 $part = explode( '|', $options);
4060 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4061 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4062 $mwLeft =& MagicWord
::get( 'img_left' );
4063 $mwRight =& MagicWord
::get( 'img_right' );
4064 $mwNone =& MagicWord
::get( 'img_none' );
4065 $mwWidth =& MagicWord
::get( 'img_width' );
4066 $mwCenter =& MagicWord
::get( 'img_center' );
4067 $mwFramed =& MagicWord
::get( 'img_framed' );
4070 $width = $height = $framed = $thumb = false;
4071 $manual_thumb = '' ;
4073 foreach( $part as $key => $val ) {
4074 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4076 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4077 # use manually specified thumbnail
4079 $manual_thumb = $match;
4080 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4081 # remember to set an alignment, don't render immediately
4083 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4084 # remember to set an alignment, don't render immediately
4086 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4087 # remember to set an alignment, don't render immediately
4089 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4090 # remember to set an alignment, don't render immediately
4092 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4093 wfDebug( "img_width match: $match\n" );
4094 # $match is the image width in pixels
4095 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4096 $width = intval( $m[1] );
4097 $height = intval( $m[2] );
4099 $width = intval($match);
4101 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4107 # Strip bad stuff out of the alt text
4108 $alt = $this->replaceLinkHoldersText( $caption );
4110 # make sure there are no placeholders in thumbnail attributes
4111 # that are later expanded to html- so expand them now and
4113 $alt = $this->unstrip($alt, $this->mStripState
);
4114 $alt = Sanitizer
::stripAllTags( $alt );
4116 # Linker does the rest
4117 $sk =& $this->mOptions
->getSkin();
4118 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4122 * Set a flag in the output object indicating that the content is dynamic and
4123 * shouldn't be cached.
4125 function disableCache() {
4126 wfDebug( "Parser output marked as uncacheable.\n" );
4127 $this->mOutput
->mCacheTime
= -1;
4131 * Callback from the Sanitizer for expanding items found in HTML attribute
4132 * values, so they can be safely tested and escaped.
4133 * @param string $text
4134 * @param array $args
4138 function attributeStripCallback( &$text, $args ) {
4139 $text = $this->replaceVariables( $text, $args );
4140 $text = $this->unstripForHTML( $text );
4144 function unstripForHTML( $text ) {
4145 $text = $this->unstrip( $text, $this->mStripState
);
4146 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4154 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4155 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4156 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4162 function getTags() { return array_keys( $this->mTagHooks
); }
4167 * Break wikitext input into sections, and either pull or replace
4168 * some particular section's text.
4170 * External callers should use the getSection and replaceSection methods.
4172 * @param $text Page wikitext
4173 * @param $section Numbered section. 0 pulls the text before the first
4174 * heading; other numbers will pull the given section
4175 * along with its lower-level subsections.
4176 * @param $mode One of "get" or "replace"
4177 * @param $newtext Replacement text for section data.
4178 * @return string for "get", the extracted section text.
4179 * for "replace", the whole page with the section replaced.
4181 private function extractSections( $text, $section, $mode, $newtext='' ) {
4182 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4183 # comments to be stripped as well)
4184 $striparray = array();
4186 $oldOutputType = $this->mOutputType
;
4187 $oldOptions = $this->mOptions
;
4188 $this->mOptions
= new ParserOptions();
4189 $this->mOutputType
= OT_WIKI
;
4191 $striptext = $this->strip( $text, $striparray, true );
4193 $this->mOutputType
= $oldOutputType;
4194 $this->mOptions
= $oldOptions;
4196 # now that we can be sure that no pseudo-sections are in the source,
4197 # split it up by section
4198 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4199 $comment = "(?:$uniq-!--.*?QINU)";
4204 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4206 (=+) # Should this be limited to 6?
4207 .+? # Section title...
4208 \\2 # Ending = count must match start
4215 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4222 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4223 (=+) # Should this be limited to 6?
4224 .+? # Section title...
4225 \\2 # Ending = count must match start
4226 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4235 PREG_SPLIT_DELIM_CAPTURE
);
4237 if( $mode == "get" ) {
4238 if( $section == 0 ) {
4239 // "Section 0" returns the content before any other section.
4244 } elseif( $mode == "replace" ) {
4245 if( $section == 0 ) {
4246 $rv = $newtext . "\n\n";
4255 for( $index = 1; $index < count( $secs ); ) {
4256 $headerLine = $secs[$index++
];
4257 if( $secs[$index] ) {
4259 $headerLevel = strlen( $secs[$index++
] );
4263 $headerLevel = intval( $secs[$index++
] );
4265 $content = $secs[$index++
];
4268 if( $mode == "get" ) {
4269 if( $count == $section ) {
4270 $rv = $headerLine . $content;
4271 $sectionLevel = $headerLevel;
4272 } elseif( $count > $section ) {
4273 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4274 $rv .= $headerLine . $content;
4276 // Broke out to a higher-level section
4280 } elseif( $mode == "replace" ) {
4281 if( $count < $section ) {
4282 $rv .= $headerLine . $content;
4283 } elseif( $count == $section ) {
4284 $rv .= $newtext . "\n\n";
4285 $sectionLevel = $headerLevel;
4286 } elseif( $count > $section ) {
4287 if( $headerLevel <= $sectionLevel ) {
4288 // Passed the section's sub-parts.
4292 $rv .= $headerLine . $content;
4297 # reinsert stripped tags
4298 $rv = $this->unstrip( $rv, $striparray );
4299 $rv = $this->unstripNoWiki( $rv, $striparray );
4305 * This function returns the text of a section, specified by a number ($section).
4306 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4307 * the first section before any such heading (section 0).
4309 * If a section contains subsections, these are also returned.
4311 * @param $text String: text to look in
4312 * @param $section Integer: section number
4313 * @return string text of the requested section
4315 function getSection( $text, $section ) {
4316 return $this->extractSections( $text, $section, "get" );
4319 function replaceSection( $oldtext, $section, $text ) {
4320 return $this->extractSections( $oldtext, $section, "replace", $text );
4327 * @package MediaWiki
4331 var $mText, # The output text
4332 $mLanguageLinks, # List of the full text of language links, in the order they appear
4333 $mCategories, # Map of category names to sort keys
4334 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4335 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4336 $mVersion, # Compatibility check
4337 $mTitleText, # title text of the chosen language variant
4338 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4339 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4340 $mImages, # DB keys of the images used, in the array key only
4341 $mExternalLinks, # External link URLs, in the key only
4342 $mHTMLtitle, # Display HTML title
4343 $mSubtitle, # Additional subtitle
4344 $mNewSection, # Show a new section link?
4345 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4347 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4348 $containsOldMagic = false, $titletext = '' )
4350 $this->mText
= $text;
4351 $this->mLanguageLinks
= $languageLinks;
4352 $this->mCategories
= $categoryLinks;
4353 $this->mContainsOldMagic
= $containsOldMagic;
4354 $this->mCacheTime
= '';
4355 $this->mVersion
= MW_PARSER_VERSION
;
4356 $this->mTitleText
= $titletext;
4357 $this->mLinks
= array();
4358 $this->mTemplates
= array();
4359 $this->mImages
= array();
4360 $this->mExternalLinks
= array();
4361 $this->mHTMLtitle
= "" ;
4362 $this->mSubtitle
= "" ;
4363 $this->mNewSection
= false;
4364 $this->mNoGallery
= false;
4367 function getText() { return $this->mText
; }
4368 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4369 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4370 function &getCategories() { return $this->mCategories
; }
4371 function getCacheTime() { return $this->mCacheTime
; }
4372 function getTitleText() { return $this->mTitleText
; }
4373 function &getLinks() { return $this->mLinks
; }
4374 function &getTemplates() { return $this->mTemplates
; }
4375 function &getImages() { return $this->mImages
; }
4376 function &getExternalLinks() { return $this->mExternalLinks
; }
4377 function getNoGallery() { return $this->mNoGallery
; }
4378 function getSubtitle() { return $this->mSubtitle
; }
4380 function containsOldMagic() { return $this->mContainsOldMagic
; }
4381 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4382 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4383 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4384 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4385 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4386 function setTitleText( $t ) { return wfSetVar($this->mTitleText
, $t); }
4387 function setSubtitle( $st ) { return wfSetVar( $this->mSubtitle
, $st ); }
4389 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4390 function addImage( $name ) { $this->mImages
[$name] = 1; }
4391 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4392 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4394 function setNewSection( $value ) {
4395 $this->mNewSection
= (bool)$value;
4397 function getNewSection() {
4398 return (bool)$this->mNewSection
;
4401 function addLink( $title, $id ) {
4402 $ns = $title->getNamespace();
4403 $dbk = $title->getDBkey();
4404 if ( !isset( $this->mLinks
[$ns] ) ) {
4405 $this->mLinks
[$ns] = array();
4407 $this->mLinks
[$ns][$dbk] = $id;
4410 function addTemplate( $title, $id ) {
4411 $ns = $title->getNamespace();
4412 $dbk = $title->getDBkey();
4413 if ( !isset( $this->mTemplates
[$ns] ) ) {
4414 $this->mTemplates
[$ns] = array();
4416 $this->mTemplates
[$ns][$dbk] = $id;
4420 * Return true if this cached output object predates the global or
4421 * per-article cache invalidation timestamps, or if it comes from
4422 * an incompatible older version.
4424 * @param string $touched the affected article's last touched timestamp
4428 function expired( $touched ) {
4429 global $wgCacheEpoch;
4430 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4431 $this->getCacheTime() < $touched ||
4432 $this->getCacheTime() <= $wgCacheEpoch ||
4433 !isset( $this->mVersion
) ||
4434 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4439 * Set options of the Parser
4441 * @package MediaWiki
4445 # All variables are private
4446 var $mUseTeX; # Use texvc to expand <math> tags
4447 var $mUseDynamicDates; # Use DateFormatter to format dates
4448 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4449 var $mAllowExternalImages; # Allow external images inline
4450 var $mAllowExternalImagesFrom; # If not, any exception?
4451 var $mSkin; # Reference to the preferred skin
4452 var $mDateFormat; # Date format index
4453 var $mEditSection; # Create "edit section" links
4454 var $mNumberHeadings; # Automatically number headings
4455 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4456 var $mTidy; # Ask for tidy cleanup
4457 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4459 var $mUser; # Stored user object, just used to initialise the skin
4461 function getUseTeX() { return $this->mUseTeX
; }
4462 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4463 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4464 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4465 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4466 function getEditSection() { return $this->mEditSection
; }
4467 function getNumberHeadings() { return $this->mNumberHeadings
; }
4468 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4469 function getTidy() { return $this->mTidy
; }
4470 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4472 function &getSkin() {
4473 if ( !isset( $this->mSkin
) ) {
4474 $this->mSkin
= $this->mUser
->getSkin();
4476 return $this->mSkin
;
4479 function getDateFormat() {
4480 if ( !isset( $this->mDateFormat
) ) {
4481 $this->mDateFormat
= $this->mUser
->getDatePreference();
4483 return $this->mDateFormat
;
4486 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4487 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4488 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4489 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4490 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4491 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4492 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4493 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4494 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4495 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4496 function setSkin( &$x ) { $this->mSkin
=& $x; }
4497 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4499 function ParserOptions( $user = null ) {
4500 $this->initialiseFromUser( $user );
4504 * Get parser options
4507 static function newFromUser( $user ) {
4508 return new ParserOptions( $user );
4511 /** Get user options */
4512 function initialiseFromUser( $userInput ) {
4513 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4514 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4515 $fname = 'ParserOptions::initialiseFromUser';
4516 wfProfileIn( $fname );
4517 if ( !$userInput ) {
4519 if ( isset( $wgUser ) ) {
4523 $user->setLoaded( true );
4526 $user =& $userInput;
4529 $this->mUser
= $user;
4531 $this->mUseTeX
= $wgUseTeX;
4532 $this->mUseDynamicDates
= $wgUseDynamicDates;
4533 $this->mInterwikiMagic
= $wgInterwikiMagic;
4534 $this->mAllowExternalImages
= $wgAllowExternalImages;
4535 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4536 $this->mSkin
= null; # Deferred
4537 $this->mDateFormat
= null; # Deferred
4538 $this->mEditSection
= true;
4539 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4540 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4541 $this->mTidy
= false;
4542 $this->mInterfaceMessage
= false;
4543 wfProfileOut( $fname );
4548 * Callback function used by Parser::replaceLinkHolders()
4549 * to substitute link placeholders.
4551 function &wfOutputReplaceMatches( $matches ) {
4552 global $wgOutputReplace;
4553 return $wgOutputReplace[$matches[1]];
4557 * Return the total number of articles
4559 function wfNumberOfArticles() {
4560 global $wgNumberOfArticles;
4563 return $wgNumberOfArticles;
4567 * Return the number of files
4569 function wfNumberOfFiles() {
4570 $fname = 'wfNumberOfFiles';
4572 wfProfileIn( $fname );
4573 $dbr =& wfGetDB( DB_SLAVE
);
4574 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4575 wfProfileOut( $fname );
4581 * Return the number of user accounts
4584 function wfNumberOfUsers() {
4585 wfProfileIn( 'wfNumberOfUsers' );
4586 $dbr =& wfGetDB( DB_SLAVE
);
4587 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4588 wfProfileOut( 'wfNumberOfUsers' );
4593 * Return the total number of pages
4596 function wfNumberOfPages() {
4597 wfProfileIn( 'wfNumberOfPages' );
4598 $dbr =& wfGetDB( DB_SLAVE
);
4599 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4600 wfProfileOut( 'wfNumberOfPages' );
4605 * Return the total number of admins
4609 function wfNumberOfAdmins() {
4610 static $admins = -1;
4611 wfProfileIn( 'wfNumberOfAdmins' );
4612 if( $admins == -1 ) {
4613 $dbr =& wfGetDB( DB_SLAVE
);
4614 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4616 wfProfileOut( 'wfNumberOfAdmins' );
4617 return (int)$admins;
4621 * Count the number of pages in a particular namespace
4623 * @param $ns Namespace
4626 function wfPagesInNs( $ns ) {
4627 static $pageCount = array();
4628 wfProfileIn( 'wfPagesInNs' );
4629 if( !isset( $pageCount[$ns] ) ) {
4630 $dbr =& wfGetDB( DB_SLAVE
);
4631 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4633 wfProfileOut( 'wfPagesInNs' );
4634 return (int)$pageCount[$ns];
4638 * Get various statistics from the database
4641 function wfLoadSiteStats() {
4642 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4643 $fname = 'wfLoadSiteStats';
4645 if ( -1 != $wgNumberOfArticles ) return;
4646 $dbr =& wfGetDB( DB_SLAVE
);
4647 $s = $dbr->selectRow( 'site_stats',
4648 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4649 array( 'ss_row_id' => 1 ), $fname
4652 if ( $s === false ) {
4655 $wgTotalViews = $s->ss_total_views
;
4656 $wgTotalEdits = $s->ss_total_edits
;
4657 $wgNumberOfArticles = $s->ss_good_articles
;
4663 * Basically replacing " > and < with HTML entities ( ", >, <)
4665 * @param $in String: text that might contain HTML tags.
4666 * @return string Escaped string
4668 function wfEscapeHTMLTagsOnly( $in ) {
4670 array( '"', '>', '<' ),
4671 array( '"', '>', '<' ),