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 if ( $this->mFirstCall
) {
191 $this->firstCallInit();
193 $this->mOutput
= new ParserOutput
;
194 $this->mAutonumber
= 0;
195 $this->mLastSection
= '';
196 $this->mDTopen
= false;
197 $this->mIncludeCount
= array();
198 $this->mStripState
= array();
199 $this->mArgStack
= array();
200 $this->mInPre
= false;
201 $this->mInterwikiLinkHolders
= array(
205 $this->mLinkHolders
= array(
206 'namespaces' => array(),
208 'queries' => array(),
212 $this->mRevisionId
= null;
215 * Prefix for temporary replacement strings for the multipass parser.
216 * \x07 should never appear in input as it's disallowed in XML.
217 * Using it at the front also gives us a little extra robustness
218 * since it shouldn't match when butted up against identifier-like
221 $this->mUniqPrefix
= "\x07UNIQ" . Parser
::getRandomString();
223 # Clear these on every parse, bug 4549
224 $this->mTemplates
= array();
225 $this->mTemplatePath
= array();
227 $this->mShowToc
= true;
228 $this->mForceTocPosition
= false;
230 wfRunHooks( 'ParserClearState', array( &$this ) );
234 * Accessor for mUniqPrefix.
238 function UniqPrefix() {
239 return $this->mUniqPrefix
;
243 * Convert wikitext to HTML
244 * Do not call this function recursively.
247 * @param string $text Text we want to parse
248 * @param Title &$title A title object
249 * @param array $options
250 * @param boolean $linestart
251 * @param boolean $clearState
252 * @param int $revid number to pass in {{REVISIONID}}
253 * @return ParserOutput a ParserOutput
255 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
257 * First pass--just handle <nowiki> sections, pass the rest off
258 * to internalParse() which does all the real work.
261 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
262 $fname = 'Parser::parse';
263 wfProfileIn( $fname );
269 $this->mOptions
= $options;
270 $this->mTitle
=& $title;
271 $oldRevisionId = $this->mRevisionId
;
272 if( $revid !== null ) {
273 $this->mRevisionId
= $revid;
275 $this->mOutputType
= OT_HTML
;
277 //$text = $this->strip( $text, $this->mStripState );
278 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
279 $x =& $this->mStripState
;
281 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
282 $text = $this->strip( $text, $x );
283 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
285 # Hook to suspend the parser in this state
286 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
287 wfProfileOut( $fname );
291 $text = $this->internalParse( $text );
293 $text = $this->unstrip( $text, $this->mStripState
);
295 # Clean up special characters, only run once, next-to-last before doBlockLevels
297 # french spaces, last one Guillemet-left
298 # only if there is something before the space
299 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1 \\2',
300 # french spaces, Guillemet-right
301 '/(\\302\\253) /' => '\\1 ',
303 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
306 $text = $this->doBlockLevels( $text, $linestart );
308 $this->replaceLinkHolders( $text );
310 # the position of the parserConvert() call should not be changed. it
311 # assumes that the links are all replaced and the only thing left
312 # is the <nowiki> mark.
313 # Side-effects: this calls $this->mOutput->setTitleText()
314 $text = $wgContLang->parserConvert( $text, $this );
316 $text = $this->unstripNoWiki( $text, $this->mStripState
);
318 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
320 $text = Sanitizer
::normalizeCharReferences( $text );
322 if (($wgUseTidy and $this->mOptions
->mTidy
) or $wgAlwaysUseTidy) {
323 $text = Parser
::tidy($text);
325 # attempt to sanitize at least some nesting problems
326 # (bug #2702 and quite a few others)
328 # ''Something [http://www.cool.com cool''] -->
329 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
330 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
331 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
332 # fix up an anchor inside another anchor, only
333 # at least for a single single nested link (bug 3695)
334 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
335 '\\1\\2</a>\\3</a>\\1\\4</a>',
336 # fix div inside inline elements- doBlockLevels won't wrap a line which
337 # contains a div, so fix it up here; replace
338 # div with escaped text
339 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
340 '\\1\\3<div\\5>\\6</div>\\8\\9',
341 # remove empty italic or bold tag pairs, some
342 # introduced by rules above
343 '/<([bi])><\/\\1>/' => '',
346 $text = preg_replace(
347 array_keys( $tidyregs ),
348 array_values( $tidyregs ),
352 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
354 $this->mOutput
->setText( $text );
355 $this->mRevisionId
= $oldRevisionId;
356 wfProfileOut( $fname );
358 return $this->mOutput
;
362 * Get a random string
367 function getRandomString() {
368 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
371 function &getTitle() { return $this->mTitle
; }
372 function getOptions() { return $this->mOptions
; }
374 function getFunctionLang() {
375 global $wgLang, $wgContLang;
376 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
380 * Replaces all occurrences of HTML-style comments and the given tags
381 * in the text with a random marker and returns teh next text. The output
382 * parameter $matches will be an associative array filled with data in
384 * 'UNIQ-xxxxx' => array(
387 * array( 'param' => 'x' ),
388 * '<element param="x">tag content</element>' ) )
390 * @param $elements list of element names. Comments are always extracted.
391 * @param $text Source text string.
392 * @param $uniq_prefix
397 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
398 $rand = Parser
::getRandomString();
403 $taglist = implode( '|', $elements );
404 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
406 while ( '' != $text ) {
407 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
409 if( count( $p ) < 5 ) {
412 if( count( $p ) > 5 ) {
426 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++
) . '-QINU';
427 $stripped .= $marker;
429 if ( $close === '/>' ) {
430 // Empty element tag, <tag />
435 if( $element == '!--' ) {
438 $end = "/(<\\/$element\\s*>)/i";
440 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
442 if( count( $q ) < 3 ) {
443 # No end tag -- let it run out to the end of the text.
452 $matches[$marker] = array( $element,
454 Sanitizer
::decodeTagAttributes( $attributes ),
455 "<$element$attributes$close$content$tail" );
461 * Strips and renders nowiki, pre, math, hiero
462 * If $render is set, performs necessary rendering operations on plugins
463 * Returns the text, and fills an array with data needed in unstrip()
464 * If the $state is already a valid strip state, it adds to the state
466 * @param bool $stripcomments when set, HTML comments <!-- like this -->
467 * will be stripped in addition to other tags. This is important
468 * for section editing, where these comments cause confusion when
469 * counting the sections in the wikisource
471 * @param array dontstrip contains tags which should not be stripped;
472 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
476 function strip( $text, &$state, $stripcomments = false , $dontstrip = array () ) {
477 $render = ($this->mOutputType
== OT_HTML
);
479 # Replace any instances of the placeholders
480 $uniq_prefix = $this->mUniqPrefix
;
481 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
482 $commentState = array();
484 $elements = array_merge(
485 array( 'nowiki', 'gallery' ),
486 array_keys( $this->mTagHooks
) );
489 $elements[] = 'html';
491 if( $this->mOptions
->getUseTeX() ) {
492 $elements[] = 'math';
495 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
496 foreach ( $elements AS $k => $v ) {
497 if ( !in_array ( $v , $dontstrip ) ) continue;
498 unset ( $elements[$k] );
502 $text = Parser
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
504 foreach( $matches as $marker => $data ) {
505 list( $element, $content, $params, $tag ) = $data;
507 $tagName = strtolower( $element );
511 if( substr( $tag, -3 ) == '-->' ) {
514 // Unclosed comment in input.
515 // Close it so later stripping can remove it
524 // Shouldn't happen otherwise. :)
526 $output = wfEscapeHTMLTagsOnly( $content );
529 $output = MathRenderer
::renderMath( $content );
532 $output = $this->renderImageGallery( $content, $params );
535 if( isset( $this->mTagHooks
[$tagName] ) ) {
536 $output = call_user_func_array( $this->mTagHooks
[$tagName],
537 array( $content, $params, $this ) );
539 throw new MWException( "Invalid call hook $element" );
543 // Just stripping tags; keep the source
546 if( !$stripcomments && $element == '!--' ) {
547 $commentState[$marker] = $output;
549 $state[$element][$marker] = $output;
553 # Unstrip comments unless explicitly told otherwise.
554 # (The comments are always stripped prior to this point, so as to
555 # not invoke any extension tags / parser hooks contained within
557 if ( !$stripcomments ) {
558 // Put them all back and forget them
559 $text = strtr( $text, $commentState );
566 * Restores pre, math, and other extensions removed by strip()
568 * always call unstripNoWiki() after this one
571 function unstrip( $text, &$state ) {
572 if ( !is_array( $state ) ) {
576 $replacements = array();
577 foreach( $state as $tag => $contentDict ) {
578 if( $tag != 'nowiki' && $tag != 'html' ) {
579 foreach( $contentDict as $uniq => $content ) {
580 $replacements[$uniq] = $content;
584 $text = strtr( $text, $replacements );
590 * Always call this after unstrip() to preserve the order
594 function unstripNoWiki( $text, &$state ) {
595 if ( !is_array( $state ) ) {
599 $replacements = array();
600 foreach( $state as $tag => $contentDict ) {
601 if( $tag == 'nowiki' ||
$tag == 'html' ) {
602 foreach( $contentDict as $uniq => $content ) {
603 $replacements[$uniq] = $content;
607 $text = strtr( $text, $replacements );
613 * Add an item to the strip state
614 * Returns the unique tag which must be inserted into the stripped text
615 * The tag will be replaced with the original text in unstrip()
619 function insertStripItem( $text, &$state ) {
620 $rnd = $this->mUniqPrefix
. '-item' . Parser
::getRandomString();
624 $state['item'][$rnd] = $text;
629 * Interface with html tidy, used if $wgUseTidy = true.
630 * If tidy isn't able to correct the markup, the original will be
631 * returned in all its glory with a warning comment appended.
633 * Either the external tidy program or the in-process tidy extension
634 * will be used depending on availability. Override the default
635 * $wgTidyInternal setting to disable the internal if it's not working.
637 * @param string $text Hideous HTML input
638 * @return string Corrected HTML output
642 function tidy( $text ) {
643 global $wgTidyInternal;
644 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
645 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
646 '<head><title>test</title></head><body>'.$text.'</body></html>';
647 if( $wgTidyInternal ) {
648 $correctedtext = Parser
::internalTidy( $wrappedtext );
650 $correctedtext = Parser
::externalTidy( $wrappedtext );
652 if( is_null( $correctedtext ) ) {
653 wfDebug( "Tidy error detected!\n" );
654 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
656 return $correctedtext;
660 * Spawn an external HTML tidy process and get corrected markup back from it.
665 function externalTidy( $text ) {
666 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
667 $fname = 'Parser::externalTidy';
668 wfProfileIn( $fname );
673 $descriptorspec = array(
674 0 => array('pipe', 'r'),
675 1 => array('pipe', 'w'),
676 2 => array('file', '/dev/null', 'a')
679 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
680 if (is_resource($process)) {
681 // Theoretically, this style of communication could cause a deadlock
682 // here. If the stdout buffer fills up, then writes to stdin could
683 // block. This doesn't appear to happen with tidy, because tidy only
684 // writes to stdout after it's finished reading from stdin. Search
685 // for tidyParseStdin and tidySaveStdout in console/tidy.c
686 fwrite($pipes[0], $text);
688 while (!feof($pipes[1])) {
689 $cleansource .= fgets($pipes[1], 1024);
692 proc_close($process);
695 wfProfileOut( $fname );
697 if( $cleansource == '' && $text != '') {
698 // Some kind of error happened, so we couldn't get the corrected text.
699 // Just give up; we'll use the source text and append a warning.
707 * Use the HTML tidy PECL extension to use the tidy library in-process,
708 * saving the overhead of spawning a new process. Currently written to
709 * the PHP 4.3.x version of the extension, may not work on PHP 5.
711 * 'pear install tidy' should be able to compile the extension module.
716 function internalTidy( $text ) {
718 $fname = 'Parser::internalTidy';
719 wfProfileIn( $fname );
721 tidy_load_config( $wgTidyConf );
722 tidy_set_encoding( 'utf8' );
723 tidy_parse_string( $text );
725 if( tidy_get_status() == 2 ) {
726 // 2 is magic number for fatal error
727 // http://www.php.net/manual/en/function.tidy-get-status.php
730 $cleansource = tidy_get_output();
732 wfProfileOut( $fname );
737 * parse the wiki syntax used to render tables
741 function doTableStuff ( $t ) {
742 $fname = 'Parser::doTableStuff';
743 wfProfileIn( $fname );
745 $t = explode ( "\n" , $t ) ;
746 $td = array () ; # Is currently a td tag open?
747 $ltd = array () ; # Was it TD or TH?
748 $tr = array () ; # Is currently a tr tag open?
749 $ltr = array () ; # tr attributes
750 $has_opened_tr = array(); # Did this table open a <tr> element?
751 $indent_level = 0; # indent level of the table
752 foreach ( $t AS $k => $x )
755 $fc = substr ( $x , 0 , 1 ) ;
756 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
757 $indent_level = strlen( $matches[1] );
759 $attributes = $this->unstripForHTML( $matches[2] );
761 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
762 '<table' . Sanitizer
::fixTagAttributes ( $attributes, 'table' ) . '>' ;
763 array_push ( $td , false ) ;
764 array_push ( $ltd , '' ) ;
765 array_push ( $tr , false ) ;
766 array_push ( $ltr , '' ) ;
767 array_push ( $has_opened_tr, false );
769 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
770 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
771 $z = "</table>" . substr ( $x , 2);
772 $l = array_pop ( $ltd ) ;
773 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
774 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
775 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
777 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
779 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
780 $x = substr ( $x , 1 ) ;
781 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
783 $l = array_pop ( $ltd ) ;
784 array_pop ( $has_opened_tr );
785 array_push ( $has_opened_tr , true ) ;
786 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
787 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
790 array_push ( $tr , false ) ;
791 array_push ( $td , false ) ;
792 array_push ( $ltd , '' ) ;
793 $attributes = $this->unstripForHTML( $x );
794 array_push ( $ltr , Sanitizer
::fixTagAttributes ( $attributes, 'tr' ) ) ;
796 else if ( '|' == $fc ||
'!' == $fc ||
'|+' == substr ( $x , 0 , 2 ) ) { # Caption
798 if ( '|+' == substr ( $x , 0 , 2 ) ) {
800 $x = substr ( $x , 1 ) ;
802 $after = substr ( $x , 1 ) ;
803 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
805 // Split up multiple cells on the same line.
806 // FIXME: This can result in improper nesting of tags processed
807 // by earlier parser steps, but should avoid splitting up eg
808 // attribute values containing literal "||".
809 $after = wfExplodeMarkup( '||', $after );
813 # Loop through each table cell
814 foreach ( $after AS $theline )
819 $tra = array_pop ( $ltr ) ;
820 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
821 array_push ( $tr , true ) ;
822 array_push ( $ltr , '' ) ;
823 array_pop ( $has_opened_tr );
824 array_push ( $has_opened_tr , true ) ;
827 $l = array_pop ( $ltd ) ;
828 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
829 if ( $fc == '|' ) $l = 'td' ;
830 else if ( $fc == '!' ) $l = 'th' ;
831 else if ( $fc == '+' ) $l = 'caption' ;
833 array_push ( $ltd , $l ) ;
836 $y = explode ( '|' , $theline , 2 ) ;
837 # Note that a '|' inside an invalid link should not
838 # be mistaken as delimiting cell parameters
839 if ( strpos( $y[0], '[[' ) !== false ) {
840 $y = array ($theline);
842 if ( count ( $y ) == 1 )
843 $y = "{$z}<{$l}>{$y[0]}" ;
845 $attributes = $this->unstripForHTML( $y[0] );
846 $y = "{$z}<{$l}".Sanitizer
::fixTagAttributes($attributes, $l).">{$y[1]}" ;
849 array_push ( $td , true ) ;
854 # Closing open td, tr && table
855 while ( count ( $td ) > 0 )
857 $l = array_pop ( $ltd ) ;
858 if ( array_pop ( $td ) ) $t[] = '</td>' ;
859 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
860 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
864 $t = implode ( "\n" , $t ) ;
865 # special case: don't return empty table
866 if($t == "<table>\n<tr><td></td></tr>\n</table>")
868 wfProfileOut( $fname );
873 * Helper function for parse() that transforms wiki markup into
874 * HTML. Only called for $mOutputType == OT_HTML.
878 function internalParse( $text ) {
881 $fname = 'Parser::internalParse';
882 wfProfileIn( $fname );
884 # Remove <noinclude> tags and <includeonly> sections
885 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
886 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
887 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
889 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
891 $text = $this->replaceVariables( $text, $args );
893 // Tables need to come after variable replacement for things to work
894 // properly; putting them before other transformations should keep
895 // exciting things like link expansions from showing up in surprising
897 $text = $this->doTableStuff( $text );
899 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
901 $text = $this->stripToc( $text );
902 $this->stripNoGallery( $text );
903 $text = $this->doHeadings( $text );
904 if($this->mOptions
->getUseDynamicDates()) {
905 $df =& DateFormatter
::getInstance();
906 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
908 $text = $this->doAllQuotes( $text );
909 $text = $this->replaceInternalLinks( $text );
910 $text = $this->replaceExternalLinks( $text );
912 # replaceInternalLinks may sometimes leave behind
913 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
914 $text = str_replace($this->mUniqPrefix
."NOPARSE", "", $text);
916 $text = $this->doMagicLinks( $text );
917 $text = $this->formatHeadings( $text, $isMain );
919 wfProfileOut( $fname );
924 * Replace special strings like "ISBN xxx" and "RFC xxx" with
925 * magic external links.
929 function &doMagicLinks( &$text ) {
930 $text = $this->magicISBN( $text );
931 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
932 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
937 * Parse headers and return html
941 function doHeadings( $text ) {
942 $fname = 'Parser::doHeadings';
943 wfProfileIn( $fname );
944 for ( $i = 6; $i >= 1; --$i ) {
945 $h = str_repeat( '=', $i );
946 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
947 "<h{$i}>\\1</h{$i}>\\2", $text );
949 wfProfileOut( $fname );
954 * Replace single quotes with HTML markup
956 * @return string the altered text
958 function doAllQuotes( $text ) {
959 $fname = 'Parser::doAllQuotes';
960 wfProfileIn( $fname );
962 $lines = explode( "\n", $text );
963 foreach ( $lines as $line ) {
964 $outtext .= $this->doQuotes ( $line ) . "\n";
966 $outtext = substr($outtext, 0,-1);
967 wfProfileOut( $fname );
972 * Helper function for doAllQuotes()
975 function doQuotes( $text ) {
976 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
977 if ( count( $arr ) == 1 )
981 # First, do some preliminary work. This may shift some apostrophes from
982 # being mark-up to being text. It also counts the number of occurrences
983 # of bold and italics mark-ups.
987 foreach ( $arr as $r )
989 if ( ( $i %
2 ) == 1 )
991 # If there are ever four apostrophes, assume the first is supposed to
992 # be text, and the remaining three constitute mark-up for bold text.
993 if ( strlen( $arr[$i] ) == 4 )
998 # If there are more than 5 apostrophes in a row, assume they're all
999 # text except for the last 5.
1000 else if ( strlen( $arr[$i] ) > 5 )
1002 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1005 # Count the number of occurrences of bold and italics mark-ups.
1006 # We are not counting sequences of five apostrophes.
1007 if ( strlen( $arr[$i] ) == 2 ) $numitalics++
; else
1008 if ( strlen( $arr[$i] ) == 3 ) $numbold++
; else
1009 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1014 # If there is an odd number of both bold and italics, it is likely
1015 # that one of the bold ones was meant to be an apostrophe followed
1016 # by italics. Which one we cannot know for certain, but it is more
1017 # likely to be one that has a single-letter word before it.
1018 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1021 $firstsingleletterword = -1;
1022 $firstmultiletterword = -1;
1024 foreach ( $arr as $r )
1026 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1028 $x1 = substr ($arr[$i-1], -1);
1029 $x2 = substr ($arr[$i-1], -2, 1);
1031 if ($firstspace == -1) $firstspace = $i;
1032 } else if ($x2 == ' ') {
1033 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1035 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1041 # If there is a single-letter word, use it!
1042 if ($firstsingleletterword > -1)
1044 $arr [ $firstsingleletterword ] = "''";
1045 $arr [ $firstsingleletterword-1 ] .= "'";
1047 # If not, but there's a multi-letter word, use that one.
1048 else if ($firstmultiletterword > -1)
1050 $arr [ $firstmultiletterword ] = "''";
1051 $arr [ $firstmultiletterword-1 ] .= "'";
1053 # ... otherwise use the first one that has neither.
1054 # (notice that it is possible for all three to be -1 if, for example,
1055 # there is only one pentuple-apostrophe in the line)
1056 else if ($firstspace > -1)
1058 $arr [ $firstspace ] = "''";
1059 $arr [ $firstspace-1 ] .= "'";
1063 # Now let's actually convert our apostrophic mush to HTML!
1068 foreach ($arr as $r)
1072 if ($state == 'both')
1079 if (strlen ($r) == 2)
1082 { $output .= '</i>'; $state = ''; }
1083 else if ($state == 'bi')
1084 { $output .= '</i>'; $state = 'b'; }
1085 else if ($state == 'ib')
1086 { $output .= '</b></i><b>'; $state = 'b'; }
1087 else if ($state == 'both')
1088 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1089 else # $state can be 'b' or ''
1090 { $output .= '<i>'; $state .= 'i'; }
1092 else if (strlen ($r) == 3)
1095 { $output .= '</b>'; $state = ''; }
1096 else if ($state == 'bi')
1097 { $output .= '</i></b><i>'; $state = 'i'; }
1098 else if ($state == 'ib')
1099 { $output .= '</b>'; $state = 'i'; }
1100 else if ($state == 'both')
1101 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1102 else # $state can be 'i' or ''
1103 { $output .= '<b>'; $state .= 'b'; }
1105 else if (strlen ($r) == 5)
1108 { $output .= '</b><i>'; $state = 'i'; }
1109 else if ($state == 'i')
1110 { $output .= '</i><b>'; $state = 'b'; }
1111 else if ($state == 'bi')
1112 { $output .= '</i></b>'; $state = ''; }
1113 else if ($state == 'ib')
1114 { $output .= '</b></i>'; $state = ''; }
1115 else if ($state == 'both')
1116 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1117 else # ($state == '')
1118 { $buffer = ''; $state = 'both'; }
1123 # Now close all remaining tags. Notice that the order is important.
1124 if ($state == 'b' ||
$state == 'ib')
1126 if ($state == 'i' ||
$state == 'bi' ||
$state == 'ib')
1130 if ($state == 'both')
1131 $output .= '<b><i>'.$buffer.'</i></b>';
1137 * Replace external links
1139 * Note: this is all very hackish and the order of execution matters a lot.
1140 * Make sure to run maintenance/parserTests.php if you change this code.
1144 function replaceExternalLinks( $text ) {
1146 $fname = 'Parser::replaceExternalLinks';
1147 wfProfileIn( $fname );
1149 $sk =& $this->mOptions
->getSkin();
1151 $bits = preg_split( EXT_LINK_BRACKETED
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1153 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1156 while ( $i<count( $bits ) ) {
1158 $protocol = $bits[$i++
];
1159 $text = $bits[$i++
];
1160 $trail = $bits[$i++
];
1162 # The characters '<' and '>' (which were escaped by
1163 # removeHTMLtags()) should not be included in
1164 # URLs, per RFC 2396.
1165 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1166 $text = substr($url, $m2[0][1]) . ' ' . $text;
1167 $url = substr($url, 0, $m2[0][1]);
1170 # If the link text is an image URL, replace it with an <img> tag
1171 # This happened by accident in the original parser, but some people used it extensively
1172 $img = $this->maybeMakeExternalImage( $text );
1173 if ( $img !== false ) {
1179 # Set linktype for CSS - if URL==text, link is essentially free
1180 $linktype = ($text == $url) ?
'free' : 'text';
1182 # No link text, e.g. [http://domain.tld/some.link]
1183 if ( $text == '' ) {
1184 # Autonumber if allowed. See bug #5918
1185 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1186 $text = '[' . ++
$this->mAutonumber
. ']';
1187 $linktype = 'autonumber';
1189 # Otherwise just use the URL
1190 $text = htmlspecialchars( $url );
1194 # Have link text, e.g. [http://domain.tld/some.link text]s
1196 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1199 $text = $wgContLang->markNoConversion($text);
1201 $url = Sanitizer
::cleanUrl( $url );
1203 # Process the trail (i.e. everything after this link up until start of the next link),
1204 # replacing any non-bracketed links
1205 $trail = $this->replaceFreeExternalLinks( $trail );
1207 # Use the encoded URL
1208 # This means that users can paste URLs directly into the text
1209 # Funny characters like ö aren't valid in URLs anyway
1210 # This was changed in August 2004
1211 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle
->getNamespace() ) . $dtrail . $trail;
1213 # Register link in the output object.
1214 # Replace unnecessary URL escape codes with the referenced character
1215 # This prevents spammers from hiding links from the filters
1216 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1217 $this->mOutput
->addExternalLink( $pasteurized );
1220 wfProfileOut( $fname );
1225 * Replace anything that looks like a URL with a link
1228 function replaceFreeExternalLinks( $text ) {
1230 $fname = 'Parser::replaceFreeExternalLinks';
1231 wfProfileIn( $fname );
1233 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1234 $s = array_shift( $bits );
1237 $sk =& $this->mOptions
->getSkin();
1239 while ( $i < count( $bits ) ){
1240 $protocol = $bits[$i++
];
1241 $remainder = $bits[$i++
];
1243 if ( preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $remainder, $m ) ) {
1244 # Found some characters after the protocol that look promising
1245 $url = $protocol . $m[1];
1248 # special case: handle urls as url args:
1249 # http://www.example.com/foo?=http://www.example.com/bar
1250 if(strlen($trail) == 0 &&
1252 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1253 preg_match( '/^('.EXT_LINK_URL_CLASS
.'+)(.*)$/s', $bits[$i +
1], $m ))
1256 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1261 # The characters '<' and '>' (which were escaped by
1262 # removeHTMLtags()) should not be included in
1263 # URLs, per RFC 2396.
1264 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1265 $trail = substr($url, $m2[0][1]) . $trail;
1266 $url = substr($url, 0, $m2[0][1]);
1269 # Move trailing punctuation to $trail
1271 # If there is no left bracket, then consider right brackets fair game too
1272 if ( strpos( $url, '(' ) === false ) {
1276 $numSepChars = strspn( strrev( $url ), $sep );
1277 if ( $numSepChars ) {
1278 $trail = substr( $url, -$numSepChars ) . $trail;
1279 $url = substr( $url, 0, -$numSepChars );
1282 $url = Sanitizer
::cleanUrl( $url );
1284 # Is this an external image?
1285 $text = $this->maybeMakeExternalImage( $url );
1286 if ( $text === false ) {
1287 # Not an image, make a link
1288 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle
->getNamespace() );
1289 # Register it in the output object...
1290 # Replace unnecessary URL escape codes with their equivalent characters
1291 $pasteurized = Parser
::replaceUnusualEscapes( $url );
1292 $this->mOutput
->addExternalLink( $pasteurized );
1294 $s .= $text . $trail;
1296 $s .= $protocol . $remainder;
1299 wfProfileOut( $fname );
1304 * Replace unusual URL escape codes with their equivalent characters
1308 * @fixme This can merge genuinely required bits in the path or query string,
1309 * breaking legit URLs. A proper fix would treat the various parts of
1310 * the URL differently; as a workaround, just use the output for
1311 * statistical records, not for actual linking/output.
1313 static function replaceUnusualEscapes( $url ) {
1314 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1315 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1319 * Callback function used in replaceUnusualEscapes().
1320 * Replaces unusual URL escape codes with their equivalent character
1324 private static function replaceUnusualEscapesCallback( $matches ) {
1325 $char = urldecode( $matches[0] );
1326 $ord = ord( $char );
1327 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1328 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1329 // No, shouldn't be escaped
1332 // Yes, leave it escaped
1338 * make an image if it's allowed, either through the global
1339 * option or through the exception
1342 function maybeMakeExternalImage( $url ) {
1343 $sk =& $this->mOptions
->getSkin();
1344 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1345 $imagesexception = !empty($imagesfrom);
1347 if ( $this->mOptions
->getAllowExternalImages()
1348 ||
( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1349 if ( preg_match( EXT_IMAGE_REGEX
, $url ) ) {
1351 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1358 * Process [[ ]] wikilinks
1362 function replaceInternalLinks( $s ) {
1364 static $fname = 'Parser::replaceInternalLinks' ;
1366 wfProfileIn( $fname );
1368 wfProfileIn( $fname.'-setup' );
1370 # the % is needed to support urlencoded titles as well
1371 if ( !$tc ) { $tc = Title
::legalChars() . '#%'; }
1373 $sk =& $this->mOptions
->getSkin();
1375 #split the entire text string on occurences of [[
1376 $a = explode( '[[', ' ' . $s );
1377 #get the first element (all text up to first [[), and remove the space we added
1378 $s = array_shift( $a );
1379 $s = substr( $s, 1 );
1381 # Match a link having the form [[namespace:link|alternate]]trail
1383 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1384 # Match cases where there is no "]]", which might still be images
1385 static $e1_img = FALSE;
1386 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1387 # Match the end of a line for a word that's not followed by whitespace,
1388 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1389 $e2 = wfMsgForContent( 'linkprefix' );
1391 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1393 if( is_null( $this->mTitle
) ) {
1394 throw new MWException( 'nooo' );
1396 $nottalk = !$this->mTitle
->isTalkPage();
1398 if ( $useLinkPrefixExtension ) {
1399 if ( preg_match( $e2, $s, $m ) ) {
1400 $first_prefix = $m[2];
1402 $first_prefix = false;
1408 $selflink = $this->mTitle
->getPrefixedText();
1409 wfProfileOut( $fname.'-setup' );
1411 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1412 $useSubpages = $this->areSubpagesAllowed();
1414 # Loop for each link
1415 for ($k = 0; isset( $a[$k] ); $k++
) {
1417 if ( $useLinkPrefixExtension ) {
1418 wfProfileIn( $fname.'-prefixhandling' );
1419 if ( preg_match( $e2, $s, $m ) ) {
1427 $prefix = $first_prefix;
1428 $first_prefix = false;
1430 wfProfileOut( $fname.'-prefixhandling' );
1433 $might_be_img = false;
1435 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1437 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1438 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1439 # the real problem is with the $e1 regex
1442 # Still some problems for cases where the ] is meant to be outside punctuation,
1443 # and no image is in sight. See bug 2095.
1446 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1447 strpos($text, '[') !== false
1450 $text .= ']'; # so that replaceExternalLinks($text) works later
1453 # fix up urlencoded title texts
1454 if(preg_match('/%/', $m[1] ))
1455 # Should anchors '#' also be rejected?
1456 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1458 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1459 $might_be_img = true;
1461 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1463 } else { # Invalid form; output directly
1464 $s .= $prefix . '[[' . $line ;
1468 # Don't allow internal links to pages containing
1469 # PROTO: where PROTO is a valid URL protocol; these
1470 # should be external links.
1471 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1472 $s .= $prefix . '[[' . $line ;
1476 # Make subpage if necessary
1477 if( $useSubpages ) {
1478 $link = $this->maybeDoSubpageLink( $m[1], $text );
1483 $noforce = (substr($m[1], 0, 1) != ':');
1485 # Strip off leading ':'
1486 $link = substr($link, 1);
1489 $nt = Title
::newFromText( $this->unstripNoWiki($link, $this->mStripState
) );
1491 $s .= $prefix . '[[' . $line;
1495 #check other language variants of the link
1496 #if the article does not exist
1497 if( $checkVariantLink
1498 && $nt->getArticleID() == 0 ) {
1499 $wgContLang->findVariantLink($link, $nt);
1502 $ns = $nt->getNamespace();
1503 $iw = $nt->getInterWiki();
1505 if ($might_be_img) { # if this is actually an invalid link
1506 if ($ns == NS_IMAGE
&& $noforce) { #but might be an image
1508 while (isset ($a[$k+
1]) ) {
1509 #look at the next 'line' to see if we can close it there
1510 $spliced = array_splice( $a, $k +
1, 1 );
1511 $next_line = array_shift( $spliced );
1512 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1513 # the first ]] closes the inner link, the second the image
1515 $text .= '[[' . $m[1];
1518 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1519 #if there's exactly one ]] that's fine, we'll keep looking
1520 $text .= '[[' . $m[0];
1522 #if $next_line is invalid too, we need look no further
1523 $text .= '[[' . $next_line;
1528 # we couldn't find the end of this imageLink, so output it raw
1529 #but don't ignore what might be perfectly normal links in the text we've examined
1530 $text = $this->replaceInternalLinks($text);
1531 $s .= $prefix . '[[' . $link . '|' . $text;
1532 # note: no $trail, because without an end, there *is* no trail
1535 } else { #it's not an image, so output it raw
1536 $s .= $prefix . '[[' . $link . '|' . $text;
1537 # note: no $trail, because without an end, there *is* no trail
1542 $wasblank = ( '' == $text );
1543 if( $wasblank ) $text = $link;
1546 # Link not escaped by : , create the various objects
1550 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1551 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1552 $s = rtrim($s . "\n");
1553 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1557 if ( $ns == NS_IMAGE
) {
1558 wfProfileIn( "$fname-image" );
1559 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1560 # recursively parse links inside the image caption
1561 # actually, this will parse them in any other parameters, too,
1562 # but it might be hard to fix that, and it doesn't matter ATM
1563 $text = $this->replaceExternalLinks($text);
1564 $text = $this->replaceInternalLinks($text);
1566 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1567 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1568 $this->mOutput
->addImage( $nt->getDBkey() );
1570 wfProfileOut( "$fname-image" );
1573 # We still need to record the image's presence on the page
1574 $this->mOutput
->addImage( $nt->getDBkey() );
1576 wfProfileOut( "$fname-image" );
1580 if ( $ns == NS_CATEGORY
) {
1581 wfProfileIn( "$fname-category" );
1582 $s = rtrim($s . "\n"); # bug 87
1585 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1586 $sortkey = $this->mTitle
->getText();
1588 $sortkey = $this->mTitle
->getPrefixedText();
1593 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1594 $sortkey = str_replace( "\n", '', $sortkey );
1595 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1596 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1599 * Strip the whitespace Category links produce, see bug 87
1600 * @todo We might want to use trim($tmp, "\n") here.
1602 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1604 wfProfileOut( "$fname-category" );
1609 if( ( $nt->getPrefixedText() === $selflink ) &&
1610 ( $nt->getFragment() === '' ) ) {
1611 # Self-links are handled specially; generally de-link and change to bold.
1612 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1616 # Special and Media are pseudo-namespaces; no pages actually exist in them
1617 if( $ns == NS_MEDIA
) {
1618 $link = $sk->makeMediaLinkObj( $nt, $text );
1619 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1620 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1621 $this->mOutput
->addImage( $nt->getDBkey() );
1623 } elseif( $ns == NS_SPECIAL
) {
1624 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1626 } elseif( $ns == NS_IMAGE
) {
1627 $img = new Image( $nt );
1628 if( $img->exists() ) {
1629 // Force a blue link if the file exists; may be a remote
1630 // upload on the shared repository, and we want to see its
1631 // auto-generated page.
1632 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1636 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1638 wfProfileOut( $fname );
1643 * Make a link placeholder. The text returned can be later resolved to a real link with
1644 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1645 * parsing of interwiki links, and secondly to allow all extistence checks and
1646 * article length checks (for stub links) to be bundled into a single query.
1649 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1650 if ( ! is_object($nt) ) {
1652 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1654 # Separate the link trail from the rest of the link
1655 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1657 if ( $nt->isExternal() ) {
1658 $nr = array_push( $this->mInterwikiLinkHolders
['texts'], $prefix.$text.$inside );
1659 $this->mInterwikiLinkHolders
['titles'][] = $nt;
1660 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1662 $nr = array_push( $this->mLinkHolders
['namespaces'], $nt->getNamespace() );
1663 $this->mLinkHolders
['dbkeys'][] = $nt->getDBkey();
1664 $this->mLinkHolders
['queries'][] = $query;
1665 $this->mLinkHolders
['texts'][] = $prefix.$text.$inside;
1666 $this->mLinkHolders
['titles'][] = $nt;
1668 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1675 * Render a forced-blue link inline; protect against double expansion of
1676 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1677 * Since this little disaster has to split off the trail text to avoid
1678 * breaking URLs in the following text without breaking trails on the
1679 * wiki links, it's been made into a horrible function.
1682 * @param string $text
1683 * @param string $query
1684 * @param string $trail
1685 * @param string $prefix
1686 * @return string HTML-wikitext mix oh yuck
1688 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1689 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1690 $sk =& $this->mOptions
->getSkin();
1691 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1692 return $this->armorLinks( $link ) . $trail;
1696 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1697 * going to go through further parsing steps before inline URL expansion.
1699 * In particular this is important when using action=render, which causes
1700 * full URLs to be included.
1702 * Oh man I hate our multi-layer parser!
1704 * @param string more-or-less HTML
1705 * @return string less-or-more HTML with NOPARSE bits
1707 function armorLinks( $text ) {
1708 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1709 "{$this->mUniqPrefix}NOPARSE$1", $text );
1713 * Return true if subpage links should be expanded on this page.
1716 function areSubpagesAllowed() {
1717 # Some namespaces don't allow subpages
1718 global $wgNamespacesWithSubpages;
1719 return !empty($wgNamespacesWithSubpages[$this->mTitle
->getNamespace()]);
1723 * Handle link to subpage if necessary
1724 * @param string $target the source of the link
1725 * @param string &$text the link text, modified as necessary
1726 * @return string the full name of the link
1729 function maybeDoSubpageLink($target, &$text) {
1732 # :Foobar -- override special treatment of prefix (images, language links)
1733 # /Foobar -- convert to CurrentPage/Foobar
1734 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1735 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1736 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1738 $fname = 'Parser::maybeDoSubpageLink';
1739 wfProfileIn( $fname );
1740 $ret = $target; # default return value is no change
1742 # Some namespaces don't allow subpages,
1743 # so only perform processing if subpages are allowed
1744 if( $this->areSubpagesAllowed() ) {
1745 # Look at the first character
1746 if( $target != '' && $target{0} == '/' ) {
1747 # / at end means we don't want the slash to be shown
1748 if( substr( $target, -1, 1 ) == '/' ) {
1749 $target = substr( $target, 1, -1 );
1752 $noslash = substr( $target, 1 );
1755 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash);
1756 if( '' === $text ) {
1758 } # this might be changed for ugliness reasons
1760 # check for .. subpage backlinks
1762 $nodotdot = $target;
1763 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1765 $nodotdot = substr( $nodotdot, 3 );
1767 if($dotdotcount > 0) {
1768 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1769 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1770 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1771 # / at the end means don't show full path
1772 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1773 $nodotdot = substr( $nodotdot, 0, -1 );
1774 if( '' === $text ) {
1778 $nodotdot = trim( $nodotdot );
1779 if( $nodotdot != '' ) {
1780 $ret .= '/' . $nodotdot;
1787 wfProfileOut( $fname );
1792 * Used by doBlockLevels()
1795 /* private */ function closeParagraph() {
1797 if ( '' != $this->mLastSection
) {
1798 $result = '</' . $this->mLastSection
. ">\n";
1800 $this->mInPre
= false;
1801 $this->mLastSection
= '';
1804 # getCommon() returns the length of the longest common substring
1805 # of both arguments, starting at the beginning of both.
1807 /* private */ function getCommon( $st1, $st2 ) {
1808 $fl = strlen( $st1 );
1809 $shorter = strlen( $st2 );
1810 if ( $fl < $shorter ) { $shorter = $fl; }
1812 for ( $i = 0; $i < $shorter; ++
$i ) {
1813 if ( $st1{$i} != $st2{$i} ) { break; }
1817 # These next three functions open, continue, and close the list
1818 # element appropriate to the prefix character passed into them.
1820 /* private */ function openList( $char ) {
1821 $result = $this->closeParagraph();
1823 if ( '*' == $char ) { $result .= '<ul><li>'; }
1824 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1825 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1826 else if ( ';' == $char ) {
1827 $result .= '<dl><dt>';
1828 $this->mDTopen
= true;
1830 else { $result = '<!-- ERR 1 -->'; }
1835 /* private */ function nextItem( $char ) {
1836 if ( '*' == $char ||
'#' == $char ) { return '</li><li>'; }
1837 else if ( ':' == $char ||
';' == $char ) {
1839 if ( $this->mDTopen
) { $close = '</dt>'; }
1840 if ( ';' == $char ) {
1841 $this->mDTopen
= true;
1842 return $close . '<dt>';
1844 $this->mDTopen
= false;
1845 return $close . '<dd>';
1848 return '<!-- ERR 2 -->';
1851 /* private */ function closeList( $char ) {
1852 if ( '*' == $char ) { $text = '</li></ul>'; }
1853 else if ( '#' == $char ) { $text = '</li></ol>'; }
1854 else if ( ':' == $char ) {
1855 if ( $this->mDTopen
) {
1856 $this->mDTopen
= false;
1857 $text = '</dt></dl>';
1859 $text = '</dd></dl>';
1862 else { return '<!-- ERR 3 -->'; }
1868 * Make lists from lines starting with ':', '*', '#', etc.
1871 * @return string the lists rendered as HTML
1873 function doBlockLevels( $text, $linestart ) {
1874 $fname = 'Parser::doBlockLevels';
1875 wfProfileIn( $fname );
1877 # Parsing through the text line by line. The main thing
1878 # happening here is handling of block-level elements p, pre,
1879 # and making lists from lines starting with * # : etc.
1881 $textLines = explode( "\n", $text );
1883 $lastPrefix = $output = '';
1884 $this->mDTopen
= $inBlockElem = false;
1886 $paragraphStack = false;
1888 if ( !$linestart ) {
1889 $output .= array_shift( $textLines );
1891 foreach ( $textLines as $oLine ) {
1892 $lastPrefixLength = strlen( $lastPrefix );
1893 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1894 $preOpenMatch = preg_match('/<pre/i', $oLine );
1895 if ( !$this->mInPre
) {
1896 # Multiple prefixes may abut each other for nested lists.
1897 $prefixLength = strspn( $oLine, '*#:;' );
1898 $pref = substr( $oLine, 0, $prefixLength );
1901 $pref2 = str_replace( ';', ':', $pref );
1902 $t = substr( $oLine, $prefixLength );
1903 $this->mInPre
= !empty($preOpenMatch);
1905 # Don't interpret any other prefixes in preformatted text
1907 $pref = $pref2 = '';
1912 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1913 # Same as the last item, so no need to deal with nesting or opening stuff
1914 $output .= $this->nextItem( substr( $pref, -1 ) );
1915 $paragraphStack = false;
1917 if ( substr( $pref, -1 ) == ';') {
1918 # The one nasty exception: definition lists work like this:
1919 # ; title : definition text
1920 # So we check for : in the remainder text to split up the
1921 # title and definition, without b0rking links.
1923 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1925 $output .= $term . $this->nextItem( ':' );
1928 } elseif( $prefixLength ||
$lastPrefixLength ) {
1929 # Either open or close a level...
1930 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1931 $paragraphStack = false;
1933 while( $commonPrefixLength < $lastPrefixLength ) {
1934 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1935 --$lastPrefixLength;
1937 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1938 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1940 while ( $prefixLength > $commonPrefixLength ) {
1941 $char = substr( $pref, $commonPrefixLength, 1 );
1942 $output .= $this->openList( $char );
1944 if ( ';' == $char ) {
1945 # FIXME: This is dupe of code above
1946 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1948 $output .= $term . $this->nextItem( ':' );
1951 ++
$commonPrefixLength;
1953 $lastPrefix = $pref2;
1955 if( 0 == $prefixLength ) {
1956 wfProfileIn( "$fname-paragraph" );
1957 # No prefix (not in list)--go to paragraph mode
1958 // XXX: use a stack for nestable elements like span, table and div
1959 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
1960 $closematch = preg_match(
1961 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1962 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
1963 if ( $openmatch or $closematch ) {
1964 $paragraphStack = false;
1965 #Â TODO bug 5718: paragraph closed
1966 $output .= $this->closeParagraph();
1967 if ( $preOpenMatch and !$preCloseMatch ) {
1968 $this->mInPre
= true;
1970 if ( $closematch ) {
1971 $inBlockElem = false;
1973 $inBlockElem = true;
1975 } else if ( !$inBlockElem && !$this->mInPre
) {
1976 if ( ' ' == $t{0} and ( $this->mLastSection
== 'pre' or trim($t) != '' ) ) {
1978 if ($this->mLastSection
!= 'pre') {
1979 $paragraphStack = false;
1980 $output .= $this->closeParagraph().'<pre>';
1981 $this->mLastSection
= 'pre';
1983 $t = substr( $t, 1 );
1986 if ( '' == trim($t) ) {
1987 if ( $paragraphStack ) {
1988 $output .= $paragraphStack.'<br />';
1989 $paragraphStack = false;
1990 $this->mLastSection
= 'p';
1992 if ($this->mLastSection
!= 'p' ) {
1993 $output .= $this->closeParagraph();
1994 $this->mLastSection
= '';
1995 $paragraphStack = '<p>';
1997 $paragraphStack = '</p><p>';
2001 if ( $paragraphStack ) {
2002 $output .= $paragraphStack;
2003 $paragraphStack = false;
2004 $this->mLastSection
= 'p';
2005 } else if ($this->mLastSection
!= 'p') {
2006 $output .= $this->closeParagraph().'<p>';
2007 $this->mLastSection
= 'p';
2012 wfProfileOut( "$fname-paragraph" );
2014 // somewhere above we forget to get out of pre block (bug 785)
2015 if($preCloseMatch && $this->mInPre
) {
2016 $this->mInPre
= false;
2018 if ($paragraphStack === false) {
2022 while ( $prefixLength ) {
2023 $output .= $this->closeList( $pref2{$prefixLength-1} );
2026 if ( '' != $this->mLastSection
) {
2027 $output .= '</' . $this->mLastSection
. '>';
2028 $this->mLastSection
= '';
2031 wfProfileOut( $fname );
2036 * Split up a string on ':', ignoring any occurences inside tags
2037 * to prevent illegal overlapping.
2038 * @param string $str the string to split
2039 * @param string &$before set to everything before the ':'
2040 * @param string &$after set to everything after the ':'
2041 * return string the position of the ':', or false if none found
2043 function findColonNoLinks($str, &$before, &$after) {
2044 $fname = 'Parser::findColonNoLinks';
2045 wfProfileIn( $fname );
2047 $pos = strpos( $str, ':' );
2048 if( $pos === false ) {
2050 wfProfileOut( $fname );
2054 $lt = strpos( $str, '<' );
2055 if( $lt === false ||
$lt > $pos ) {
2056 // Easy; no tag nesting to worry about
2057 $before = substr( $str, 0, $pos );
2058 $after = substr( $str, $pos+
1 );
2059 wfProfileOut( $fname );
2063 // Ugly state machine to walk through avoiding tags.
2064 $state = MW_COLON_STATE_TEXT
;
2066 $len = strlen( $str );
2067 for( $i = 0; $i < $len; $i++
) {
2071 // (Using the number is a performance hack for common cases)
2072 case 0: // MW_COLON_STATE_TEXT:
2075 // Could be either a <start> tag or an </end> tag
2076 $state = MW_COLON_STATE_TAGSTART
;
2081 $before = substr( $str, 0, $i );
2082 $after = substr( $str, $i +
1 );
2083 wfProfileOut( $fname );
2086 // Embedded in a tag; don't break it.
2089 // Skip ahead looking for something interesting
2090 $colon = strpos( $str, ':', $i );
2091 if( $colon === false ) {
2092 // Nothing else interesting
2093 wfProfileOut( $fname );
2096 $lt = strpos( $str, '<', $i );
2097 if( $stack === 0 ) {
2098 if( $lt === false ||
$colon < $lt ) {
2100 $before = substr( $str, 0, $colon );
2101 $after = substr( $str, $colon +
1 );
2102 wfProfileOut( $fname );
2106 if( $lt === false ) {
2107 // Nothing else interesting to find; abort!
2108 // We're nested, but there's no close tags left. Abort!
2111 // Skip ahead to next tag start
2113 $state = MW_COLON_STATE_TAGSTART
;
2116 case 1: // MW_COLON_STATE_TAG:
2121 $state = MW_COLON_STATE_TEXT
;
2124 // Slash may be followed by >?
2125 $state = MW_COLON_STATE_TAGSLASH
;
2131 case 2: // MW_COLON_STATE_TAGSTART:
2134 $state = MW_COLON_STATE_CLOSETAG
;
2137 $state = MW_COLON_STATE_COMMENT
;
2140 // Illegal early close? This shouldn't happen D:
2141 $state = MW_COLON_STATE_TEXT
;
2144 $state = MW_COLON_STATE_TAG
;
2147 case 3: // MW_COLON_STATE_CLOSETAG:
2152 wfDebug( "Invalid input in $fname; too many close tags\n" );
2153 wfProfileOut( $fname );
2156 $state = MW_COLON_STATE_TEXT
;
2159 case MW_COLON_STATE_TAGSLASH
:
2161 // Yes, a self-closed tag <blah/>
2162 $state = MW_COLON_STATE_TEXT
;
2164 // Probably we're jumping the gun, and this is an attribute
2165 $state = MW_COLON_STATE_TAG
;
2168 case 5: // MW_COLON_STATE_COMMENT:
2170 $state = MW_COLON_STATE_COMMENTDASH
;
2173 case MW_COLON_STATE_COMMENTDASH
:
2175 $state = MW_COLON_STATE_COMMENTDASHDASH
;
2177 $state = MW_COLON_STATE_COMMENT
;
2180 case MW_COLON_STATE_COMMENTDASHDASH
:
2182 $state = MW_COLON_STATE_TEXT
;
2184 $state = MW_COLON_STATE_COMMENT
;
2188 throw new MWException( "State machine error in $fname" );
2192 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2195 wfProfileOut( $fname );
2200 * Return value of a magic variable (like PAGENAME)
2204 function getVariableValue( $index ) {
2205 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2208 * Some of these require message or data lookups and can be
2209 * expensive to check many times.
2211 static $varCache = array();
2212 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2213 if ( isset( $varCache[$index] ) )
2214 return $varCache[$index];
2217 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2220 case 'currentmonth':
2221 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2222 case 'currentmonthname':
2223 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2224 case 'currentmonthnamegen':
2225 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2226 case 'currentmonthabbrev':
2227 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2229 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2231 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2233 return $this->mTitle
->getText();
2235 return $this->mTitle
->getPartialURL();
2236 case 'fullpagename':
2237 return $this->mTitle
->getPrefixedText();
2238 case 'fullpagenamee':
2239 return $this->mTitle
->getPrefixedURL();
2241 return $this->mTitle
->getSubpageText();
2242 case 'subpagenamee':
2243 return $this->mTitle
->getSubpageUrlForm();
2244 case 'basepagename':
2245 return $this->mTitle
->getBaseText();
2246 case 'basepagenamee':
2247 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2248 case 'talkpagename':
2249 if( $this->mTitle
->canTalk() ) {
2250 $talkPage = $this->mTitle
->getTalkPage();
2251 return $talkPage->getPrefixedText();
2255 case 'talkpagenamee':
2256 if( $this->mTitle
->canTalk() ) {
2257 $talkPage = $this->mTitle
->getTalkPage();
2258 return $talkPage->getPrefixedUrl();
2262 case 'subjectpagename':
2263 $subjPage = $this->mTitle
->getSubjectPage();
2264 return $subjPage->getPrefixedText();
2265 case 'subjectpagenamee':
2266 $subjPage = $this->mTitle
->getSubjectPage();
2267 return $subjPage->getPrefixedUrl();
2269 return $this->mRevisionId
;
2271 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2273 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2275 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2277 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2278 case 'subjectspace':
2279 return $this->mTitle
->getSubjectNsText();
2280 case 'subjectspacee':
2281 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2282 case 'currentdayname':
2283 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) +
1 );
2285 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2287 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2289 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2290 // int to remove the padding
2291 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2293 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2294 case 'numberofarticles':
2295 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2296 case 'numberoffiles':
2297 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2298 case 'numberofusers':
2299 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2300 case 'numberofpages':
2301 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2302 case 'numberofadmins':
2303 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2304 case 'currenttimestamp':
2305 return $varCache[$index] = wfTimestampNow();
2306 case 'currentversion':
2314 return $wgServerName;
2316 return $wgScriptPath;
2317 case 'directionmark':
2318 return $wgContLang->getDirMark();
2319 case 'contentlanguage':
2320 global $wgContLanguageCode;
2321 return $wgContLanguageCode;
2324 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2332 * initialise the magic variables (like CURRENTMONTHNAME)
2336 function initialiseVariables() {
2337 $fname = 'Parser::initialiseVariables';
2338 wfProfileIn( $fname );
2339 $variableIDs = MagicWord
::getVariableIDs();
2341 $this->mVariables
= array();
2342 foreach ( $variableIDs as $id ) {
2343 $mw =& MagicWord
::get( $id );
2344 $mw->addToArray( $this->mVariables
, $id );
2346 wfProfileOut( $fname );
2350 * parse any parentheses in format ((title|part|part))
2351 * and call callbacks to get a replacement text for any found piece
2353 * @param string $text The text to parse
2354 * @param array $callbacks rules in form:
2355 * '{' => array( # opening parentheses
2356 * 'end' => '}', # closing parentheses
2357 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2358 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2363 function replace_callback ($text, $callbacks) {
2364 wfProfileIn( __METHOD__
. '-self' );
2365 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2366 $lastOpeningBrace = -1; # last not closed parentheses
2368 for ($i = 0; $i < strlen($text); $i++
) {
2369 # check for any opening brace
2372 foreach ($callbacks as $key => $value) {
2373 $pos = strpos ($text, $key, $i);
2374 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)) {
2380 if ($lastOpeningBrace >= 0) {
2381 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2383 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2388 $pos = strpos ($text, '|', $i);
2390 if (false !== $pos && (-1 == $nextPos ||
$pos < $nextPos)){
2401 # found openning brace, lets add it to parentheses stack
2402 if (null != $rule) {
2403 $piece = array('brace' => $text[$i],
2404 'braceEnd' => $rule['end'],
2409 # count openning brace characters
2410 while ($i+
1 < strlen($text) && $text[$i+
1] == $piece['brace']) {
2415 $piece['startAt'] = $i+
1;
2416 $piece['partStart'] = $i+
1;
2418 # we need to add to stack only if openning brace count is enough for any given rule
2419 foreach ($rule['cb'] as $cnt => $fn) {
2420 if ($piece['count'] >= $cnt) {
2421 $lastOpeningBrace ++
;
2422 $openingBraceStack[$lastOpeningBrace] = $piece;
2429 else if ($lastOpeningBrace >= 0) {
2430 # first check if it is a closing brace
2431 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2432 # lets check if it is enough characters for closing brace
2434 while ($i+
$count < strlen($text) && $text[$i+
$count] == $text[$i])
2437 # if there are more closing parentheses than opening ones, we parse less
2438 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2439 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2441 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2443 $matchingCallback = null;
2444 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2445 if ($count >= $cnt && $matchingCount < $cnt) {
2446 $matchingCount = $cnt;
2447 $matchingCallback = $fn;
2451 if ($matchingCount == 0) {
2456 # lets set a title or last part (if '|' was found)
2457 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2458 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2460 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2462 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2463 $pieceEnd = $i +
$matchingCount;
2465 if( is_callable( $matchingCallback ) ) {
2467 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2468 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2469 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2470 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2472 # finally we can call a user callback and replace piece of text
2473 wfProfileOut( __METHOD__
. '-self' );
2474 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2475 wfProfileIn( __METHOD__
. '-self' );
2476 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2477 $i = $pieceStart +
strlen($replaceWith) - 1;
2480 # null value for callback means that parentheses should be parsed, but not replaced
2481 $i +
= $matchingCount - 1;
2484 # reset last openning parentheses, but keep it in case there are unused characters
2485 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2486 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2487 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2490 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2491 $openingBraceStack[$lastOpeningBrace--] = null;
2493 if ($matchingCount < $piece['count']) {
2494 $piece['count'] -= $matchingCount;
2495 $piece['startAt'] -= $matchingCount;
2496 $piece['partStart'] = $piece['startAt'];
2497 # do we still qualify for any callback with remaining count?
2498 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2499 if ($piece['count'] >= $cnt) {
2500 $lastOpeningBrace ++
;
2501 $openingBraceStack[$lastOpeningBrace] = $piece;
2509 # lets set a title if it is a first separator, or next part otherwise
2510 if ($text[$i] == '|') {
2511 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2512 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2513 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2516 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2518 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i +
1;
2523 wfProfileOut( __METHOD__
. '-self' );
2528 * Replace magic variables, templates, and template arguments
2529 * with the appropriate text. Templates are substituted recursively,
2530 * taking care to avoid infinite loops.
2532 * Note that the substitution depends on value of $mOutputType:
2533 * OT_WIKI: only {{subst:}} templates
2534 * OT_MSG: only magic variables
2535 * OT_HTML: all templates and magic variables
2537 * @param string $tex The text to transform
2538 * @param array $args Key-value pairs representing template parameters to substitute
2539 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2542 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2543 # Prevent too big inclusions
2544 if( strlen( $text ) > MAX_INCLUDE_SIZE
) {
2548 $fname = 'Parser::replaceVariables';
2549 wfProfileIn( $fname );
2551 # This function is called recursively. To keep track of arguments we need a stack:
2552 array_push( $this->mArgStack
, $args );
2554 $braceCallbacks = array();
2556 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2558 if ( $this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) {
2559 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2561 $callbacks = array();
2562 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2563 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2564 $text = $this->replace_callback ($text, $callbacks);
2566 array_pop( $this->mArgStack
);
2568 wfProfileOut( $fname );
2573 * Replace magic variables
2576 function variableSubstitution( $matches ) {
2577 $fname = 'Parser::variableSubstitution';
2578 $varname = $matches[1];
2579 wfProfileIn( $fname );
2581 if ( $this->mOutputType
== OT_WIKI
) {
2582 # Do only magic variables prefixed by SUBST
2583 $mwSubst =& MagicWord
::get( 'subst' );
2584 if (!$mwSubst->matchStartAndRemove( $varname ))
2586 # Note that if we don't substitute the variable below,
2587 # we don't remove the {{subst:}} magic word, in case
2588 # it is a template rather than a magic variable.
2590 if ( !$skip && array_key_exists( $varname, $this->mVariables
) ) {
2591 $id = $this->mVariables
[$varname];
2592 $text = $this->getVariableValue( $id );
2593 $this->mOutput
->mContainsOldMagic
= true;
2595 $text = $matches[0];
2597 wfProfileOut( $fname );
2601 # Split template arguments
2602 function getTemplateArgs( $argsString ) {
2603 if ( $argsString === '' ) {
2607 $args = explode( '|', substr( $argsString, 1 ) );
2609 # If any of the arguments contains a '[[' but no ']]', it needs to be
2610 # merged with the next arg because the '|' character between belongs
2611 # to the link syntax and not the template parameter syntax.
2612 $argc = count($args);
2614 for ( $i = 0; $i < $argc-1; $i++
) {
2615 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2616 $args[$i] .= '|'.$args[$i+
1];
2617 array_splice($args, $i+
1, 1);
2627 * Return the text of a template, after recursively
2628 * replacing any variables or templates within the template.
2630 * @param array $piece The parts of the template
2631 * $piece['text']: matched text
2632 * $piece['title']: the title, i.e. the part before the |
2633 * $piece['parts']: the parameter array
2634 * @return string the text of the template
2637 function braceSubstitution( $piece ) {
2638 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2639 $fname = 'Parser::braceSubstitution';
2640 wfProfileIn( $fname );
2643 $found = false; # $text has been filled
2644 $nowiki = false; # wiki markup in $text should be escaped
2645 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2646 $noargs = false; # Don't replace triple-brace arguments in $text
2647 $replaceHeadings = false; # Make the edit section links go to the template not the article
2648 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2649 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2651 # Title object, where $text came from
2656 # $part1 is the bit before the first |, and must contain only title characters
2657 # $args is a list of arguments, starting from index 0, not including $part1
2659 $part1 = $piece['title'];
2660 # If the third subpattern matched anything, it will start with |
2662 if (null == $piece['parts']) {
2663 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2664 if ($replaceWith != $piece['text']) {
2665 $text = $replaceWith;
2672 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2673 $argc = count( $args );
2677 $mwSubst =& MagicWord
::get( 'subst' );
2678 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType
== OT_WIKI
) ) {
2679 # One of two possibilities is true:
2680 # 1) Found SUBST but not in the PST phase
2681 # 2) Didn't find SUBST and in the PST phase
2682 # In either case, return without further processing
2683 $text = $piece['text'];
2690 # MSG, MSGNW, INT and RAW
2693 $mwMsgnw =& MagicWord
::get( 'msgnw' );
2694 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2697 # Remove obsolete MSG:
2698 $mwMsg =& MagicWord
::get( 'msg' );
2699 $mwMsg->matchStartAndRemove( $part1 );
2703 $mwRaw =& MagicWord
::get( 'raw' );
2704 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2705 $forceRawInterwiki = true;
2708 # Check if it is an internal message
2709 $mwInt =& MagicWord
::get( 'int' );
2710 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2711 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2712 $text = $linestart . wfMsgReal( $part1, $args, true );
2720 wfProfileIn( __METHOD__
. '-pfunc' );
2722 $colonPos = strpos( $part1, ':' );
2723 if ( $colonPos !== false ) {
2724 # Case sensitive functions
2725 $function = substr( $part1, 0, $colonPos );
2726 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2727 $function = $this->mFunctionSynonyms
[1][$function];
2729 # Case insensitive functions
2730 $function = strtolower( $function );
2731 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2732 $function = $this->mFunctionSynonyms
[0][$function];
2738 $funcArgs = array_map( 'trim', $args );
2739 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos +
1 ) ) ), $funcArgs );
2740 $result = call_user_func_array( $this->mFunctionHooks
[$function], $funcArgs );
2743 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2747 if ( is_array( $result ) ) {
2748 if ( isset( $result[0] ) ) {
2749 $text = $linestart . $result[0];
2750 unset( $result[0] );
2753 // Extract flags into the local scope
2754 // This allows callers to set flags such as nowiki, noparse, found, etc.
2757 $text = $linestart . $result;
2761 wfProfileOut( __METHOD__
. '-pfunc' );
2764 # Template table test
2766 # Did we encounter this template already? If yes, it is in the cache
2767 # and we need to check for loops.
2768 if ( !$found && isset( $this->mTemplates
[$piece['title']] ) ) {
2771 # Infinite loop test
2772 if ( isset( $this->mTemplatePath
[$part1] ) ) {
2776 $text = $linestart .
2777 '{{' . $part1 . '}}' .
2778 '<!-- WARNING: template loop detected -->';
2779 wfDebug( "$fname: template loop broken at '$part1'\n" );
2781 # set $text to cached message.
2782 $text = $linestart . $this->mTemplates
[$piece['title']];
2786 # Load from database
2787 $lastPathLevel = $this->mTemplatePath
;
2789 wfProfileIn( __METHOD__
. '-loadtpl' );
2791 # declaring $subpage directly in the function call
2792 # does not work correctly with references and breaks
2793 # {{/subpage}}-style inclusions
2795 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2796 if ($subpage !== '') {
2797 $ns = $this->mTitle
->getNamespace();
2799 $title = Title
::newFromText( $part1, $ns );
2802 if ( !is_null( $title ) ) {
2803 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2804 # Check for language variants if the template is not found
2805 if($checkVariantLink && $title->getArticleID() == 0){
2806 $wgContLang->findVariantLink($part1, $title);
2809 if ( !$title->isExternal() ) {
2810 # Check for excessive inclusion
2811 $dbk = $title->getPrefixedDBkey();
2812 if ( $this->incrementIncludeCount( $dbk ) ) {
2813 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->mOutputType
!= OT_WIKI
) {
2814 $text = SpecialPage
::capturePath( $title );
2815 if ( is_string( $text ) ) {
2820 $this->disableCache();
2823 $articleContent = $this->fetchTemplate( $title );
2824 if ( $articleContent !== false ) {
2826 $text = $articleContent;
2827 $replaceHeadings = true;
2832 # If the title is valid but undisplayable, make a link to it
2833 if ( $this->mOutputType
== OT_HTML
&& !$found ) {
2834 $text = '[['.$title->getPrefixedText().']]';
2837 } elseif ( $title->isTrans() ) {
2838 // Interwiki transclusion
2839 if ( $this->mOutputType
== OT_HTML
&& !$forceRawInterwiki ) {
2840 $text = $this->interwikiTransclude( $title, 'render' );
2844 $text = $this->interwikiTransclude( $title, 'raw' );
2845 $replaceHeadings = true;
2850 # Template cache array insertion
2851 # Use the original $piece['title'] not the mangled $part1, so that
2852 # modifiers such as RAW: produce separate cache entries
2855 // A special page; don't store it in the template cache.
2857 $this->mTemplates
[$piece['title']] = $text;
2859 $text = $linestart . $text;
2862 wfProfileOut( __METHOD__
. '-loadtpl' );
2865 # Recursive parsing, escaping and link table handling
2866 # Only for HTML output
2867 if ( $nowiki && $found && $this->mOutputType
== OT_HTML
) {
2868 $text = wfEscapeWikiText( $text );
2869 } elseif ( ($this->mOutputType
== OT_HTML ||
$this->mOutputType
== OT_WIKI
) && $found ) {
2871 $assocArgs = array();
2873 # Clean up argument array
2874 $assocArgs = array();
2876 foreach( $args as $arg ) {
2877 $eqpos = strpos( $arg, '=' );
2878 if ( $eqpos === false ) {
2879 $assocArgs[$index++
] = $arg;
2881 $name = trim( substr( $arg, 0, $eqpos ) );
2882 $value = trim( substr( $arg, $eqpos+
1 ) );
2883 if ( $value === false ) {
2886 if ( $name !== false ) {
2887 $assocArgs[$name] = $value;
2892 # Add a new element to the templace recursion path
2893 $this->mTemplatePath
[$part1] = 1;
2897 # If there are any <onlyinclude> tags, only include them
2898 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2899 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2901 foreach ($m[1] as $piece)
2904 # Remove <noinclude> sections and <includeonly> tags
2905 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2906 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2908 if( $this->mOutputType
== OT_HTML
) {
2909 # Strip <nowiki>, <pre>, etc.
2910 $text = $this->strip( $text, $this->mStripState
);
2911 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2913 $text = $this->replaceVariables( $text, $assocArgs );
2915 # If the template begins with a table or block-level
2916 # element, it should be treated as beginning a new line.
2917 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2918 $text = "\n" . $text;
2920 } elseif ( !$noargs ) {
2921 # $noparse and !$noargs
2922 # Just replace the arguments, not any double-brace items
2923 # This is used for rendered interwiki transclusion
2924 $text = $this->replaceVariables( $text, $assocArgs, true );
2927 # Prune lower levels off the recursion check path
2928 $this->mTemplatePath
= $lastPathLevel;
2931 wfProfileOut( $fname );
2932 return $piece['text'];
2934 wfProfileIn( __METHOD__
. '-placeholders' );
2936 # Replace raw HTML by a placeholder
2937 # Add a blank line preceding, to prevent it from mucking up
2938 # immediately preceding headings
2939 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState
);
2941 # replace ==section headers==
2942 # XXX this needs to go away once we have a better parser.
2943 if ( $this->mOutputType
!= OT_WIKI
&& $replaceHeadings ) {
2944 if( !is_null( $title ) )
2945 $encodedname = base64_encode($title->getPrefixedDBkey());
2947 $encodedname = base64_encode("");
2948 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2949 PREG_SPLIT_DELIM_CAPTURE
);
2952 for( $i = 0; $i < count($m); $i +
= 2 ) {
2954 if (!isset($m[$i +
1]) ||
$m[$i +
1] == "") continue;
2956 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2960 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2961 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2962 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2968 wfProfileOut( __METHOD__
. '-placeholders' );
2971 # Prune lower levels off the recursion check path
2972 $this->mTemplatePath
= $lastPathLevel;
2975 wfProfileOut( $fname );
2976 return $piece['text'];
2978 wfProfileOut( $fname );
2984 * Fetch the unparsed text of a template and register a reference to it.
2986 function fetchTemplate( $title ) {
2988 // Loop to fetch the article, with up to 1 redirect
2989 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
2990 $rev = Revision
::newFromTitle( $title );
2991 $this->mOutput
->addTemplate( $title, $title->getArticleID() );
2995 $text = $rev->getText();
2996 if ( $text === false ) {
3000 $title = Title
::newFromRedirect( $text );
3006 * Transclude an interwiki link.
3008 function interwikiTransclude( $title, $action ) {
3009 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3011 if (!$wgEnableScaryTranscluding)
3012 return wfMsg('scarytranscludedisabled');
3014 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3015 // But we'll handle it generally anyway
3016 if ( $title->getNamespace() ) {
3017 // Use the canonical namespace, which should work anywhere
3018 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3020 $articleName = $title->getDBkey();
3023 $url = str_replace('$1', urlencode($articleName), Title
::getInterwikiLink($title->getInterwiki()));
3024 $url .= "?action=$action";
3025 if (strlen($url) > 255)
3026 return wfMsg('scarytranscludetoolong');
3027 return $this->fetchScaryTemplateMaybeFromCache($url);
3030 function fetchScaryTemplateMaybeFromCache($url) {
3031 global $wgTranscludeCacheExpiry;
3032 $dbr =& wfGetDB(DB_SLAVE
);
3033 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3034 array('tc_url' => $url));
3036 $time = $obj->tc_time
;
3037 $text = $obj->tc_contents
;
3038 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3043 $text = Http
::get($url);
3045 return wfMsg('scarytranscludefailed', $url);
3047 $dbw =& wfGetDB(DB_MASTER
);
3048 $dbw->replace('transcache', array('tc_url'), array(
3050 'tc_time' => time(),
3051 'tc_contents' => $text));
3057 * Triple brace replacement -- used for template arguments
3060 function argSubstitution( $matches ) {
3061 $arg = trim( $matches['title'] );
3062 $text = $matches['text'];
3063 $inputArgs = end( $this->mArgStack
);
3065 if ( array_key_exists( $arg, $inputArgs ) ) {
3066 $text = $inputArgs[$arg];
3067 } else if ($this->mOutputType
== OT_HTML
&& null != $matches['parts'] && count($matches['parts']) > 0) {
3068 $text = $matches['parts'][0];
3075 * Returns true if the function is allowed to include this entity
3078 function incrementIncludeCount( $dbk ) {
3079 if ( !array_key_exists( $dbk, $this->mIncludeCount
) ) {
3080 $this->mIncludeCount
[$dbk] = 0;
3082 if ( ++
$this->mIncludeCount
[$dbk] <= MAX_INCLUDE_REPEAT
) {
3090 * Detect __NOGALLERY__ magic word and set a placeholder
3092 function stripNoGallery( &$text ) {
3093 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3095 $mw = MagicWord
::get( 'nogallery' );
3096 $this->mOutput
->mNoGallery
= $mw->matchAndRemove( $text ) ;
3100 * Detect __TOC__ magic word and set a placeholder
3102 function stripToc( $text ) {
3103 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3105 $mw = MagicWord
::get( 'notoc' );
3106 if( $mw->matchAndRemove( $text ) ) {
3107 $this->mShowToc
= false;
3110 $mw = MagicWord
::get( 'toc' );
3111 if( $mw->match( $text ) ) {
3112 $this->mShowToc
= true;
3113 $this->mForceTocPosition
= true;
3115 // Set a placeholder. At the end we'll fill it in with the TOC.
3116 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3118 // Only keep the first one.
3119 $text = $mw->replace( '', $text );
3125 * This function accomplishes several tasks:
3126 * 1) Auto-number headings if that option is enabled
3127 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3128 * 3) Add a Table of contents on the top for users who have enabled the option
3129 * 4) Auto-anchor headings
3131 * It loops through all headlines, collects the necessary data, then splits up the
3132 * string and re-inserts the newly formatted headlines.
3134 * @param string $text
3135 * @param boolean $isMain
3138 function formatHeadings( $text, $isMain=true ) {
3139 global $wgMaxTocLevel, $wgContLang;
3141 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3142 if( !$this->mTitle
->userCanEdit() ) {
3145 $showEditLink = $this->mOptions
->getEditSection();
3148 # Inhibit editsection links if requested in the page
3149 $esw =& MagicWord
::get( 'noeditsection' );
3150 if( $esw->matchAndRemove( $text ) ) {
3154 # Get all headlines for numbering them and adding funky stuff like [edit]
3155 # links - this is for later, but we need the number of headlines right now
3156 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3158 # if there are fewer than 4 headlines in the article, do not show TOC
3159 # unless it's been explicitly enabled.
3160 $enoughToc = $this->mShowToc
&&
3161 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3163 # Allow user to stipulate that a page should have a "new section"
3164 # link added via __NEWSECTIONLINK__
3165 $mw =& MagicWord
::get( 'newsectionlink' );
3166 if( $mw->matchAndRemove( $text ) )
3167 $this->mOutput
->setNewSection( true );
3169 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3170 # override above conditions and always show TOC above first header
3171 $mw =& MagicWord
::get( 'forcetoc' );
3172 if ($mw->matchAndRemove( $text ) ) {
3173 $this->mShowToc
= true;
3177 # Never ever show TOC if no headers
3178 if( $numMatches < 1 ) {
3182 # We need this to perform operations on the HTML
3183 $sk =& $this->mOptions
->getSkin();
3187 $sectionCount = 0; # headlineCount excluding template sections
3189 # Ugh .. the TOC should have neat indentation levels which can be
3190 # passed to the skin functions. These are determined here
3194 $sublevelCount = array();
3195 $levelCount = array();
3202 foreach( $matches[3] as $headline ) {
3204 $templatetitle = '';
3205 $templatesection = 0;
3208 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3210 $templatetitle = base64_decode($mat[1]);
3211 $templatesection = 1 +
(int)base64_decode($mat[2]);
3212 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3216 $prevlevel = $level;
3217 $prevtoclevel = $toclevel;
3219 $level = $matches[1][$headlineCount];
3221 if( $doNumberHeadings ||
$enoughToc ) {
3223 if ( $level > $prevlevel ) {
3224 # Increase TOC level
3226 $sublevelCount[$toclevel] = 0;
3227 if( $toclevel<$wgMaxTocLevel ) {
3228 $toc .= $sk->tocIndent();
3231 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3232 # Decrease TOC level, find level to jump to
3234 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3235 # Can only go down to level 1
3238 for ($i = $toclevel; $i > 0; $i--) {
3239 if ( $levelCount[$i] == $level ) {
3240 # Found last matching level
3244 elseif ( $levelCount[$i] < $level ) {
3245 # Found first matching level below current level
3251 if( $toclevel<$wgMaxTocLevel ) {
3252 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3256 # No change in level, end TOC line
3257 if( $toclevel<$wgMaxTocLevel ) {
3258 $toc .= $sk->tocLineEnd();
3262 $levelCount[$toclevel] = $level;
3264 # count number of headlines for each level
3265 @$sublevelCount[$toclevel]++
;
3267 for( $i = 1; $i <= $toclevel; $i++
) {
3268 if( !empty( $sublevelCount[$i] ) ) {
3272 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3278 # The canonized header is a version of the header text safe to use for links
3279 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3280 $canonized_headline = $this->unstrip( $headline, $this->mStripState
);
3281 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState
);
3283 # Remove link placeholders by the link text.
3284 # <!--LINK number-->
3286 # link text with suffix
3287 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3288 "\$this->mLinkHolders['texts'][\$1]",
3289 $canonized_headline );
3290 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3291 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3292 $canonized_headline );
3295 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3296 $tocline = trim( $canonized_headline );
3297 # Save headline for section edit hint before it's escaped
3298 $headline_hint = trim( $canonized_headline );
3299 $canonized_headline = Sanitizer
::escapeId( $tocline );
3300 $refers[$headlineCount] = $canonized_headline;
3302 # count how many in assoc. array so we can track dupes in anchors
3303 @$refers[$canonized_headline]++
;
3304 $refcount[$headlineCount]=$refers[$canonized_headline];
3306 # Don't number the heading if it is the only one (looks silly)
3307 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3308 # the two are different if the line contains a link
3309 $headline=$numbering . ' ' . $headline;
3312 # Create the anchor for linking from the TOC to the section
3313 $anchor = $canonized_headline;
3314 if($refcount[$headlineCount] > 1 ) {
3315 $anchor .= '_' . $refcount[$headlineCount];
3317 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3318 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3320 if( $showEditLink && ( !$istemplate ||
$templatetitle !== "" ) ) {
3321 if ( empty( $head[$headlineCount] ) ) {
3322 $head[$headlineCount] = '';
3325 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3327 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle
, $sectionCount+
1, $headline_hint);
3330 # give headline the correct <h#> tag
3331 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3339 if( $toclevel<$wgMaxTocLevel ) {
3340 $toc .= $sk->tocUnindent( $toclevel - 1 );
3342 $toc = $sk->tocList( $toc );
3345 # split up and insert constructed headlines
3347 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3350 foreach( $blocks as $block ) {
3351 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3352 # This is the [edit] link that appears for the top block of text when
3353 # section editing is enabled
3355 # Disabled because it broke block formatting
3356 # For example, a bullet point in the top line
3357 # $full .= $sk->editSectionLink(0);
3360 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3361 # Top anchor now in skin
3365 if( !empty( $head[$i] ) ) {
3370 if( $this->mForceTocPosition
) {
3371 return str_replace( '<!--MWTOC-->', $toc, $full );
3378 * Return an HTML link for the "ISBN 123456" text
3381 function magicISBN( $text ) {
3382 $fname = 'Parser::magicISBN';
3383 wfProfileIn( $fname );
3385 $a = split( 'ISBN ', ' '.$text );
3386 if ( count ( $a ) < 2 ) {
3387 wfProfileOut( $fname );
3390 $text = substr( array_shift( $a ), 1);
3391 $valid = '0123456789-Xx';
3393 foreach ( $a as $x ) {
3394 # hack: don't replace inside thumbnail title/alt
3396 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3401 $isbn = $blank = '' ;
3402 while ( $x !== '' && ' ' == $x{0} ) {
3404 $x = substr( $x, 1 );
3406 if ( $x == '' ) { # blank isbn
3407 $text .= "ISBN $blank";
3410 while ( strstr( $valid, $x{0} ) != false ) {
3412 $x = substr( $x, 1 );
3414 $num = str_replace( '-', '', $isbn );
3415 $num = str_replace( ' ', '', $num );
3416 $num = str_replace( 'x', 'X', $num );
3419 $text .= "ISBN $blank$x";
3421 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Booksources' );
3422 $text .= '<a href="' .
3423 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3424 "\" class=\"internal\">ISBN $isbn</a>";
3428 wfProfileOut( $fname );
3433 * Return an HTML link for the "RFC 1234" text
3436 * @param string $text Text to be processed
3437 * @param string $keyword Magic keyword to use (default RFC)
3438 * @param string $urlmsg Interface message to use (default rfcurl)
3441 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3443 $valid = '0123456789';
3446 $a = split( $keyword, ' '.$text );
3447 if ( count ( $a ) < 2 ) {
3450 $text = substr( array_shift( $a ), 1);
3452 /* Check if keyword is preceed by [[.
3453 * This test is made here cause of the array_shift above
3454 * that prevent the test to be done in the foreach.
3456 if ( substr( $text, -2 ) == '[[' ) {
3460 foreach ( $a as $x ) {
3461 /* token might be empty if we have RFC RFC 1234 */
3467 # hack: don't replace inside thumbnail title/alt
3469 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3470 $text .= $keyword . $x;
3476 /** remove and save whitespaces in $blank */
3477 while ( $x{0} == ' ' ) {
3479 $x = substr( $x, 1 );
3482 /** remove and save the rfc number in $id */
3483 while ( strstr( $valid, $x{0} ) != false ) {
3485 $x = substr( $x, 1 );
3489 /* call back stripped spaces*/
3490 $text .= $keyword.$blank.$x;
3491 } elseif( $internal ) {
3493 $text .= $keyword.$id.$x;
3495 /* build the external link*/
3496 $url = wfMsg( $urlmsg, $id);
3497 $sk =& $this->mOptions
->getSkin();
3498 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3499 $text .= "<a href=\"{$url}\"{$la}>{$keyword}{$id}</a>{$x}";
3502 /* Check if the next RFC keyword is preceed by [[ */
3503 $internal = ( substr($x,-2) == '[[' );
3509 * Transform wiki markup when saving a page by doing \r\n -> \n
3510 * conversion, substitting signatures, {{subst:}} templates, etc.
3512 * @param string $text the text to transform
3513 * @param Title &$title the Title object for the current article
3514 * @param User &$user the User object describing the current user
3515 * @param ParserOptions $options parsing options
3516 * @param bool $clearState whether to clear the parser state first
3517 * @return string the altered wiki markup
3520 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3521 $this->mOptions
= $options;
3522 $this->mTitle
=& $title;
3523 $this->mOutputType
= OT_WIKI
;
3525 if ( $clearState ) {
3526 $this->clearState();
3529 $stripState = false;
3533 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3534 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3535 $text = $this->pstPass2( $text, $stripState, $user );
3536 $text = $this->unstrip( $text, $stripState );
3537 $text = $this->unstripNoWiki( $text, $stripState );
3542 * Pre-save transform helper function
3545 function pstPass2( $text, &$stripState, &$user ) {
3546 global $wgContLang, $wgLocaltimezone;
3548 /* Note: This is the timestamp saved as hardcoded wikitext to
3549 * the database, we use $wgContLang here in order to give
3550 * everyone the same signature and use the default one rather
3551 * than the one selected in each user's preferences.
3553 if ( isset( $wgLocaltimezone ) ) {
3554 $oldtz = getenv( 'TZ' );
3555 putenv( 'TZ='.$wgLocaltimezone );
3557 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3558 ' (' . date( 'T' ) . ')';
3559 if ( isset( $wgLocaltimezone ) ) {
3560 putenv( 'TZ='.$oldtz );
3563 # Variable replacement
3564 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3565 $text = $this->replaceVariables( $text );
3567 # Strip out <nowiki> etc. added via replaceVariables
3568 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3571 $sigText = $this->getUserSig( $user );
3572 $text = strtr( $text, array(
3574 '~~~~' => "$sigText $d",
3578 # Context links: [[|name]] and [[name (context)|]]
3580 global $wgLegalTitleChars;
3581 $tc = "[$wgLegalTitleChars]";
3582 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3584 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3585 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3587 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3588 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3589 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3590 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3592 $t = $this->mTitle
->getText();
3593 if ( preg_match( $conpat, $t, $m ) ) {
3596 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3597 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3598 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3600 if ( '' == $context ) {
3601 $text = preg_replace( $p2, '[[\\1]]', $text );
3603 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3606 # Trim trailing whitespace
3607 # __END__ tag allows for trailing
3608 # whitespace to be deliberately included
3609 $text = rtrim( $text );
3610 $mw =& MagicWord
::get( 'end' );
3611 $mw->matchAndRemove( $text );
3617 * Fetch the user's signature text, if any, and normalize to
3618 * validated, ready-to-insert wikitext.
3624 function getUserSig( &$user ) {
3625 $username = $user->getName();
3626 $nickname = $user->getOption( 'nickname' );
3627 $nickname = $nickname === '' ?
$username : $nickname;
3629 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3630 # Sig. might contain markup; validate this
3631 if( $this->validateSig( $nickname ) !== false ) {
3632 # Validated; clean up (if needed) and return it
3633 return $this->cleanSig( $nickname, true );
3635 # Failed to validate; fall back to the default
3636 $nickname = $username;
3637 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3641 // Make sure nickname doesnt get a sig in a sig
3642 $nickname = $this->cleanSigInSig( $nickname );
3644 # If we're still here, make it a link to the user page
3645 $userpage = $user->getUserPage();
3646 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3650 * Check that the user's signature contains no bad XML
3652 * @param string $text
3653 * @return mixed An expanded string, or false if invalid.
3655 function validateSig( $text ) {
3656 return( wfIsWellFormedXmlFragment( $text ) ?
$text : false );
3660 * Clean up signature text
3662 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3663 * 2) Substitute all transclusions
3665 * @param string $text
3666 * @param $parsing Whether we're cleaning (preferences save) or parsing
3667 * @return string Signature text
3669 function cleanSig( $text, $parsing = false ) {
3671 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI
: OT_MSG
);
3673 $substWord = MagicWord
::get( 'subst' );
3674 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3675 $substText = '{{' . $substWord->getSynonym( 0 );
3677 $text = preg_replace( $substRegex, $substText, $text );
3678 $text = $this->cleanSigInSig( $text );
3679 $text = $this->replaceVariables( $text );
3681 $this->clearState();
3686 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3687 * @param string $text
3688 * @return string Signature text with /~{3,5}/ removed
3690 function cleanSigInSig( $text ) {
3691 $text = preg_replace( '/~{3,5}/', '', $text );
3696 * Set up some variables which are usually set up in parse()
3697 * so that an external function can call some class members with confidence
3700 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3701 $this->mTitle
=& $title;
3702 $this->mOptions
= $options;
3703 $this->mOutputType
= $outputType;
3704 if ( $clearState ) {
3705 $this->clearState();
3710 * Transform a MediaWiki message by replacing magic variables.
3712 * @param string $text the text to transform
3713 * @param ParserOptions $options options
3714 * @return string the text with variables substituted
3717 function transformMsg( $text, $options ) {
3719 static $executing = false;
3721 $fname = "Parser::transformMsg";
3723 # Guard against infinite recursion
3729 wfProfileIn($fname);
3731 $this->mTitle
= $wgTitle;
3732 $this->mOptions
= $options;
3733 $this->mOutputType
= OT_MSG
;
3734 $this->clearState();
3735 $text = $this->replaceVariables( $text );
3738 wfProfileOut($fname);
3743 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3744 * The callback should have the following form:
3745 * function myParserHook( $text, $params, &$parser ) { ... }
3747 * Transform and return $text. Use $parser for any required context, e.g. use
3748 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3752 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3753 * @param mixed $callback The callback function (and object) to use for the tag
3755 * @return The old value of the mTagHooks array associated with the hook
3757 function setHook( $tag, $callback ) {
3758 $tag = strtolower( $tag );
3759 $oldVal = @$this->mTagHooks
[$tag];
3760 $this->mTagHooks
[$tag] = $callback;
3766 * Create a function, e.g. {{sum:1|2|3}}
3767 * The callback function should have the form:
3768 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3770 * The callback may either return the text result of the function, or an array with the text
3771 * in element 0, and a number of flags in the other elements. The names of the flags are
3772 * specified in the keys. Valid flags are:
3773 * found The text returned is valid, stop processing the template. This
3775 * nowiki Wiki markup in the return value should be escaped
3776 * noparse Unsafe HTML tags should not be stripped, etc.
3777 * noargs Don't replace triple-brace arguments in the return value
3778 * isHTML The returned text is HTML, armour it against wikitext transformation
3782 * @param mixed $id The magic word ID
3783 * @param mixed $callback The callback function (and object) to use
3784 * @param integer $flags a combination of the following flags:
3785 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3787 * @return The old callback function for this name, if any
3789 function setFunctionHook( $id, $callback, $flags = 0 ) {
3790 $oldVal = @$this->mFunctionHooks
[$id];
3791 $this->mFunctionHooks
[$id] = $callback;
3793 # Add to function cache
3794 $mw = MagicWord
::get( $id );
3796 throw new MWException( 'The calling convention to Parser::setFunctionHook() has changed, ' .
3797 'it is now required to pass a MagicWord ID as the first parameter.' );
3800 $synonyms = $mw->getSynonyms();
3801 $sensitive = intval( $mw->isCaseSensitive() );
3803 foreach ( $synonyms as $syn ) {
3805 if ( !$sensitive ) {
3806 $syn = strtolower( $syn );
3809 if ( !( $flags & SFH_NO_HASH
) ) {
3812 # Remove trailing colon
3813 if ( substr( $syn, -1, 1 ) == ':' ) {
3814 $syn = substr( $syn, 0, -1 );
3816 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
3822 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3823 * Placeholders created in Skin::makeLinkObj()
3824 * Returns an array of links found, indexed by PDBK:
3828 * $options is a bit field, RLH_FOR_UPDATE to select for update
3830 function replaceLinkHolders( &$text, $options = 0 ) {
3832 global $wgOutputReplace;
3834 $fname = 'Parser::replaceLinkHolders';
3835 wfProfileIn( $fname );
3839 $sk =& $this->mOptions
->getSkin();
3840 $linkCache =& LinkCache
::singleton();
3842 if ( !empty( $this->mLinkHolders
['namespaces'] ) ) {
3843 wfProfileIn( $fname.'-check' );
3844 $dbr =& wfGetDB( DB_SLAVE
);
3845 $page = $dbr->tableName( 'page' );
3846 $threshold = $wgUser->getOption('stubthreshold');
3849 asort( $this->mLinkHolders
['namespaces'] );
3853 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3855 $title = $this->mLinkHolders
['titles'][$key];
3857 # Skip invalid entries.
3858 # Result will be ugly, but prevents crash.
3859 if ( is_null( $title ) ) {
3862 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3864 # Check if it's a static known link, e.g. interwiki
3865 if ( $title->isAlwaysKnown() ) {
3866 $colours[$pdbk] = 1;
3867 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3868 $colours[$pdbk] = 1;
3869 $this->mOutput
->addLink( $title, $id );
3870 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3871 $colours[$pdbk] = 0;
3873 # Not in the link cache, add it to the query
3874 if ( !isset( $current ) ) {
3876 $query = "SELECT page_id, page_namespace, page_title";
3877 if ( $threshold > 0 ) {
3878 $query .= ', page_len, page_is_redirect';
3880 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3881 } elseif ( $current != $ns ) {
3883 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3888 $query .= $dbr->addQuotes( $this->mLinkHolders
['dbkeys'][$key] );
3893 if ( $options & RLH_FOR_UPDATE
) {
3894 $query .= ' FOR UPDATE';
3897 $res = $dbr->query( $query, $fname );
3899 # Fetch data and form into an associative array
3900 # non-existent = broken
3903 while ( $s = $dbr->fetchObject($res) ) {
3904 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
3905 $pdbk = $title->getPrefixedDBkey();
3906 $linkCache->addGoodLinkObj( $s->page_id
, $title );
3907 $this->mOutput
->addLink( $title, $s->page_id
);
3909 if ( $threshold > 0 ) {
3910 $size = $s->page_len
;
3911 if ( $s->page_is_redirect ||
$s->page_namespace
!= 0 ||
$size >= $threshold ) {
3912 $colours[$pdbk] = 1;
3914 $colours[$pdbk] = 2;
3917 $colours[$pdbk] = 1;
3921 wfProfileOut( $fname.'-check' );
3923 # Construct search and replace arrays
3924 wfProfileIn( $fname.'-construct' );
3925 $wgOutputReplace = array();
3926 foreach ( $this->mLinkHolders
['namespaces'] as $key => $ns ) {
3927 $pdbk = $pdbks[$key];
3928 $searchkey = "<!--LINK $key-->";
3929 $title = $this->mLinkHolders
['titles'][$key];
3930 if ( empty( $colours[$pdbk] ) ) {
3931 $linkCache->addBadLinkObj( $title );
3932 $colours[$pdbk] = 0;
3933 $this->mOutput
->addLink( $title, 0 );
3934 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3935 $this->mLinkHolders
['texts'][$key],
3936 $this->mLinkHolders
['queries'][$key] );
3937 } elseif ( $colours[$pdbk] == 1 ) {
3938 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3939 $this->mLinkHolders
['texts'][$key],
3940 $this->mLinkHolders
['queries'][$key] );
3941 } elseif ( $colours[$pdbk] == 2 ) {
3942 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3943 $this->mLinkHolders
['texts'][$key],
3944 $this->mLinkHolders
['queries'][$key] );
3947 wfProfileOut( $fname.'-construct' );
3950 wfProfileIn( $fname.'-replace' );
3952 $text = preg_replace_callback(
3953 '/(<!--LINK .*?-->)/',
3954 "wfOutputReplaceMatches",
3957 wfProfileOut( $fname.'-replace' );
3960 # Now process interwiki link holders
3961 # This is quite a bit simpler than internal links
3962 if ( !empty( $this->mInterwikiLinkHolders
['texts'] ) ) {
3963 wfProfileIn( $fname.'-interwiki' );
3964 # Make interwiki link HTML
3965 $wgOutputReplace = array();
3966 foreach( $this->mInterwikiLinkHolders
['texts'] as $key => $link ) {
3967 $title = $this->mInterwikiLinkHolders
['titles'][$key];
3968 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3971 $text = preg_replace_callback(
3972 '/<!--IWLINK (.*?)-->/',
3973 "wfOutputReplaceMatches",
3975 wfProfileOut( $fname.'-interwiki' );
3978 wfProfileOut( $fname );
3983 * Replace <!--LINK--> link placeholders with plain text of links
3984 * (not HTML-formatted).
3985 * @param string $text
3988 function replaceLinkHoldersText( $text ) {
3989 $fname = 'Parser::replaceLinkHoldersText';
3990 wfProfileIn( $fname );
3992 $text = preg_replace_callback(
3993 '/<!--(LINK|IWLINK) (.*?)-->/',
3994 array( &$this, 'replaceLinkHoldersTextCallback' ),
3997 wfProfileOut( $fname );
4002 * @param array $matches
4006 function replaceLinkHoldersTextCallback( $matches ) {
4007 $type = $matches[1];
4009 if( $type == 'LINK' ) {
4010 if( isset( $this->mLinkHolders
['texts'][$key] ) ) {
4011 return $this->mLinkHolders
['texts'][$key];
4013 } elseif( $type == 'IWLINK' ) {
4014 if( isset( $this->mInterwikiLinkHolders
['texts'][$key] ) ) {
4015 return $this->mInterwikiLinkHolders
['texts'][$key];
4022 * Tag hook handler for 'pre'.
4024 function renderPreTag( $text, $attribs, $parser ) {
4025 // Backwards-compatibility hack
4026 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4028 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4029 return wfOpenElement( 'pre', $attribs ) .
4030 wfEscapeHTMLTagsOnly( $content ) .
4035 * Renders an image gallery from a text with one line per image.
4036 * text labels may be given by using |-style alternative text. E.g.
4037 * Image:one.jpg|The number "1"
4038 * Image:tree.jpg|A tree
4039 * given as text will return the HTML of a gallery with two images,
4040 * labeled 'The number "1"' and
4043 function renderImageGallery( $text, $params ) {
4044 $ig = new ImageGallery();
4045 $ig->setShowBytes( false );
4046 $ig->setShowFilename( false );
4048 $ig->useSkin( $this->mOptions
->getSkin() );
4050 if( isset( $params['caption'] ) )
4051 $ig->setCaption( $params['caption'] );
4053 $lines = explode( "\n", $text );
4054 foreach ( $lines as $line ) {
4055 # match lines like these:
4056 # Image:someimage.jpg|This is some image
4057 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4059 if ( count( $matches ) == 0 ) {
4062 $tp = Title
::newFromText( $matches[1] );
4064 if( is_null( $nt ) ) {
4065 # Bogus title. Ignore these so we don't bomb out later.
4068 if ( isset( $matches[3] ) ) {
4069 $label = $matches[3];
4074 $pout = $this->parse( $label,
4077 false, // Strip whitespace...?
4078 false // Don't clear state!
4080 $html = $pout->getText();
4082 $ig->add( new Image( $nt ), $html );
4084 # Only add real images (bug #5586)
4085 if ( $nt->getNamespace() == NS_IMAGE
) {
4086 $this->mOutput
->addImage( $nt->getDBkey() );
4089 return $ig->toHTML();
4093 * Parse image options text and use it to make an image
4095 function makeImage( &$nt, $options ) {
4096 global $wgUseImageResize;
4100 # Check if the options text is of the form "options|alt text"
4102 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4103 # * left no resizing, just left align. label is used for alt= only
4104 # * right same, but right aligned
4105 # * none same, but not aligned
4106 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4107 # * center center the image
4108 # * framed Keep original image size, no magnify-button.
4110 $part = explode( '|', $options);
4112 $mwThumb =& MagicWord
::get( 'img_thumbnail' );
4113 $mwManualThumb =& MagicWord
::get( 'img_manualthumb' );
4114 $mwLeft =& MagicWord
::get( 'img_left' );
4115 $mwRight =& MagicWord
::get( 'img_right' );
4116 $mwNone =& MagicWord
::get( 'img_none' );
4117 $mwWidth =& MagicWord
::get( 'img_width' );
4118 $mwCenter =& MagicWord
::get( 'img_center' );
4119 $mwFramed =& MagicWord
::get( 'img_framed' );
4122 $width = $height = $framed = $thumb = false;
4123 $manual_thumb = '' ;
4125 foreach( $part as $key => $val ) {
4126 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4128 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4129 # use manually specified thumbnail
4131 $manual_thumb = $match;
4132 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4133 # remember to set an alignment, don't render immediately
4135 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4136 # remember to set an alignment, don't render immediately
4138 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4139 # remember to set an alignment, don't render immediately
4141 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4142 # remember to set an alignment, don't render immediately
4144 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4145 wfDebug( "img_width match: $match\n" );
4146 # $match is the image width in pixels
4147 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4148 $width = intval( $m[1] );
4149 $height = intval( $m[2] );
4151 $width = intval($match);
4153 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4159 # Strip bad stuff out of the alt text
4160 $alt = $this->replaceLinkHoldersText( $caption );
4162 # make sure there are no placeholders in thumbnail attributes
4163 # that are later expanded to html- so expand them now and
4165 $alt = $this->unstrip($alt, $this->mStripState
);
4166 $alt = Sanitizer
::stripAllTags( $alt );
4168 # Linker does the rest
4169 $sk =& $this->mOptions
->getSkin();
4170 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4174 * Set a flag in the output object indicating that the content is dynamic and
4175 * shouldn't be cached.
4177 function disableCache() {
4178 wfDebug( "Parser output marked as uncacheable.\n" );
4179 $this->mOutput
->mCacheTime
= -1;
4183 * Callback from the Sanitizer for expanding items found in HTML attribute
4184 * values, so they can be safely tested and escaped.
4185 * @param string $text
4186 * @param array $args
4190 function attributeStripCallback( &$text, $args ) {
4191 $text = $this->replaceVariables( $text, $args );
4192 $text = $this->unstripForHTML( $text );
4196 function unstripForHTML( $text ) {
4197 $text = $this->unstrip( $text, $this->mStripState
);
4198 $text = $this->unstripNoWiki( $text, $this->mStripState
);
4206 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4207 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4208 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4214 function getTags() { return array_keys( $this->mTagHooks
); }
4219 * Break wikitext input into sections, and either pull or replace
4220 * some particular section's text.
4222 * External callers should use the getSection and replaceSection methods.
4224 * @param $text Page wikitext
4225 * @param $section Numbered section. 0 pulls the text before the first
4226 * heading; other numbers will pull the given section
4227 * along with its lower-level subsections.
4228 * @param $mode One of "get" or "replace"
4229 * @param $newtext Replacement text for section data.
4230 * @return string for "get", the extracted section text.
4231 * for "replace", the whole page with the section replaced.
4233 private function extractSections( $text, $section, $mode, $newtext='' ) {
4234 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4235 # comments to be stripped as well)
4236 $striparray = array();
4238 $oldOutputType = $this->mOutputType
;
4239 $oldOptions = $this->mOptions
;
4240 $this->mOptions
= new ParserOptions();
4241 $this->mOutputType
= OT_WIKI
;
4243 $striptext = $this->strip( $text, $striparray, true );
4245 $this->mOutputType
= $oldOutputType;
4246 $this->mOptions
= $oldOptions;
4248 # now that we can be sure that no pseudo-sections are in the source,
4249 # split it up by section
4250 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4251 $comment = "(?:$uniq-!--.*?QINU)";
4256 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4258 (=+) # Should this be limited to 6?
4259 .+? # Section title...
4260 \\2 # Ending = count must match start
4267 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4274 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4275 (=+) # Should this be limited to 6?
4276 .+? # Section title...
4277 \\2 # Ending = count must match start
4278 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4287 PREG_SPLIT_DELIM_CAPTURE
);
4289 if( $mode == "get" ) {
4290 if( $section == 0 ) {
4291 // "Section 0" returns the content before any other section.
4296 } elseif( $mode == "replace" ) {
4297 if( $section == 0 ) {
4298 $rv = $newtext . "\n\n";
4307 for( $index = 1; $index < count( $secs ); ) {
4308 $headerLine = $secs[$index++
];
4309 if( $secs[$index] ) {
4311 $headerLevel = strlen( $secs[$index++
] );
4315 $headerLevel = intval( $secs[$index++
] );
4317 $content = $secs[$index++
];
4320 if( $mode == "get" ) {
4321 if( $count == $section ) {
4322 $rv = $headerLine . $content;
4323 $sectionLevel = $headerLevel;
4324 } elseif( $count > $section ) {
4325 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4326 $rv .= $headerLine . $content;
4328 // Broke out to a higher-level section
4332 } elseif( $mode == "replace" ) {
4333 if( $count < $section ) {
4334 $rv .= $headerLine . $content;
4335 } elseif( $count == $section ) {
4336 $rv .= $newtext . "\n\n";
4337 $sectionLevel = $headerLevel;
4338 } elseif( $count > $section ) {
4339 if( $headerLevel <= $sectionLevel ) {
4340 // Passed the section's sub-parts.
4344 $rv .= $headerLine . $content;
4349 # reinsert stripped tags
4350 $rv = $this->unstrip( $rv, $striparray );
4351 $rv = $this->unstripNoWiki( $rv, $striparray );
4357 * This function returns the text of a section, specified by a number ($section).
4358 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4359 * the first section before any such heading (section 0).
4361 * If a section contains subsections, these are also returned.
4363 * @param $text String: text to look in
4364 * @param $section Integer: section number
4365 * @return string text of the requested section
4367 function getSection( $text, $section ) {
4368 return $this->extractSections( $text, $section, "get" );
4371 function replaceSection( $oldtext, $section, $text ) {
4372 return $this->extractSections( $oldtext, $section, "replace", $text );
4379 * @package MediaWiki
4383 var $mText, # The output text
4384 $mLanguageLinks, # List of the full text of language links, in the order they appear
4385 $mCategories, # Map of category names to sort keys
4386 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4387 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4388 $mVersion, # Compatibility check
4389 $mTitleText, # title text of the chosen language variant
4390 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4391 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4392 $mImages, # DB keys of the images used, in the array key only
4393 $mExternalLinks, # External link URLs, in the key only
4394 $mHTMLtitle, # Display HTML title
4395 $mSubtitle, # Additional subtitle
4396 $mNewSection, # Show a new section link?
4397 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4399 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4400 $containsOldMagic = false, $titletext = '' )
4402 $this->mText
= $text;
4403 $this->mLanguageLinks
= $languageLinks;
4404 $this->mCategories
= $categoryLinks;
4405 $this->mContainsOldMagic
= $containsOldMagic;
4406 $this->mCacheTime
= '';
4407 $this->mVersion
= MW_PARSER_VERSION
;
4408 $this->mTitleText
= $titletext;
4409 $this->mLinks
= array();
4410 $this->mTemplates
= array();
4411 $this->mImages
= array();
4412 $this->mExternalLinks
= array();
4413 $this->mHTMLtitle
= "" ;
4414 $this->mSubtitle
= "" ;
4415 $this->mNewSection
= false;
4416 $this->mNoGallery
= false;
4419 function getText() { return $this->mText
; }
4420 function &getLanguageLinks() { return $this->mLanguageLinks
; }
4421 function getCategoryLinks() { return array_keys( $this->mCategories
); }
4422 function &getCategories() { return $this->mCategories
; }
4423 function getCacheTime() { return $this->mCacheTime
; }
4424 function getTitleText() { return $this->mTitleText
; }
4425 function &getLinks() { return $this->mLinks
; }
4426 function &getTemplates() { return $this->mTemplates
; }
4427 function &getImages() { return $this->mImages
; }
4428 function &getExternalLinks() { return $this->mExternalLinks
; }
4429 function getNoGallery() { return $this->mNoGallery
; }
4431 function containsOldMagic() { return $this->mContainsOldMagic
; }
4432 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
4433 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
4434 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
4435 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic
, $com ); }
4436 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime
, $t ); }
4437 function setTitleText( $t ) { return wfSetVar ($this->mTitleText
, $t); }
4439 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
4440 function addImage( $name ) { $this->mImages
[$name] = 1; }
4441 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
4442 function addExternalLink( $url ) { $this->mExternalLinks
[$url] = 1; }
4444 function setNewSection( $value ) {
4445 $this->mNewSection
= (bool)$value;
4447 function getNewSection() {
4448 return (bool)$this->mNewSection
;
4451 function addLink( $title, $id ) {
4452 $ns = $title->getNamespace();
4453 $dbk = $title->getDBkey();
4454 if ( !isset( $this->mLinks
[$ns] ) ) {
4455 $this->mLinks
[$ns] = array();
4457 $this->mLinks
[$ns][$dbk] = $id;
4460 function addTemplate( $title, $id ) {
4461 $ns = $title->getNamespace();
4462 $dbk = $title->getDBkey();
4463 if ( !isset( $this->mTemplates
[$ns] ) ) {
4464 $this->mTemplates
[$ns] = array();
4466 $this->mTemplates
[$ns][$dbk] = $id;
4470 * Return true if this cached output object predates the global or
4471 * per-article cache invalidation timestamps, or if it comes from
4472 * an incompatible older version.
4474 * @param string $touched the affected article's last touched timestamp
4478 function expired( $touched ) {
4479 global $wgCacheEpoch;
4480 return $this->getCacheTime() == -1 ||
// parser says it's uncacheable
4481 $this->getCacheTime() < $touched ||
4482 $this->getCacheTime() <= $wgCacheEpoch ||
4483 !isset( $this->mVersion
) ||
4484 version_compare( $this->mVersion
, MW_PARSER_VERSION
, "lt" );
4489 * Set options of the Parser
4491 * @package MediaWiki
4495 # All variables are private
4496 var $mUseTeX; # Use texvc to expand <math> tags
4497 var $mUseDynamicDates; # Use DateFormatter to format dates
4498 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4499 var $mAllowExternalImages; # Allow external images inline
4500 var $mAllowExternalImagesFrom; # If not, any exception?
4501 var $mSkin; # Reference to the preferred skin
4502 var $mDateFormat; # Date format index
4503 var $mEditSection; # Create "edit section" links
4504 var $mNumberHeadings; # Automatically number headings
4505 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4506 var $mTidy; # Ask for tidy cleanup
4507 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4509 var $mUser; # Stored user object, just used to initialise the skin
4511 function getUseTeX() { return $this->mUseTeX
; }
4512 function getUseDynamicDates() { return $this->mUseDynamicDates
; }
4513 function getInterwikiMagic() { return $this->mInterwikiMagic
; }
4514 function getAllowExternalImages() { return $this->mAllowExternalImages
; }
4515 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom
; }
4516 function getDateFormat() { return $this->mDateFormat
; }
4517 function getEditSection() { return $this->mEditSection
; }
4518 function getNumberHeadings() { return $this->mNumberHeadings
; }
4519 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion
; }
4520 function getTidy() { return $this->mTidy
; }
4521 function getInterfaceMessage() { return $this->mInterfaceMessage
; }
4523 function &getSkin() {
4524 if ( !isset( $this->mSkin
) ) {
4525 $this->mSkin
= $this->mUser
->getSkin();
4527 return $this->mSkin
;
4530 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX
, $x ); }
4531 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates
, $x ); }
4532 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic
, $x ); }
4533 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages
, $x ); }
4534 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom
, $x ); }
4535 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat
, $x ); }
4536 function setEditSection( $x ) { return wfSetVar( $this->mEditSection
, $x ); }
4537 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings
, $x ); }
4538 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion
, $x ); }
4539 function setTidy( $x ) { return wfSetVar( $this->mTidy
, $x); }
4540 function setSkin( &$x ) { $this->mSkin
=& $x; }
4541 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage
, $x); }
4543 function ParserOptions( $user = null ) {
4544 $this->initialiseFromUser( $user );
4548 * Get parser options
4551 static function newFromUser( $user ) {
4552 return new ParserOptions( $user );
4555 /** Get user options */
4556 function initialiseFromUser( $userInput ) {
4557 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4558 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4559 $fname = 'ParserOptions::initialiseFromUser';
4560 wfProfileIn( $fname );
4561 if ( !$userInput ) {
4563 if ( isset( $wgUser ) ) {
4567 $user->setLoaded( true );
4570 $user =& $userInput;
4573 $this->mUser
= $user;
4575 $this->mUseTeX
= $wgUseTeX;
4576 $this->mUseDynamicDates
= $wgUseDynamicDates;
4577 $this->mInterwikiMagic
= $wgInterwikiMagic;
4578 $this->mAllowExternalImages
= $wgAllowExternalImages;
4579 $this->mAllowExternalImagesFrom
= $wgAllowExternalImagesFrom;
4580 $this->mSkin
= null; # Deferred
4581 $this->mDateFormat
= $user->getOption( 'date' );
4582 $this->mEditSection
= true;
4583 $this->mNumberHeadings
= $user->getOption( 'numberheadings' );
4584 $this->mAllowSpecialInclusion
= $wgAllowSpecialInclusion;
4585 $this->mTidy
= false;
4586 $this->mInterfaceMessage
= false;
4587 wfProfileOut( $fname );
4592 * Callback function used by Parser::replaceLinkHolders()
4593 * to substitute link placeholders.
4595 function &wfOutputReplaceMatches( $matches ) {
4596 global $wgOutputReplace;
4597 return $wgOutputReplace[$matches[1]];
4601 * Return the total number of articles
4603 function wfNumberOfArticles() {
4604 global $wgNumberOfArticles;
4607 return $wgNumberOfArticles;
4611 * Return the number of files
4613 function wfNumberOfFiles() {
4614 $fname = 'wfNumberOfFiles';
4616 wfProfileIn( $fname );
4617 $dbr =& wfGetDB( DB_SLAVE
);
4618 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4619 wfProfileOut( $fname );
4625 * Return the number of user accounts
4628 function wfNumberOfUsers() {
4629 wfProfileIn( 'wfNumberOfUsers' );
4630 $dbr =& wfGetDB( DB_SLAVE
);
4631 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4632 wfProfileOut( 'wfNumberOfUsers' );
4637 * Return the total number of pages
4640 function wfNumberOfPages() {
4641 wfProfileIn( 'wfNumberOfPages' );
4642 $dbr =& wfGetDB( DB_SLAVE
);
4643 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4644 wfProfileOut( 'wfNumberOfPages' );
4649 * Return the total number of admins
4653 function wfNumberOfAdmins() {
4654 static $admins = -1;
4655 wfProfileIn( 'wfNumberOfAdmins' );
4656 if( $admins == -1 ) {
4657 $dbr =& wfGetDB( DB_SLAVE
);
4658 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4660 wfProfileOut( 'wfNumberOfAdmins' );
4661 return (int)$admins;
4665 * Count the number of pages in a particular namespace
4667 * @param $ns Namespace
4670 function wfPagesInNs( $ns ) {
4671 static $pageCount = array();
4672 wfProfileIn( 'wfPagesInNs' );
4673 if( !isset( $pageCount[$ns] ) ) {
4674 $dbr =& wfGetDB( DB_SLAVE
);
4675 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4677 wfProfileOut( 'wfPagesInNs' );
4678 return (int)$pageCount[$ns];
4682 * Get various statistics from the database
4685 function wfLoadSiteStats() {
4686 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4687 $fname = 'wfLoadSiteStats';
4689 if ( -1 != $wgNumberOfArticles ) return;
4690 $dbr =& wfGetDB( DB_SLAVE
);
4691 $s = $dbr->selectRow( 'site_stats',
4692 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4693 array( 'ss_row_id' => 1 ), $fname
4696 if ( $s === false ) {
4699 $wgTotalViews = $s->ss_total_views
;
4700 $wgTotalEdits = $s->ss_total_edits
;
4701 $wgNumberOfArticles = $s->ss_good_articles
;
4707 * Basically replacing " > and < with HTML entities ( ", >, <)
4709 * @param $in String: text that might contain HTML tags.
4710 * @return string Escaped string
4712 function wfEscapeHTMLTagsOnly( $in ) {
4714 array( '"', '>', '<' ),
4715 array( '"', '>', '<' ),