hook point for injecting fields into edit form
[mediawiki.git] / includes / Parser.php
blob50e86ac41f3f4baf8c2aa50bd53e437fa8e4b9df
1 <?php
2 /**
3 * File for Parser and related classes
5 * @addtogroup Parser
6 */
8 /**
9 * Update this version number when the ParserOutput format
10 * changes in an incompatible way, so the parser cache
11 * can automatically discard old data.
13 define( 'MW_PARSER_VERSION', '1.6.1' );
15 define( 'RLH_FOR_UPDATE', 1 );
17 # Allowed values for $mOutputType
18 define( 'OT_HTML', 1 );
19 define( 'OT_WIKI', 2 );
20 define( 'OT_MSG' , 3 );
21 define( 'OT_PREPROCESS', 4 );
23 # Flags for setFunctionHook
24 define( 'SFH_NO_HASH', 1 );
26 # string parameter for extractTags which will cause it
27 # to strip HTML comments in addition to regular
28 # <XML>-style tags. This should not be anything we
29 # may want to use in wikisyntax
30 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
32 # Constants needed for external link processing
33 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
34 # Everything except bracket, space, or control characters
35 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
36 # Including space, but excluding newlines
37 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
38 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
39 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
40 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
41 EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
42 define( 'EXT_IMAGE_REGEX',
43 '/^('.HTTP_PROTOCOLS.')'. # Protocol
44 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
45 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
48 // State constants for the definition list colon extraction
49 define( 'MW_COLON_STATE_TEXT', 0 );
50 define( 'MW_COLON_STATE_TAG', 1 );
51 define( 'MW_COLON_STATE_TAGSTART', 2 );
52 define( 'MW_COLON_STATE_CLOSETAG', 3 );
53 define( 'MW_COLON_STATE_TAGSLASH', 4 );
54 define( 'MW_COLON_STATE_COMMENT', 5 );
55 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
56 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
58 /**
59 * PHP Parser
61 * Processes wiki markup
63 * <pre>
64 * There are four main entry points into the Parser class:
65 * parse()
66 * produces HTML output
67 * preSaveTransform().
68 * produces altered wiki markup.
69 * transformMsg()
70 * performs brace substitution on MediaWiki messages
71 * preprocess()
72 * removes HTML comments and expands templates
74 * Globals used:
75 * objects: $wgLang, $wgContLang
77 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
79 * settings:
80 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
81 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
82 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
83 * $wgMaxArticleSize*
85 * * only within ParserOptions
86 * </pre>
89 class Parser
91 const VERSION = MW_PARSER_VERSION;
92 /**#@+
93 * @private
95 # Persistent:
96 var $mTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mIncludeSizes, $mDefaultSort;
103 var $mTemplates, // cache of already loaded templates, avoids
104 // multiple SQL queries for the same string
105 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
106 // in this path. Used for loop detection.
108 # Temporary
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions, // ParserOptions object
111 $mTitle, // Title context, used for self-link rendering and similar things
112 $mOutputType, // Output type, one of the OT_xxx constants
113 $ot, // Shortcut alias, see setOutputType()
114 $mRevisionId, // ID to display in {{REVISIONID}} tags
115 $mRevisionTimestamp, // The timestamp of the specified revision ID
116 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
118 /**#@-*/
121 * Constructor
123 * @public
125 function Parser() {
126 $this->mTagHooks = array();
127 $this->mFunctionHooks = array();
128 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
129 $this->mFirstCall = true;
133 * Do various kinds of initialisation on the first call of the parser
135 function firstCallInit() {
136 if ( !$this->mFirstCall ) {
137 return;
140 wfProfileIn( __METHOD__ );
141 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
143 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
145 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH );
146 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH );
147 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH );
148 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH );
149 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH );
150 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH );
151 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH );
152 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH );
153 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH );
154 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH );
155 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH );
156 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH );
157 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH );
158 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH );
159 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH );
160 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH );
161 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH );
162 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH );
163 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH );
164 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH );
165 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH );
166 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH );
167 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH );
168 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
169 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), 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();
179 $this->mFirstCall = false;
180 wfProfileOut( __METHOD__ );
184 * Clear Parser state
186 * @private
188 function clearState() {
189 wfProfileIn( __METHOD__ );
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 = new StripState;
199 $this->mArgStack = array();
200 $this->mInPre = false;
201 $this->mInterwikiLinkHolders = array(
202 'texts' => array(),
203 'titles' => array()
205 $this->mLinkHolders = array(
206 'namespaces' => array(),
207 'dbkeys' => array(),
208 'queries' => array(),
209 'texts' => array(),
210 'titles' => array()
212 $this->mRevisionTimestamp = $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
219 * string constructs.
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;
229 $this->mIncludeSizes = array(
230 'pre-expand' => 0,
231 'post-expand' => 0,
232 'arg' => 0
234 $this->mDefaultSort = false;
236 wfRunHooks( 'ParserClearState', array( &$this ) );
237 wfProfileOut( __METHOD__ );
240 function setOutputType( $ot ) {
241 $this->mOutputType = $ot;
242 // Shortcut alias
243 $this->ot = array(
244 'html' => $ot == OT_HTML,
245 'wiki' => $ot == OT_WIKI,
246 'msg' => $ot == OT_MSG,
247 'pre' => $ot == OT_PREPROCESS,
252 * Accessor for mUniqPrefix.
254 * @public
256 function uniqPrefix() {
257 return $this->mUniqPrefix;
261 * Convert wikitext to HTML
262 * Do not call this function recursively.
264 * @param string $text Text we want to parse
265 * @param Title &$title A title object
266 * @param array $options
267 * @param boolean $linestart
268 * @param boolean $clearState
269 * @param int $revid number to pass in {{REVISIONID}}
270 * @return ParserOutput a ParserOutput
272 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
274 * First pass--just handle <nowiki> sections, pass the rest off
275 * to internalParse() which does all the real work.
278 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
279 $fname = 'Parser::parse-' . wfGetCaller();
280 wfProfileIn( __METHOD__ );
281 wfProfileIn( $fname );
283 if ( $clearState ) {
284 $this->clearState();
287 $this->mOptions = $options;
288 $this->mTitle =& $title;
289 $oldRevisionId = $this->mRevisionId;
290 $oldRevisionTimestamp = $this->mRevisionTimestamp;
291 if( $revid !== null ) {
292 $this->mRevisionId = $revid;
293 $this->mRevisionTimestamp = null;
295 $this->setOutputType( OT_HTML );
296 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
297 $text = $this->strip( $text, $this->mStripState );
298 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
299 $text = $this->internalParse( $text );
300 $text = $this->mStripState->unstripGeneral( $text );
302 # Clean up special characters, only run once, next-to-last before doBlockLevels
303 $fixtags = array(
304 # french spaces, last one Guillemet-left
305 # only if there is something before the space
306 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
307 # french spaces, Guillemet-right
308 '/(\\302\\253) /' => '\\1&nbsp;',
310 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
312 # only once and last
313 $text = $this->doBlockLevels( $text, $linestart );
315 $this->replaceLinkHolders( $text );
317 # the position of the parserConvert() call should not be changed. it
318 # assumes that the links are all replaced and the only thing left
319 # is the <nowiki> mark.
320 # Side-effects: this calls $this->mOutput->setTitleText()
321 $text = $wgContLang->parserConvert( $text, $this );
323 $text = $this->mStripState->unstripNoWiki( $text );
325 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
327 $text = Sanitizer::normalizeCharReferences( $text );
329 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
330 $text = Parser::tidy($text);
331 } else {
332 # attempt to sanitize at least some nesting problems
333 # (bug #2702 and quite a few others)
334 $tidyregs = array(
335 # ''Something [http://www.cool.com cool''] -->
336 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
337 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
338 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
339 # fix up an anchor inside another anchor, only
340 # at least for a single single nested link (bug 3695)
341 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
342 '\\1\\2</a>\\3</a>\\1\\4</a>',
343 # fix div inside inline elements- doBlockLevels won't wrap a line which
344 # contains a div, so fix it up here; replace
345 # div with escaped text
346 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
347 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
348 # remove empty italic or bold tag pairs, some
349 # introduced by rules above
350 '/<([bi])><\/\\1>/' => '',
353 $text = preg_replace(
354 array_keys( $tidyregs ),
355 array_values( $tidyregs ),
356 $text );
359 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
361 # Information on include size limits, for the benefit of users who try to skirt them
362 if ( max( $this->mIncludeSizes ) > 1000 ) {
363 $max = $this->mOptions->getMaxIncludeSize();
364 $text .= "<!-- \n" .
365 "Pre-expand include size: {$this->mIncludeSizes['pre-expand']} bytes\n" .
366 "Post-expand include size: {$this->mIncludeSizes['post-expand']} bytes\n" .
367 "Template argument size: {$this->mIncludeSizes['arg']} bytes\n" .
368 "Maximum: $max bytes\n" .
369 "-->\n";
371 $this->mOutput->setText( $text );
372 $this->mRevisionId = $oldRevisionId;
373 $this->mRevisionTimestamp = $oldRevisionTimestamp;
374 wfProfileOut( $fname );
375 wfProfileOut( __METHOD__ );
377 return $this->mOutput;
381 * Recursive parser entry point that can be called from an extension tag
382 * hook.
384 function recursiveTagParse( $text ) {
385 wfProfileIn( __METHOD__ );
386 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
387 $text = $this->strip( $text, $this->mStripState );
388 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
389 $text = $this->internalParse( $text );
390 wfProfileOut( __METHOD__ );
391 return $text;
395 * Expand templates and variables in the text, producing valid, static wikitext.
396 * Also removes comments.
398 function preprocess( $text, $title, $options ) {
399 wfProfileIn( __METHOD__ );
400 $this->clearState();
401 $this->setOutputType( OT_PREPROCESS );
402 $this->mOptions = $options;
403 $this->mTitle = $title;
404 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
405 $text = $this->strip( $text, $this->mStripState );
406 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
407 if ( $this->mOptions->getRemoveComments() ) {
408 $text = Sanitizer::removeHTMLcomments( $text );
410 $text = $this->replaceVariables( $text );
411 $text = $this->mStripState->unstripBoth( $text );
412 wfProfileOut( __METHOD__ );
413 return $text;
417 * Get a random string
419 * @private
420 * @static
422 function getRandomString() {
423 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
426 function &getTitle() { return $this->mTitle; }
427 function getOptions() { return $this->mOptions; }
429 function getFunctionLang() {
430 global $wgLang, $wgContLang;
431 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
435 * Replaces all occurrences of HTML-style comments and the given tags
436 * in the text with a random marker and returns teh next text. The output
437 * parameter $matches will be an associative array filled with data in
438 * the form:
439 * 'UNIQ-xxxxx' => array(
440 * 'element',
441 * 'tag content',
442 * array( 'param' => 'x' ),
443 * '<element param="x">tag content</element>' ) )
445 * @param $elements list of element names. Comments are always extracted.
446 * @param $text Source text string.
447 * @param $uniq_prefix
449 * @private
450 * @static
452 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
453 static $n = 1;
454 $stripped = '';
455 $matches = array();
457 $taglist = implode( '|', $elements );
458 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
460 while ( '' != $text ) {
461 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
462 $stripped .= $p[0];
463 if( count( $p ) < 5 ) {
464 break;
466 if( count( $p ) > 5 ) {
467 // comment
468 $element = $p[4];
469 $attributes = '';
470 $close = '';
471 $inside = $p[5];
472 } else {
473 // tag
474 $element = $p[1];
475 $attributes = $p[2];
476 $close = $p[3];
477 $inside = $p[4];
480 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++) . '-QINU';
481 $stripped .= $marker;
483 if ( $close === '/>' ) {
484 // Empty element tag, <tag />
485 $content = null;
486 $text = $inside;
487 $tail = null;
488 } else {
489 if( $element == '!--' ) {
490 $end = '/(-->)/';
491 } else {
492 $end = "/(<\\/$element\\s*>)/i";
494 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
495 $content = $q[0];
496 if( count( $q ) < 3 ) {
497 # No end tag -- let it run out to the end of the text.
498 $tail = '';
499 $text = '';
500 } else {
501 $tail = $q[1];
502 $text = $q[2];
506 $matches[$marker] = array( $element,
507 $content,
508 Sanitizer::decodeTagAttributes( $attributes ),
509 "<$element$attributes$close$content$tail" );
511 return $stripped;
515 * Strips and renders nowiki, pre, math, hiero
516 * If $render is set, performs necessary rendering operations on plugins
517 * Returns the text, and fills an array with data needed in unstrip()
519 * @param StripState $state
521 * @param bool $stripcomments when set, HTML comments <!-- like this -->
522 * will be stripped in addition to other tags. This is important
523 * for section editing, where these comments cause confusion when
524 * counting the sections in the wikisource
526 * @param array dontstrip contains tags which should not be stripped;
527 * used to prevent stipping of <gallery> when saving (fixes bug 2700)
529 * @private
531 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
532 global $wgContLang;
533 wfProfileIn( __METHOD__ );
534 $render = ($this->mOutputType == OT_HTML);
536 $uniq_prefix = $this->mUniqPrefix;
537 $commentState = new ReplacementArray;
538 $nowikiItems = array();
539 $generalItems = array();
541 $elements = array_merge(
542 array( 'nowiki', 'gallery' ),
543 array_keys( $this->mTagHooks ) );
544 global $wgRawHtml;
545 if( $wgRawHtml ) {
546 $elements[] = 'html';
548 if( $this->mOptions->getUseTeX() ) {
549 $elements[] = 'math';
552 # Removing $dontstrip tags from $elements list (currently only 'gallery', fixing bug 2700)
553 foreach ( $elements AS $k => $v ) {
554 if ( !in_array ( $v , $dontstrip ) ) continue;
555 unset ( $elements[$k] );
558 $matches = array();
559 $text = Parser::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
561 foreach( $matches as $marker => $data ) {
562 list( $element, $content, $params, $tag ) = $data;
563 if( $render ) {
564 $tagName = strtolower( $element );
565 wfProfileIn( __METHOD__."-render-$tagName" );
566 switch( $tagName ) {
567 case '!--':
568 // Comment
569 if( substr( $tag, -3 ) == '-->' ) {
570 $output = $tag;
571 } else {
572 // Unclosed comment in input.
573 // Close it so later stripping can remove it
574 $output = "$tag-->";
576 break;
577 case 'html':
578 if( $wgRawHtml ) {
579 $output = $content;
580 break;
582 // Shouldn't happen otherwise. :)
583 case 'nowiki':
584 $output = Xml::escapeTagsOnly( $content );
585 break;
586 case 'math':
587 $output = $wgContLang->armourMath( MathRenderer::renderMath( $content ) );
588 break;
589 case 'gallery':
590 $output = $this->renderImageGallery( $content, $params );
591 break;
592 default:
593 if( isset( $this->mTagHooks[$tagName] ) ) {
594 $output = call_user_func_array( $this->mTagHooks[$tagName],
595 array( $content, $params, $this ) );
596 } else {
597 throw new MWException( "Invalid call hook $element" );
600 wfProfileOut( __METHOD__."-render-$tagName" );
601 } else {
602 // Just stripping tags; keep the source
603 $output = $tag;
606 // Unstrip the output, to support recursive strip() calls
607 $output = $state->unstripBoth( $output );
609 if( !$stripcomments && $element == '!--' ) {
610 $commentState->setPair( $marker, $output );
611 } elseif ( $element == 'html' || $element == 'nowiki' ) {
612 $nowikiItems[$marker] = $output;
613 } else {
614 $generalItems[$marker] = $output;
617 # Add the new items to the state
618 # We do this after the loop instead of during it to avoid slowing
619 # down the recursive unstrip
620 $state->nowiki->mergeArray( $nowikiItems );
621 $state->general->mergeArray( $generalItems );
623 # Unstrip comments unless explicitly told otherwise.
624 # (The comments are always stripped prior to this point, so as to
625 # not invoke any extension tags / parser hooks contained within
626 # a comment.)
627 if ( !$stripcomments ) {
628 // Put them all back and forget them
629 $text = $commentState->replace( $text );
632 wfProfileOut( __METHOD__ );
633 return $text;
637 * Restores pre, math, and other extensions removed by strip()
639 * always call unstripNoWiki() after this one
640 * @private
641 * @deprecated use $this->mStripState->unstrip()
643 function unstrip( $text, $state ) {
644 return $state->unstripGeneral( $text );
648 * Always call this after unstrip() to preserve the order
650 * @private
651 * @deprecated use $this->mStripState->unstrip()
653 function unstripNoWiki( $text, $state ) {
654 return $state->unstripNoWiki( $text );
658 * @deprecated use $this->mStripState->unstripBoth()
660 function unstripForHTML( $text ) {
661 return $this->mStripState->unstripBoth( $text );
665 * Add an item to the strip state
666 * Returns the unique tag which must be inserted into the stripped text
667 * The tag will be replaced with the original text in unstrip()
669 * @private
671 function insertStripItem( $text, &$state ) {
672 $rnd = $this->mUniqPrefix . '-item' . Parser::getRandomString();
673 $state->general->setPair( $rnd, $text );
674 return $rnd;
678 * Interface with html tidy, used if $wgUseTidy = true.
679 * If tidy isn't able to correct the markup, the original will be
680 * returned in all its glory with a warning comment appended.
682 * Either the external tidy program or the in-process tidy extension
683 * will be used depending on availability. Override the default
684 * $wgTidyInternal setting to disable the internal if it's not working.
686 * @param string $text Hideous HTML input
687 * @return string Corrected HTML output
688 * @public
689 * @static
691 function tidy( $text ) {
692 global $wgTidyInternal;
693 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
694 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
695 '<head><title>test</title></head><body>'.$text.'</body></html>';
696 if( $wgTidyInternal ) {
697 $correctedtext = Parser::internalTidy( $wrappedtext );
698 } else {
699 $correctedtext = Parser::externalTidy( $wrappedtext );
701 if( is_null( $correctedtext ) ) {
702 wfDebug( "Tidy error detected!\n" );
703 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
705 return $correctedtext;
709 * Spawn an external HTML tidy process and get corrected markup back from it.
711 * @private
712 * @static
714 function externalTidy( $text ) {
715 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
716 $fname = 'Parser::externalTidy';
717 wfProfileIn( $fname );
719 $cleansource = '';
720 $opts = ' -utf8';
722 $descriptorspec = array(
723 0 => array('pipe', 'r'),
724 1 => array('pipe', 'w'),
725 2 => array('file', '/dev/null', 'a') // FIXME: this line in UNIX-specific, it generates a warning on Windows, because /dev/null is not a valid Windows file.
727 $pipes = array();
728 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
729 if (is_resource($process)) {
730 // Theoretically, this style of communication could cause a deadlock
731 // here. If the stdout buffer fills up, then writes to stdin could
732 // block. This doesn't appear to happen with tidy, because tidy only
733 // writes to stdout after it's finished reading from stdin. Search
734 // for tidyParseStdin and tidySaveStdout in console/tidy.c
735 fwrite($pipes[0], $text);
736 fclose($pipes[0]);
737 while (!feof($pipes[1])) {
738 $cleansource .= fgets($pipes[1], 1024);
740 fclose($pipes[1]);
741 proc_close($process);
744 wfProfileOut( $fname );
746 if( $cleansource == '' && $text != '') {
747 // Some kind of error happened, so we couldn't get the corrected text.
748 // Just give up; we'll use the source text and append a warning.
749 return null;
750 } else {
751 return $cleansource;
756 * Use the HTML tidy PECL extension to use the tidy library in-process,
757 * saving the overhead of spawning a new process. Currently written to
758 * the PHP 4.3.x version of the extension, may not work on PHP 5.
760 * 'pear install tidy' should be able to compile the extension module.
762 * @private
763 * @static
765 function internalTidy( $text ) {
766 global $wgTidyConf;
767 $fname = 'Parser::internalTidy';
768 wfProfileIn( $fname );
770 tidy_load_config( $wgTidyConf );
771 tidy_set_encoding( 'utf8' );
772 tidy_parse_string( $text );
773 tidy_clean_repair();
774 if( tidy_get_status() == 2 ) {
775 // 2 is magic number for fatal error
776 // http://www.php.net/manual/en/function.tidy-get-status.php
777 $cleansource = null;
778 } else {
779 $cleansource = tidy_get_output();
781 wfProfileOut( $fname );
782 return $cleansource;
786 * parse the wiki syntax used to render tables
788 * @private
790 function doTableStuff ( $text ) {
791 $fname = 'Parser::doTableStuff';
792 wfProfileIn( $fname );
794 $lines = explode ( "\n" , $text );
795 $td_history = array (); // Is currently a td tag open?
796 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
797 $tr_history = array (); // Is currently a tr tag open?
798 $tr_attributes = array (); // history of tr attributes
799 $has_opened_tr = array(); // Did this table open a <tr> element?
800 $indent_level = 0; // indent level of the table
801 foreach ( $lines as $key => $line )
803 $line = trim ( $line );
805 if( $line == '' ) { // empty line, go to next line
806 continue;
808 $first_character = $line{0};
809 $matches = array();
811 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
812 // First check if we are starting a new table
813 $indent_level = strlen( $matches[1] );
815 $attributes = $this->mStripState->unstripBoth( $matches[2] );
816 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'table' );
818 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
819 array_push ( $td_history , false );
820 array_push ( $last_tag_history , '' );
821 array_push ( $tr_history , false );
822 array_push ( $tr_attributes , '' );
823 array_push ( $has_opened_tr , false );
824 } else if ( count ( $td_history ) == 0 ) {
825 // Don't do any of the following
826 continue;
827 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
828 // We are ending a table
829 $line = '</table>' . substr ( $line , 2 );
830 $last_tag = array_pop ( $last_tag_history );
832 if ( !array_pop ( $has_opened_tr ) ) {
833 $line = "<tr><td></td></tr>{$line}";
836 if ( array_pop ( $tr_history ) ) {
837 $line = "</tr>{$line}";
840 if ( array_pop ( $td_history ) ) {
841 $line = "</{$last_tag}>{$line}";
843 array_pop ( $tr_attributes );
844 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
845 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
846 // Now we have a table row
847 $line = preg_replace( '#^\|-+#', '', $line );
849 // Whats after the tag is now only attributes
850 $attributes = $this->mStripState->unstripBoth( $line );
851 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'tr' );
852 array_pop ( $tr_attributes );
853 array_push ( $tr_attributes , $attributes );
855 $line = '';
856 $last_tag = array_pop ( $last_tag_history );
857 array_pop ( $has_opened_tr );
858 array_push ( $has_opened_tr , true );
860 if ( array_pop ( $tr_history ) ) {
861 $line = '</tr>';
864 if ( array_pop ( $td_history ) ) {
865 $line = "</{$last_tag}>{$line}";
868 $lines[$key] = $line;
869 array_push ( $tr_history , false );
870 array_push ( $td_history , false );
871 array_push ( $last_tag_history , '' );
873 else if ( $first_character == '|' || $first_character == '!' || substr ( $line , 0 , 2 ) == '|+' ) {
874 // This might be cell elements, td, th or captions
875 if ( substr ( $line , 0 , 2 ) == '|+' ) {
876 $first_character = '+';
877 $line = substr ( $line , 1 );
880 $line = substr ( $line , 1 );
882 if ( $first_character == '!' ) {
883 $line = str_replace ( '!!' , '||' , $line );
886 // Split up multiple cells on the same line.
887 // FIXME : This can result in improper nesting of tags processed
888 // by earlier parser steps, but should avoid splitting up eg
889 // attribute values containing literal "||".
890 $cells = StringUtils::explodeMarkup( '||' , $line );
892 $lines[$key] = '';
894 // Loop through each table cell
895 foreach ( $cells as $cell )
897 $previous = '';
898 if ( $first_character != '+' )
900 $tr_after = array_pop ( $tr_attributes );
901 if ( !array_pop ( $tr_history ) ) {
902 $previous = "<tr{$tr_after}>\n";
904 array_push ( $tr_history , true );
905 array_push ( $tr_attributes , '' );
906 array_pop ( $has_opened_tr );
907 array_push ( $has_opened_tr , true );
910 $last_tag = array_pop ( $last_tag_history );
912 if ( array_pop ( $td_history ) ) {
913 $previous = "</{$last_tag}>{$previous}";
916 if ( $first_character == '|' ) {
917 $last_tag = 'td';
918 } else if ( $first_character == '!' ) {
919 $last_tag = 'th';
920 } else if ( $first_character == '+' ) {
921 $last_tag = 'caption';
922 } else {
923 $last_tag = '';
926 array_push ( $last_tag_history , $last_tag );
928 // A cell could contain both parameters and data
929 $cell_data = explode ( '|' , $cell , 2 );
931 // Bug 553: Note that a '|' inside an invalid link should not
932 // be mistaken as delimiting cell parameters
933 if ( strpos( $cell_data[0], '[[' ) !== false ) {
934 $cell = "{$previous}<{$last_tag}>{$cell}";
935 } else if ( count ( $cell_data ) == 1 )
936 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
937 else {
938 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
939 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
940 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
943 $lines[$key] .= $cell;
944 array_push ( $td_history , true );
949 // Closing open td, tr && table
950 while ( count ( $td_history ) > 0 )
952 if ( array_pop ( $td_history ) ) {
953 $lines[] = '</td>' ;
955 if ( array_pop ( $tr_history ) ) {
956 $lines[] = '</tr>' ;
958 if ( !array_pop ( $has_opened_tr ) ) {
959 $lines[] = "<tr><td></td></tr>" ;
962 $lines[] = '</table>' ;
965 $output = implode ( "\n" , $lines ) ;
967 // special case: don't return empty table
968 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
969 $output = '';
972 wfProfileOut( $fname );
974 return $output;
978 * Helper function for parse() that transforms wiki markup into
979 * HTML. Only called for $mOutputType == OT_HTML.
981 * @private
983 function internalParse( $text ) {
984 $args = array();
985 $isMain = true;
986 $fname = 'Parser::internalParse';
987 wfProfileIn( $fname );
989 # Hook to suspend the parser in this state
990 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
991 wfProfileOut( $fname );
992 return $text ;
995 # Remove <noinclude> tags and <includeonly> sections
996 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
997 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
998 $text = StringUtils::delimiterReplace( '<includeonly>', '</includeonly>', '', $text );
1000 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
1002 $text = $this->replaceVariables( $text, $args );
1003 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text ) );
1005 // Tables need to come after variable replacement for things to work
1006 // properly; putting them before other transformations should keep
1007 // exciting things like link expansions from showing up in surprising
1008 // places.
1009 $text = $this->doTableStuff( $text );
1011 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1013 $text = $this->stripToc( $text );
1014 $this->stripNoGallery( $text );
1015 $text = $this->doHeadings( $text );
1016 if($this->mOptions->getUseDynamicDates()) {
1017 $df =& DateFormatter::getInstance();
1018 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
1020 $text = $this->doAllQuotes( $text );
1021 $text = $this->replaceInternalLinks( $text );
1022 $text = $this->replaceExternalLinks( $text );
1024 # replaceInternalLinks may sometimes leave behind
1025 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1026 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
1028 $text = $this->doMagicLinks( $text );
1029 $text = $this->formatHeadings( $text, $isMain );
1031 wfProfileOut( $fname );
1032 return $text;
1036 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1037 * magic external links.
1039 * @private
1041 function &doMagicLinks( &$text ) {
1042 wfProfileIn( __METHOD__ );
1043 $text = preg_replace_callback(
1044 '!(?: # Start cases
1045 <a.*?</a> | # Skip link text
1046 <.*?> | # Skip stuff inside HTML elements
1047 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1048 ISBN\s+(\b # ISBN, capture number as m[2]
1049 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1050 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1051 [0-9Xx] # check digit
1053 )!x', array( &$this, 'magicLinkCallback' ), $text );
1054 wfProfileOut( __METHOD__ );
1055 return $text;
1058 function magicLinkCallback( $m ) {
1059 if ( substr( $m[0], 0, 1 ) == '<' ) {
1060 # Skip HTML element
1061 return $m[0];
1062 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1063 $isbn = $m[2];
1064 $num = strtr( $isbn, array(
1065 '-' => '',
1066 ' ' => '',
1067 'x' => 'X',
1069 $titleObj = SpecialPage::getTitleFor( 'Booksources' );
1070 $text = '<a href="' .
1071 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1072 "\" class=\"internal\">ISBN $isbn</a>";
1073 } else {
1074 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1075 $keyword = 'RFC';
1076 $urlmsg = 'rfcurl';
1077 $id = $m[1];
1078 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1079 $keyword = 'PMID';
1080 $urlmsg = 'pubmedurl';
1081 $id = $m[1];
1082 } else {
1083 throw new MWException( __METHOD__.': unrecognised match type "' .
1084 substr($m[0], 0, 20 ) . '"' );
1087 $url = wfMsg( $urlmsg, $id);
1088 $sk = $this->mOptions->getSkin();
1089 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1090 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1092 return $text;
1096 * Parse headers and return html
1098 * @private
1100 function doHeadings( $text ) {
1101 $fname = 'Parser::doHeadings';
1102 wfProfileIn( $fname );
1103 for ( $i = 6; $i >= 1; --$i ) {
1104 $h = str_repeat( '=', $i );
1105 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
1106 "<h{$i}>\\1</h{$i}>\\2", $text );
1108 wfProfileOut( $fname );
1109 return $text;
1113 * Replace single quotes with HTML markup
1114 * @private
1115 * @return string the altered text
1117 function doAllQuotes( $text ) {
1118 $fname = 'Parser::doAllQuotes';
1119 wfProfileIn( $fname );
1120 $outtext = '';
1121 $lines = explode( "\n", $text );
1122 foreach ( $lines as $line ) {
1123 $outtext .= $this->doQuotes ( $line ) . "\n";
1125 $outtext = substr($outtext, 0,-1);
1126 wfProfileOut( $fname );
1127 return $outtext;
1131 * Helper function for doAllQuotes()
1132 * @private
1134 function doQuotes( $text ) {
1135 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1136 if ( count( $arr ) == 1 )
1137 return $text;
1138 else
1140 # First, do some preliminary work. This may shift some apostrophes from
1141 # being mark-up to being text. It also counts the number of occurrences
1142 # of bold and italics mark-ups.
1143 $i = 0;
1144 $numbold = 0;
1145 $numitalics = 0;
1146 foreach ( $arr as $r )
1148 if ( ( $i % 2 ) == 1 )
1150 # If there are ever four apostrophes, assume the first is supposed to
1151 # be text, and the remaining three constitute mark-up for bold text.
1152 if ( strlen( $arr[$i] ) == 4 )
1154 $arr[$i-1] .= "'";
1155 $arr[$i] = "'''";
1157 # If there are more than 5 apostrophes in a row, assume they're all
1158 # text except for the last 5.
1159 else if ( strlen( $arr[$i] ) > 5 )
1161 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1162 $arr[$i] = "'''''";
1164 # Count the number of occurrences of bold and italics mark-ups.
1165 # We are not counting sequences of five apostrophes.
1166 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++; }
1167 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++; }
1168 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
1170 $i++;
1173 # If there is an odd number of both bold and italics, it is likely
1174 # that one of the bold ones was meant to be an apostrophe followed
1175 # by italics. Which one we cannot know for certain, but it is more
1176 # likely to be one that has a single-letter word before it.
1177 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
1179 $i = 0;
1180 $firstsingleletterword = -1;
1181 $firstmultiletterword = -1;
1182 $firstspace = -1;
1183 foreach ( $arr as $r )
1185 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
1187 $x1 = substr ($arr[$i-1], -1);
1188 $x2 = substr ($arr[$i-1], -2, 1);
1189 if ($x1 == ' ') {
1190 if ($firstspace == -1) $firstspace = $i;
1191 } else if ($x2 == ' ') {
1192 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1193 } else {
1194 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1197 $i++;
1200 # If there is a single-letter word, use it!
1201 if ($firstsingleletterword > -1)
1203 $arr [ $firstsingleletterword ] = "''";
1204 $arr [ $firstsingleletterword-1 ] .= "'";
1206 # If not, but there's a multi-letter word, use that one.
1207 else if ($firstmultiletterword > -1)
1209 $arr [ $firstmultiletterword ] = "''";
1210 $arr [ $firstmultiletterword-1 ] .= "'";
1212 # ... otherwise use the first one that has neither.
1213 # (notice that it is possible for all three to be -1 if, for example,
1214 # there is only one pentuple-apostrophe in the line)
1215 else if ($firstspace > -1)
1217 $arr [ $firstspace ] = "''";
1218 $arr [ $firstspace-1 ] .= "'";
1222 # Now let's actually convert our apostrophic mush to HTML!
1223 $output = '';
1224 $buffer = '';
1225 $state = '';
1226 $i = 0;
1227 foreach ($arr as $r)
1229 if (($i % 2) == 0)
1231 if ($state == 'both')
1232 $buffer .= $r;
1233 else
1234 $output .= $r;
1236 else
1238 if (strlen ($r) == 2)
1240 if ($state == 'i')
1241 { $output .= '</i>'; $state = ''; }
1242 else if ($state == 'bi')
1243 { $output .= '</i>'; $state = 'b'; }
1244 else if ($state == 'ib')
1245 { $output .= '</b></i><b>'; $state = 'b'; }
1246 else if ($state == 'both')
1247 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1248 else # $state can be 'b' or ''
1249 { $output .= '<i>'; $state .= 'i'; }
1251 else if (strlen ($r) == 3)
1253 if ($state == 'b')
1254 { $output .= '</b>'; $state = ''; }
1255 else if ($state == 'bi')
1256 { $output .= '</i></b><i>'; $state = 'i'; }
1257 else if ($state == 'ib')
1258 { $output .= '</b>'; $state = 'i'; }
1259 else if ($state == 'both')
1260 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1261 else # $state can be 'i' or ''
1262 { $output .= '<b>'; $state .= 'b'; }
1264 else if (strlen ($r) == 5)
1266 if ($state == 'b')
1267 { $output .= '</b><i>'; $state = 'i'; }
1268 else if ($state == 'i')
1269 { $output .= '</i><b>'; $state = 'b'; }
1270 else if ($state == 'bi')
1271 { $output .= '</i></b>'; $state = ''; }
1272 else if ($state == 'ib')
1273 { $output .= '</b></i>'; $state = ''; }
1274 else if ($state == 'both')
1275 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1276 else # ($state == '')
1277 { $buffer = ''; $state = 'both'; }
1280 $i++;
1282 # Now close all remaining tags. Notice that the order is important.
1283 if ($state == 'b' || $state == 'ib')
1284 $output .= '</b>';
1285 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1286 $output .= '</i>';
1287 if ($state == 'bi')
1288 $output .= '</b>';
1289 # There might be lonely ''''', so make sure we have a buffer
1290 if ($state == 'both' && $buffer)
1291 $output .= '<b><i>'.$buffer.'</i></b>';
1292 return $output;
1297 * Replace external links
1299 * Note: this is all very hackish and the order of execution matters a lot.
1300 * Make sure to run maintenance/parserTests.php if you change this code.
1302 * @private
1304 function replaceExternalLinks( $text ) {
1305 global $wgContLang;
1306 $fname = 'Parser::replaceExternalLinks';
1307 wfProfileIn( $fname );
1309 $sk = $this->mOptions->getSkin();
1311 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1313 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1315 $i = 0;
1316 while ( $i<count( $bits ) ) {
1317 $url = $bits[$i++];
1318 $protocol = $bits[$i++];
1319 $text = $bits[$i++];
1320 $trail = $bits[$i++];
1322 # The characters '<' and '>' (which were escaped by
1323 # removeHTMLtags()) should not be included in
1324 # URLs, per RFC 2396.
1325 $m2 = array();
1326 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1327 $text = substr($url, $m2[0][1]) . ' ' . $text;
1328 $url = substr($url, 0, $m2[0][1]);
1331 # If the link text is an image URL, replace it with an <img> tag
1332 # This happened by accident in the original parser, but some people used it extensively
1333 $img = $this->maybeMakeExternalImage( $text );
1334 if ( $img !== false ) {
1335 $text = $img;
1338 $dtrail = '';
1340 # Set linktype for CSS - if URL==text, link is essentially free
1341 $linktype = ($text == $url) ? 'free' : 'text';
1343 # No link text, e.g. [http://domain.tld/some.link]
1344 if ( $text == '' ) {
1345 # Autonumber if allowed. See bug #5918
1346 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1347 $text = '[' . ++$this->mAutonumber . ']';
1348 $linktype = 'autonumber';
1349 } else {
1350 # Otherwise just use the URL
1351 $text = htmlspecialchars( $url );
1352 $linktype = 'free';
1354 } else {
1355 # Have link text, e.g. [http://domain.tld/some.link text]s
1356 # Check for trail
1357 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1360 $text = $wgContLang->markNoConversion($text);
1362 $url = Sanitizer::cleanUrl( $url );
1364 # Process the trail (i.e. everything after this link up until start of the next link),
1365 # replacing any non-bracketed links
1366 $trail = $this->replaceFreeExternalLinks( $trail );
1368 # Use the encoded URL
1369 # This means that users can paste URLs directly into the text
1370 # Funny characters like &ouml; aren't valid in URLs anyway
1371 # This was changed in August 2004
1372 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle->getNamespace() ) . $dtrail . $trail;
1374 # Register link in the output object.
1375 # Replace unnecessary URL escape codes with the referenced character
1376 # This prevents spammers from hiding links from the filters
1377 $pasteurized = Parser::replaceUnusualEscapes( $url );
1378 $this->mOutput->addExternalLink( $pasteurized );
1381 wfProfileOut( $fname );
1382 return $s;
1386 * Replace anything that looks like a URL with a link
1387 * @private
1389 function replaceFreeExternalLinks( $text ) {
1390 global $wgContLang;
1391 $fname = 'Parser::replaceFreeExternalLinks';
1392 wfProfileIn( $fname );
1394 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1395 $s = array_shift( $bits );
1396 $i = 0;
1398 $sk = $this->mOptions->getSkin();
1400 while ( $i < count( $bits ) ){
1401 $protocol = $bits[$i++];
1402 $remainder = $bits[$i++];
1404 $m = array();
1405 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1406 # Found some characters after the protocol that look promising
1407 $url = $protocol . $m[1];
1408 $trail = $m[2];
1410 # special case: handle urls as url args:
1411 # http://www.example.com/foo?=http://www.example.com/bar
1412 if(strlen($trail) == 0 &&
1413 isset($bits[$i]) &&
1414 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1415 preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $bits[$i + 1], $m ))
1417 # add protocol, arg
1418 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1419 $i += 2;
1420 $trail = $m[2];
1423 # The characters '<' and '>' (which were escaped by
1424 # removeHTMLtags()) should not be included in
1425 # URLs, per RFC 2396.
1426 $m2 = array();
1427 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1428 $trail = substr($url, $m2[0][1]) . $trail;
1429 $url = substr($url, 0, $m2[0][1]);
1432 # Move trailing punctuation to $trail
1433 $sep = ',;\.:!?';
1434 # If there is no left bracket, then consider right brackets fair game too
1435 if ( strpos( $url, '(' ) === false ) {
1436 $sep .= ')';
1439 $numSepChars = strspn( strrev( $url ), $sep );
1440 if ( $numSepChars ) {
1441 $trail = substr( $url, -$numSepChars ) . $trail;
1442 $url = substr( $url, 0, -$numSepChars );
1445 $url = Sanitizer::cleanUrl( $url );
1447 # Is this an external image?
1448 $text = $this->maybeMakeExternalImage( $url );
1449 if ( $text === false ) {
1450 # Not an image, make a link
1451 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle->getNamespace() );
1452 # Register it in the output object...
1453 # Replace unnecessary URL escape codes with their equivalent characters
1454 $pasteurized = Parser::replaceUnusualEscapes( $url );
1455 $this->mOutput->addExternalLink( $pasteurized );
1457 $s .= $text . $trail;
1458 } else {
1459 $s .= $protocol . $remainder;
1462 wfProfileOut( $fname );
1463 return $s;
1467 * Replace unusual URL escape codes with their equivalent characters
1468 * @param string
1469 * @return string
1470 * @static
1471 * @fixme This can merge genuinely required bits in the path or query string,
1472 * breaking legit URLs. A proper fix would treat the various parts of
1473 * the URL differently; as a workaround, just use the output for
1474 * statistical records, not for actual linking/output.
1476 static function replaceUnusualEscapes( $url ) {
1477 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1478 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1482 * Callback function used in replaceUnusualEscapes().
1483 * Replaces unusual URL escape codes with their equivalent character
1484 * @static
1485 * @private
1487 private static function replaceUnusualEscapesCallback( $matches ) {
1488 $char = urldecode( $matches[0] );
1489 $ord = ord( $char );
1490 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1491 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1492 // No, shouldn't be escaped
1493 return $char;
1494 } else {
1495 // Yes, leave it escaped
1496 return $matches[0];
1501 * make an image if it's allowed, either through the global
1502 * option or through the exception
1503 * @private
1505 function maybeMakeExternalImage( $url ) {
1506 $sk = $this->mOptions->getSkin();
1507 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1508 $imagesexception = !empty($imagesfrom);
1509 $text = false;
1510 if ( $this->mOptions->getAllowExternalImages()
1511 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1512 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1513 # Image found
1514 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1517 return $text;
1521 * Process [[ ]] wikilinks
1523 * @private
1525 function replaceInternalLinks( $s ) {
1526 global $wgContLang;
1527 static $fname = 'Parser::replaceInternalLinks' ;
1529 wfProfileIn( $fname );
1531 wfProfileIn( $fname.'-setup' );
1532 static $tc = FALSE;
1533 # the % is needed to support urlencoded titles as well
1534 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1536 $sk = $this->mOptions->getSkin();
1538 #split the entire text string on occurences of [[
1539 $a = explode( '[[', ' ' . $s );
1540 #get the first element (all text up to first [[), and remove the space we added
1541 $s = array_shift( $a );
1542 $s = substr( $s, 1 );
1544 # Match a link having the form [[namespace:link|alternate]]trail
1545 static $e1 = FALSE;
1546 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1547 # Match cases where there is no "]]", which might still be images
1548 static $e1_img = FALSE;
1549 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1550 # Match the end of a line for a word that's not followed by whitespace,
1551 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1552 $e2 = wfMsgForContent( 'linkprefix' );
1554 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1555 if( is_null( $this->mTitle ) ) {
1556 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1558 $nottalk = !$this->mTitle->isTalkPage();
1560 if ( $useLinkPrefixExtension ) {
1561 $m = array();
1562 if ( preg_match( $e2, $s, $m ) ) {
1563 $first_prefix = $m[2];
1564 } else {
1565 $first_prefix = false;
1567 } else {
1568 $prefix = '';
1571 if($wgContLang->hasVariants()) {
1572 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1573 } else {
1574 $selflink = array($this->mTitle->getPrefixedText());
1576 $useSubpages = $this->areSubpagesAllowed();
1577 wfProfileOut( $fname.'-setup' );
1579 # Loop for each link
1580 for ($k = 0; isset( $a[$k] ); $k++) {
1581 $line = $a[$k];
1582 if ( $useLinkPrefixExtension ) {
1583 wfProfileIn( $fname.'-prefixhandling' );
1584 if ( preg_match( $e2, $s, $m ) ) {
1585 $prefix = $m[2];
1586 $s = $m[1];
1587 } else {
1588 $prefix='';
1590 # first link
1591 if($first_prefix) {
1592 $prefix = $first_prefix;
1593 $first_prefix = false;
1595 wfProfileOut( $fname.'-prefixhandling' );
1598 $might_be_img = false;
1600 wfProfileIn( "$fname-e1" );
1601 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1602 $text = $m[2];
1603 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1604 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1605 # the real problem is with the $e1 regex
1606 # See bug 1300.
1608 # Still some problems for cases where the ] is meant to be outside punctuation,
1609 # and no image is in sight. See bug 2095.
1611 if( $text !== '' &&
1612 substr( $m[3], 0, 1 ) === ']' &&
1613 strpos($text, '[') !== false
1616 $text .= ']'; # so that replaceExternalLinks($text) works later
1617 $m[3] = substr( $m[3], 1 );
1619 # fix up urlencoded title texts
1620 if( strpos( $m[1], '%' ) !== false ) {
1621 # Should anchors '#' also be rejected?
1622 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1624 $trail = $m[3];
1625 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1626 $might_be_img = true;
1627 $text = $m[2];
1628 if ( strpos( $m[1], '%' ) !== false ) {
1629 $m[1] = urldecode($m[1]);
1631 $trail = "";
1632 } else { # Invalid form; output directly
1633 $s .= $prefix . '[[' . $line ;
1634 wfProfileOut( "$fname-e1" );
1635 continue;
1637 wfProfileOut( "$fname-e1" );
1638 wfProfileIn( "$fname-misc" );
1640 # Don't allow internal links to pages containing
1641 # PROTO: where PROTO is a valid URL protocol; these
1642 # should be external links.
1643 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1644 $s .= $prefix . '[[' . $line ;
1645 continue;
1648 # Make subpage if necessary
1649 if( $useSubpages ) {
1650 $link = $this->maybeDoSubpageLink( $m[1], $text );
1651 } else {
1652 $link = $m[1];
1655 $noforce = (substr($m[1], 0, 1) != ':');
1656 if (!$noforce) {
1657 # Strip off leading ':'
1658 $link = substr($link, 1);
1661 wfProfileOut( "$fname-misc" );
1662 wfProfileIn( "$fname-title" );
1663 $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
1664 if( !$nt ) {
1665 $s .= $prefix . '[[' . $line;
1666 wfProfileOut( "$fname-title" );
1667 continue;
1670 $ns = $nt->getNamespace();
1671 $iw = $nt->getInterWiki();
1672 wfProfileOut( "$fname-title" );
1674 if ($might_be_img) { # if this is actually an invalid link
1675 wfProfileIn( "$fname-might_be_img" );
1676 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1677 $found = false;
1678 while (isset ($a[$k+1]) ) {
1679 #look at the next 'line' to see if we can close it there
1680 $spliced = array_splice( $a, $k + 1, 1 );
1681 $next_line = array_shift( $spliced );
1682 $m = explode( ']]', $next_line, 3 );
1683 if ( count( $m ) == 3 ) {
1684 # the first ]] closes the inner link, the second the image
1685 $found = true;
1686 $text .= "[[{$m[0]}]]{$m[1]}";
1687 $trail = $m[2];
1688 break;
1689 } elseif ( count( $m ) == 2 ) {
1690 #if there's exactly one ]] that's fine, we'll keep looking
1691 $text .= "[[{$m[0]}]]{$m[1]}";
1692 } else {
1693 #if $next_line is invalid too, we need look no further
1694 $text .= '[[' . $next_line;
1695 break;
1698 if ( !$found ) {
1699 # we couldn't find the end of this imageLink, so output it raw
1700 #but don't ignore what might be perfectly normal links in the text we've examined
1701 $text = $this->replaceInternalLinks($text);
1702 $s .= "{$prefix}[[$link|$text";
1703 # note: no $trail, because without an end, there *is* no trail
1704 wfProfileOut( "$fname-might_be_img" );
1705 continue;
1707 } else { #it's not an image, so output it raw
1708 $s .= "{$prefix}[[$link|$text";
1709 # note: no $trail, because without an end, there *is* no trail
1710 wfProfileOut( "$fname-might_be_img" );
1711 continue;
1713 wfProfileOut( "$fname-might_be_img" );
1716 $wasblank = ( '' == $text );
1717 if( $wasblank ) $text = $link;
1719 # Link not escaped by : , create the various objects
1720 if( $noforce ) {
1722 # Interwikis
1723 wfProfileIn( "$fname-interwiki" );
1724 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1725 $this->mOutput->addLanguageLink( $nt->getFullText() );
1726 $s = rtrim($s . $prefix);
1727 $s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
1728 wfProfileOut( "$fname-interwiki" );
1729 continue;
1731 wfProfileOut( "$fname-interwiki" );
1733 if ( $ns == NS_IMAGE ) {
1734 wfProfileIn( "$fname-image" );
1735 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1736 # recursively parse links inside the image caption
1737 # actually, this will parse them in any other parameters, too,
1738 # but it might be hard to fix that, and it doesn't matter ATM
1739 $text = $this->replaceExternalLinks($text);
1740 $text = $this->replaceInternalLinks($text);
1742 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1743 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1744 $this->mOutput->addImage( $nt->getDBkey() );
1746 wfProfileOut( "$fname-image" );
1747 continue;
1748 } else {
1749 # We still need to record the image's presence on the page
1750 $this->mOutput->addImage( $nt->getDBkey() );
1752 wfProfileOut( "$fname-image" );
1756 if ( $ns == NS_CATEGORY ) {
1757 wfProfileIn( "$fname-category" );
1758 $s = rtrim($s . "\n"); # bug 87
1760 if ( $wasblank ) {
1761 $sortkey = $this->getDefaultSort();
1762 } else {
1763 $sortkey = $text;
1765 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1766 $sortkey = str_replace( "\n", '', $sortkey );
1767 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1768 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1771 * Strip the whitespace Category links produce, see bug 87
1772 * @todo We might want to use trim($tmp, "\n") here.
1774 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1776 wfProfileOut( "$fname-category" );
1777 continue;
1781 # Self-link checking
1782 if( $nt->getFragment() === '' ) {
1783 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1784 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1785 continue;
1789 # Special and Media are pseudo-namespaces; no pages actually exist in them
1790 if( $ns == NS_MEDIA ) {
1791 $link = $sk->makeMediaLinkObj( $nt, $text );
1792 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1793 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1794 $this->mOutput->addImage( $nt->getDBkey() );
1795 continue;
1796 } elseif( $ns == NS_SPECIAL ) {
1797 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1798 continue;
1799 } elseif( $ns == NS_IMAGE ) {
1800 $img = new Image( $nt );
1801 if( $img->exists() ) {
1802 // Force a blue link if the file exists; may be a remote
1803 // upload on the shared repository, and we want to see its
1804 // auto-generated page.
1805 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1806 $this->mOutput->addLink( $nt );
1807 continue;
1810 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1812 wfProfileOut( $fname );
1813 return $s;
1817 * Make a link placeholder. The text returned can be later resolved to a real link with
1818 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1819 * parsing of interwiki links, and secondly to allow all existence checks and
1820 * article length checks (for stub links) to be bundled into a single query.
1823 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1824 wfProfileIn( __METHOD__ );
1825 if ( ! is_object($nt) ) {
1826 # Fail gracefully
1827 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1828 } else {
1829 # Separate the link trail from the rest of the link
1830 list( $inside, $trail ) = Linker::splitTrail( $trail );
1832 if ( $nt->isExternal() ) {
1833 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1834 $this->mInterwikiLinkHolders['titles'][] = $nt;
1835 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1836 } else {
1837 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1838 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1839 $this->mLinkHolders['queries'][] = $query;
1840 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1841 $this->mLinkHolders['titles'][] = $nt;
1843 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1846 wfProfileOut( __METHOD__ );
1847 return $retVal;
1851 * Render a forced-blue link inline; protect against double expansion of
1852 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1853 * Since this little disaster has to split off the trail text to avoid
1854 * breaking URLs in the following text without breaking trails on the
1855 * wiki links, it's been made into a horrible function.
1857 * @param Title $nt
1858 * @param string $text
1859 * @param string $query
1860 * @param string $trail
1861 * @param string $prefix
1862 * @return string HTML-wikitext mix oh yuck
1864 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1865 list( $inside, $trail ) = Linker::splitTrail( $trail );
1866 $sk = $this->mOptions->getSkin();
1867 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1868 return $this->armorLinks( $link ) . $trail;
1872 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1873 * going to go through further parsing steps before inline URL expansion.
1875 * In particular this is important when using action=render, which causes
1876 * full URLs to be included.
1878 * Oh man I hate our multi-layer parser!
1880 * @param string more-or-less HTML
1881 * @return string less-or-more HTML with NOPARSE bits
1883 function armorLinks( $text ) {
1884 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1885 "{$this->mUniqPrefix}NOPARSE$1", $text );
1889 * Return true if subpage links should be expanded on this page.
1890 * @return bool
1892 function areSubpagesAllowed() {
1893 # Some namespaces don't allow subpages
1894 global $wgNamespacesWithSubpages;
1895 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1899 * Handle link to subpage if necessary
1900 * @param string $target the source of the link
1901 * @param string &$text the link text, modified as necessary
1902 * @return string the full name of the link
1903 * @private
1905 function maybeDoSubpageLink($target, &$text) {
1906 # Valid link forms:
1907 # Foobar -- normal
1908 # :Foobar -- override special treatment of prefix (images, language links)
1909 # /Foobar -- convert to CurrentPage/Foobar
1910 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1911 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1912 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1914 $fname = 'Parser::maybeDoSubpageLink';
1915 wfProfileIn( $fname );
1916 $ret = $target; # default return value is no change
1918 # bug 7425
1919 $target = trim( $target );
1921 # Some namespaces don't allow subpages,
1922 # so only perform processing if subpages are allowed
1923 if( $this->areSubpagesAllowed() ) {
1924 # Look at the first character
1925 if( $target != '' && $target{0} == '/' ) {
1926 # / at end means we don't want the slash to be shown
1927 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1928 if( $trailingSlashes ) {
1929 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1930 } else {
1931 $noslash = substr( $target, 1 );
1934 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1935 if( '' === $text ) {
1936 $text = $target;
1937 } # this might be changed for ugliness reasons
1938 } else {
1939 # check for .. subpage backlinks
1940 $dotdotcount = 0;
1941 $nodotdot = $target;
1942 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1943 ++$dotdotcount;
1944 $nodotdot = substr( $nodotdot, 3 );
1946 if($dotdotcount > 0) {
1947 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1948 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1949 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1950 # / at the end means don't show full path
1951 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1952 $nodotdot = substr( $nodotdot, 0, -1 );
1953 if( '' === $text ) {
1954 $text = $nodotdot;
1957 $nodotdot = trim( $nodotdot );
1958 if( $nodotdot != '' ) {
1959 $ret .= '/' . $nodotdot;
1966 wfProfileOut( $fname );
1967 return $ret;
1970 /**#@+
1971 * Used by doBlockLevels()
1972 * @private
1974 /* private */ function closeParagraph() {
1975 $result = '';
1976 if ( '' != $this->mLastSection ) {
1977 $result = '</' . $this->mLastSection . ">\n";
1979 $this->mInPre = false;
1980 $this->mLastSection = '';
1981 return $result;
1983 # getCommon() returns the length of the longest common substring
1984 # of both arguments, starting at the beginning of both.
1986 /* private */ function getCommon( $st1, $st2 ) {
1987 $fl = strlen( $st1 );
1988 $shorter = strlen( $st2 );
1989 if ( $fl < $shorter ) { $shorter = $fl; }
1991 for ( $i = 0; $i < $shorter; ++$i ) {
1992 if ( $st1{$i} != $st2{$i} ) { break; }
1994 return $i;
1996 # These next three functions open, continue, and close the list
1997 # element appropriate to the prefix character passed into them.
1999 /* private */ function openList( $char ) {
2000 $result = $this->closeParagraph();
2002 if ( '*' == $char ) { $result .= '<ul><li>'; }
2003 else if ( '#' == $char ) { $result .= '<ol><li>'; }
2004 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
2005 else if ( ';' == $char ) {
2006 $result .= '<dl><dt>';
2007 $this->mDTopen = true;
2009 else { $result = '<!-- ERR 1 -->'; }
2011 return $result;
2014 /* private */ function nextItem( $char ) {
2015 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
2016 else if ( ':' == $char || ';' == $char ) {
2017 $close = '</dd>';
2018 if ( $this->mDTopen ) { $close = '</dt>'; }
2019 if ( ';' == $char ) {
2020 $this->mDTopen = true;
2021 return $close . '<dt>';
2022 } else {
2023 $this->mDTopen = false;
2024 return $close . '<dd>';
2027 return '<!-- ERR 2 -->';
2030 /* private */ function closeList( $char ) {
2031 if ( '*' == $char ) { $text = '</li></ul>'; }
2032 else if ( '#' == $char ) { $text = '</li></ol>'; }
2033 else if ( ':' == $char ) {
2034 if ( $this->mDTopen ) {
2035 $this->mDTopen = false;
2036 $text = '</dt></dl>';
2037 } else {
2038 $text = '</dd></dl>';
2041 else { return '<!-- ERR 3 -->'; }
2042 return $text."\n";
2044 /**#@-*/
2047 * Make lists from lines starting with ':', '*', '#', etc.
2049 * @private
2050 * @return string the lists rendered as HTML
2052 function doBlockLevels( $text, $linestart ) {
2053 $fname = 'Parser::doBlockLevels';
2054 wfProfileIn( $fname );
2056 # Parsing through the text line by line. The main thing
2057 # happening here is handling of block-level elements p, pre,
2058 # and making lists from lines starting with * # : etc.
2060 $textLines = explode( "\n", $text );
2062 $lastPrefix = $output = '';
2063 $this->mDTopen = $inBlockElem = false;
2064 $prefixLength = 0;
2065 $paragraphStack = false;
2067 if ( !$linestart ) {
2068 $output .= array_shift( $textLines );
2070 foreach ( $textLines as $oLine ) {
2071 $lastPrefixLength = strlen( $lastPrefix );
2072 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2073 $preOpenMatch = preg_match('/<pre/i', $oLine );
2074 if ( !$this->mInPre ) {
2075 # Multiple prefixes may abut each other for nested lists.
2076 $prefixLength = strspn( $oLine, '*#:;' );
2077 $pref = substr( $oLine, 0, $prefixLength );
2079 # eh?
2080 $pref2 = str_replace( ';', ':', $pref );
2081 $t = substr( $oLine, $prefixLength );
2082 $this->mInPre = !empty($preOpenMatch);
2083 } else {
2084 # Don't interpret any other prefixes in preformatted text
2085 $prefixLength = 0;
2086 $pref = $pref2 = '';
2087 $t = $oLine;
2090 # List generation
2091 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2092 # Same as the last item, so no need to deal with nesting or opening stuff
2093 $output .= $this->nextItem( substr( $pref, -1 ) );
2094 $paragraphStack = false;
2096 if ( substr( $pref, -1 ) == ';') {
2097 # The one nasty exception: definition lists work like this:
2098 # ; title : definition text
2099 # So we check for : in the remainder text to split up the
2100 # title and definition, without b0rking links.
2101 $term = $t2 = '';
2102 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2103 $t = $t2;
2104 $output .= $term . $this->nextItem( ':' );
2107 } elseif( $prefixLength || $lastPrefixLength ) {
2108 # Either open or close a level...
2109 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2110 $paragraphStack = false;
2112 while( $commonPrefixLength < $lastPrefixLength ) {
2113 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2114 --$lastPrefixLength;
2116 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2117 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2119 while ( $prefixLength > $commonPrefixLength ) {
2120 $char = substr( $pref, $commonPrefixLength, 1 );
2121 $output .= $this->openList( $char );
2123 if ( ';' == $char ) {
2124 # FIXME: This is dupe of code above
2125 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2126 $t = $t2;
2127 $output .= $term . $this->nextItem( ':' );
2130 ++$commonPrefixLength;
2132 $lastPrefix = $pref2;
2134 if( 0 == $prefixLength ) {
2135 wfProfileIn( "$fname-paragraph" );
2136 # No prefix (not in list)--go to paragraph mode
2137 // XXX: use a stack for nestable elements like span, table and div
2138 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2139 $closematch = preg_match(
2140 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2141 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2142 if ( $openmatch or $closematch ) {
2143 $paragraphStack = false;
2144 # TODO bug 5718: paragraph closed
2145 $output .= $this->closeParagraph();
2146 if ( $preOpenMatch and !$preCloseMatch ) {
2147 $this->mInPre = true;
2149 if ( $closematch ) {
2150 $inBlockElem = false;
2151 } else {
2152 $inBlockElem = true;
2154 } else if ( !$inBlockElem && !$this->mInPre ) {
2155 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
2156 // pre
2157 if ($this->mLastSection != 'pre') {
2158 $paragraphStack = false;
2159 $output .= $this->closeParagraph().'<pre>';
2160 $this->mLastSection = 'pre';
2162 $t = substr( $t, 1 );
2163 } else {
2164 // paragraph
2165 if ( '' == trim($t) ) {
2166 if ( $paragraphStack ) {
2167 $output .= $paragraphStack.'<br />';
2168 $paragraphStack = false;
2169 $this->mLastSection = 'p';
2170 } else {
2171 if ($this->mLastSection != 'p' ) {
2172 $output .= $this->closeParagraph();
2173 $this->mLastSection = '';
2174 $paragraphStack = '<p>';
2175 } else {
2176 $paragraphStack = '</p><p>';
2179 } else {
2180 if ( $paragraphStack ) {
2181 $output .= $paragraphStack;
2182 $paragraphStack = false;
2183 $this->mLastSection = 'p';
2184 } else if ($this->mLastSection != 'p') {
2185 $output .= $this->closeParagraph().'<p>';
2186 $this->mLastSection = 'p';
2191 wfProfileOut( "$fname-paragraph" );
2193 // somewhere above we forget to get out of pre block (bug 785)
2194 if($preCloseMatch && $this->mInPre) {
2195 $this->mInPre = false;
2197 if ($paragraphStack === false) {
2198 $output .= $t."\n";
2201 while ( $prefixLength ) {
2202 $output .= $this->closeList( $pref2{$prefixLength-1} );
2203 --$prefixLength;
2205 if ( '' != $this->mLastSection ) {
2206 $output .= '</' . $this->mLastSection . '>';
2207 $this->mLastSection = '';
2210 wfProfileOut( $fname );
2211 return $output;
2215 * Split up a string on ':', ignoring any occurences inside tags
2216 * to prevent illegal overlapping.
2217 * @param string $str the string to split
2218 * @param string &$before set to everything before the ':'
2219 * @param string &$after set to everything after the ':'
2220 * return string the position of the ':', or false if none found
2222 function findColonNoLinks($str, &$before, &$after) {
2223 $fname = 'Parser::findColonNoLinks';
2224 wfProfileIn( $fname );
2226 $pos = strpos( $str, ':' );
2227 if( $pos === false ) {
2228 // Nothing to find!
2229 wfProfileOut( $fname );
2230 return false;
2233 $lt = strpos( $str, '<' );
2234 if( $lt === false || $lt > $pos ) {
2235 // Easy; no tag nesting to worry about
2236 $before = substr( $str, 0, $pos );
2237 $after = substr( $str, $pos+1 );
2238 wfProfileOut( $fname );
2239 return $pos;
2242 // Ugly state machine to walk through avoiding tags.
2243 $state = MW_COLON_STATE_TEXT;
2244 $stack = 0;
2245 $len = strlen( $str );
2246 for( $i = 0; $i < $len; $i++ ) {
2247 $c = $str{$i};
2249 switch( $state ) {
2250 // (Using the number is a performance hack for common cases)
2251 case 0: // MW_COLON_STATE_TEXT:
2252 switch( $c ) {
2253 case "<":
2254 // Could be either a <start> tag or an </end> tag
2255 $state = MW_COLON_STATE_TAGSTART;
2256 break;
2257 case ":":
2258 if( $stack == 0 ) {
2259 // We found it!
2260 $before = substr( $str, 0, $i );
2261 $after = substr( $str, $i + 1 );
2262 wfProfileOut( $fname );
2263 return $i;
2265 // Embedded in a tag; don't break it.
2266 break;
2267 default:
2268 // Skip ahead looking for something interesting
2269 $colon = strpos( $str, ':', $i );
2270 if( $colon === false ) {
2271 // Nothing else interesting
2272 wfProfileOut( $fname );
2273 return false;
2275 $lt = strpos( $str, '<', $i );
2276 if( $stack === 0 ) {
2277 if( $lt === false || $colon < $lt ) {
2278 // We found it!
2279 $before = substr( $str, 0, $colon );
2280 $after = substr( $str, $colon + 1 );
2281 wfProfileOut( $fname );
2282 return $i;
2285 if( $lt === false ) {
2286 // Nothing else interesting to find; abort!
2287 // We're nested, but there's no close tags left. Abort!
2288 break 2;
2290 // Skip ahead to next tag start
2291 $i = $lt;
2292 $state = MW_COLON_STATE_TAGSTART;
2294 break;
2295 case 1: // MW_COLON_STATE_TAG:
2296 // In a <tag>
2297 switch( $c ) {
2298 case ">":
2299 $stack++;
2300 $state = MW_COLON_STATE_TEXT;
2301 break;
2302 case "/":
2303 // Slash may be followed by >?
2304 $state = MW_COLON_STATE_TAGSLASH;
2305 break;
2306 default:
2307 // ignore
2309 break;
2310 case 2: // MW_COLON_STATE_TAGSTART:
2311 switch( $c ) {
2312 case "/":
2313 $state = MW_COLON_STATE_CLOSETAG;
2314 break;
2315 case "!":
2316 $state = MW_COLON_STATE_COMMENT;
2317 break;
2318 case ">":
2319 // Illegal early close? This shouldn't happen D:
2320 $state = MW_COLON_STATE_TEXT;
2321 break;
2322 default:
2323 $state = MW_COLON_STATE_TAG;
2325 break;
2326 case 3: // MW_COLON_STATE_CLOSETAG:
2327 // In a </tag>
2328 if( $c == ">" ) {
2329 $stack--;
2330 if( $stack < 0 ) {
2331 wfDebug( "Invalid input in $fname; too many close tags\n" );
2332 wfProfileOut( $fname );
2333 return false;
2335 $state = MW_COLON_STATE_TEXT;
2337 break;
2338 case MW_COLON_STATE_TAGSLASH:
2339 if( $c == ">" ) {
2340 // Yes, a self-closed tag <blah/>
2341 $state = MW_COLON_STATE_TEXT;
2342 } else {
2343 // Probably we're jumping the gun, and this is an attribute
2344 $state = MW_COLON_STATE_TAG;
2346 break;
2347 case 5: // MW_COLON_STATE_COMMENT:
2348 if( $c == "-" ) {
2349 $state = MW_COLON_STATE_COMMENTDASH;
2351 break;
2352 case MW_COLON_STATE_COMMENTDASH:
2353 if( $c == "-" ) {
2354 $state = MW_COLON_STATE_COMMENTDASHDASH;
2355 } else {
2356 $state = MW_COLON_STATE_COMMENT;
2358 break;
2359 case MW_COLON_STATE_COMMENTDASHDASH:
2360 if( $c == ">" ) {
2361 $state = MW_COLON_STATE_TEXT;
2362 } else {
2363 $state = MW_COLON_STATE_COMMENT;
2365 break;
2366 default:
2367 throw new MWException( "State machine error in $fname" );
2370 if( $stack > 0 ) {
2371 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2372 return false;
2374 wfProfileOut( $fname );
2375 return false;
2379 * Return value of a magic variable (like PAGENAME)
2381 * @private
2383 function getVariableValue( $index ) {
2384 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2387 * Some of these require message or data lookups and can be
2388 * expensive to check many times.
2390 static $varCache = array();
2391 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2392 if ( isset( $varCache[$index] ) ) {
2393 return $varCache[$index];
2397 $ts = time();
2398 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2400 # Use the time zone
2401 global $wgLocaltimezone;
2402 if ( isset( $wgLocaltimezone ) ) {
2403 $oldtz = getenv( 'TZ' );
2404 putenv( 'TZ='.$wgLocaltimezone );
2406 $localTimestamp = date( 'YmdHis', $ts );
2407 $localMonth = date( 'm', $ts );
2408 $localMonthName = date( 'n', $ts );
2409 $localDay = date( 'j', $ts );
2410 $localDay2 = date( 'd', $ts );
2411 $localDayOfWeek = date( 'w', $ts );
2412 $localWeek = date( 'W', $ts );
2413 $localYear = date( 'Y', $ts );
2414 $localHour = date( 'H', $ts );
2415 if ( isset( $wgLocaltimezone ) ) {
2416 putenv( 'TZ='.$oldtz );
2419 switch ( $index ) {
2420 case 'currentmonth':
2421 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2422 case 'currentmonthname':
2423 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2424 case 'currentmonthnamegen':
2425 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2426 case 'currentmonthabbrev':
2427 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2428 case 'currentday':
2429 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2430 case 'currentday2':
2431 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2432 case 'localmonth':
2433 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2434 case 'localmonthname':
2435 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2436 case 'localmonthnamegen':
2437 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2438 case 'localmonthabbrev':
2439 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2440 case 'localday':
2441 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2442 case 'localday2':
2443 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2444 case 'pagename':
2445 return $this->mTitle->getText();
2446 case 'pagenamee':
2447 return $this->mTitle->getPartialURL();
2448 case 'fullpagename':
2449 return $this->mTitle->getPrefixedText();
2450 case 'fullpagenamee':
2451 return $this->mTitle->getPrefixedURL();
2452 case 'subpagename':
2453 return $this->mTitle->getSubpageText();
2454 case 'subpagenamee':
2455 return $this->mTitle->getSubpageUrlForm();
2456 case 'basepagename':
2457 return $this->mTitle->getBaseText();
2458 case 'basepagenamee':
2459 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2460 case 'talkpagename':
2461 if( $this->mTitle->canTalk() ) {
2462 $talkPage = $this->mTitle->getTalkPage();
2463 return $talkPage->getPrefixedText();
2464 } else {
2465 return '';
2467 case 'talkpagenamee':
2468 if( $this->mTitle->canTalk() ) {
2469 $talkPage = $this->mTitle->getTalkPage();
2470 return $talkPage->getPrefixedUrl();
2471 } else {
2472 return '';
2474 case 'subjectpagename':
2475 $subjPage = $this->mTitle->getSubjectPage();
2476 return $subjPage->getPrefixedText();
2477 case 'subjectpagenamee':
2478 $subjPage = $this->mTitle->getSubjectPage();
2479 return $subjPage->getPrefixedUrl();
2480 case 'revisionid':
2481 return $this->mRevisionId;
2482 case 'revisionday':
2483 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2484 case 'revisionday2':
2485 return substr( $this->getRevisionTimestamp(), 6, 2 );
2486 case 'revisionmonth':
2487 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2488 case 'revisionyear':
2489 return substr( $this->getRevisionTimestamp(), 0, 4 );
2490 case 'revisiontimestamp':
2491 return $this->getRevisionTimestamp();
2492 case 'namespace':
2493 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2494 case 'namespacee':
2495 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2496 case 'talkspace':
2497 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2498 case 'talkspacee':
2499 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2500 case 'subjectspace':
2501 return $this->mTitle->getSubjectNsText();
2502 case 'subjectspacee':
2503 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2504 case 'currentdayname':
2505 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
2506 case 'currentyear':
2507 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2508 case 'currenttime':
2509 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2510 case 'currenthour':
2511 return $varCache[$index] = $wgContLang->formatNum( date( 'H', $ts ), true );
2512 case 'currentweek':
2513 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2514 // int to remove the padding
2515 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2516 case 'currentdow':
2517 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2518 case 'localdayname':
2519 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2520 case 'localyear':
2521 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2522 case 'localtime':
2523 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2524 case 'localhour':
2525 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2526 case 'localweek':
2527 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2528 // int to remove the padding
2529 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2530 case 'localdow':
2531 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2532 case 'numberofarticles':
2533 return $varCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2534 case 'numberoffiles':
2535 return $varCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2536 case 'numberofusers':
2537 return $varCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2538 case 'numberofpages':
2539 return $varCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2540 case 'numberofadmins':
2541 return $varCache[$index] = $wgContLang->formatNum( SiteStats::admins() );
2542 case 'currenttimestamp':
2543 return $varCache[$index] = wfTimestampNow();
2544 case 'localtimestamp':
2545 return $varCache[$index] = $localTimestamp;
2546 case 'currentversion':
2547 return $varCache[$index] = SpecialVersion::getVersion();
2548 case 'sitename':
2549 return $wgSitename;
2550 case 'server':
2551 return $wgServer;
2552 case 'servername':
2553 return $wgServerName;
2554 case 'scriptpath':
2555 return $wgScriptPath;
2556 case 'directionmark':
2557 return $wgContLang->getDirMark();
2558 case 'contentlanguage':
2559 global $wgContLanguageCode;
2560 return $wgContLanguageCode;
2561 default:
2562 $ret = null;
2563 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2564 return $ret;
2565 else
2566 return null;
2571 * initialise the magic variables (like CURRENTMONTHNAME)
2573 * @private
2575 function initialiseVariables() {
2576 $fname = 'Parser::initialiseVariables';
2577 wfProfileIn( $fname );
2578 $variableIDs = MagicWord::getVariableIDs();
2580 $this->mVariables = array();
2581 foreach ( $variableIDs as $id ) {
2582 $mw =& MagicWord::get( $id );
2583 $mw->addToArray( $this->mVariables, $id );
2585 wfProfileOut( $fname );
2589 * parse any parentheses in format ((title|part|part))
2590 * and call callbacks to get a replacement text for any found piece
2592 * @param string $text The text to parse
2593 * @param array $callbacks rules in form:
2594 * '{' => array( # opening parentheses
2595 * 'end' => '}', # closing parentheses
2596 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2597 * 3 => callback # replacement callback to call if {{{..}}} is found
2600 * 'min' => 2, # Minimum parenthesis count in cb
2601 * 'max' => 3, # Maximum parenthesis count in cb
2602 * @private
2604 function replace_callback ($text, $callbacks) {
2605 wfProfileIn( __METHOD__ );
2606 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2607 $lastOpeningBrace = -1; # last not closed parentheses
2609 $validOpeningBraces = implode( '', array_keys( $callbacks ) );
2611 $i = 0;
2612 while ( $i < strlen( $text ) ) {
2613 # Find next opening brace, closing brace or pipe
2614 if ( $lastOpeningBrace == -1 ) {
2615 $currentClosing = '';
2616 $search = $validOpeningBraces;
2617 } else {
2618 $currentClosing = $openingBraceStack[$lastOpeningBrace]['braceEnd'];
2619 $search = $validOpeningBraces . '|' . $currentClosing;
2621 $rule = null;
2622 $i += strcspn( $text, $search, $i );
2623 if ( $i < strlen( $text ) ) {
2624 if ( $text[$i] == '|' ) {
2625 $found = 'pipe';
2626 } elseif ( $text[$i] == $currentClosing ) {
2627 $found = 'close';
2628 } elseif ( isset( $callbacks[$text[$i]] ) ) {
2629 $found = 'open';
2630 $rule = $callbacks[$text[$i]];
2631 } else {
2632 # Some versions of PHP have a strcspn which stops on null characters
2633 # Ignore and continue
2634 ++$i;
2635 continue;
2637 } else {
2638 # All done
2639 break;
2642 if ( $found == 'open' ) {
2643 # found opening brace, let's add it to parentheses stack
2644 $piece = array('brace' => $text[$i],
2645 'braceEnd' => $rule['end'],
2646 'title' => '',
2647 'parts' => null);
2649 # count opening brace characters
2650 $piece['count'] = strspn( $text, $piece['brace'], $i );
2651 $piece['startAt'] = $piece['partStart'] = $i + $piece['count'];
2652 $i += $piece['count'];
2654 # we need to add to stack only if opening brace count is enough for one of the rules
2655 if ( $piece['count'] >= $rule['min'] ) {
2656 $lastOpeningBrace ++;
2657 $openingBraceStack[$lastOpeningBrace] = $piece;
2659 } elseif ( $found == 'close' ) {
2660 # lets check if it is enough characters for closing brace
2661 $maxCount = $openingBraceStack[$lastOpeningBrace]['count'];
2662 $count = strspn( $text, $text[$i], $i, $maxCount );
2664 # check for maximum matching characters (if there are 5 closing
2665 # characters, we will probably need only 3 - depending on the rules)
2666 $matchingCount = 0;
2667 $matchingCallback = null;
2668 $cbType = $callbacks[$openingBraceStack[$lastOpeningBrace]['brace']];
2669 if ( $count > $cbType['max'] ) {
2670 # The specified maximum exists in the callback array, unless the caller
2671 # has made an error
2672 $matchingCount = $cbType['max'];
2673 } else {
2674 # Count is less than the maximum
2675 # Skip any gaps in the callback array to find the true largest match
2676 # Need to use array_key_exists not isset because the callback can be null
2677 $matchingCount = $count;
2678 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $cbType['cb'] ) ) {
2679 --$matchingCount;
2683 if ($matchingCount <= 0) {
2684 $i += $count;
2685 continue;
2687 $matchingCallback = $cbType['cb'][$matchingCount];
2689 # let's set a title or last part (if '|' was found)
2690 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2691 $openingBraceStack[$lastOpeningBrace]['title'] =
2692 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2693 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2694 } else {
2695 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2696 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2697 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2700 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2701 $pieceEnd = $i + $matchingCount;
2703 if( is_callable( $matchingCallback ) ) {
2704 $cbArgs = array (
2705 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2706 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2707 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2708 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == "\n")),
2710 # finally we can call a user callback and replace piece of text
2711 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2712 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2713 $i = $pieceStart + strlen($replaceWith);
2714 } else {
2715 # null value for callback means that parentheses should be parsed, but not replaced
2716 $i += $matchingCount;
2719 # reset last opening parentheses, but keep it in case there are unused characters
2720 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2721 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2722 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2723 'title' => '',
2724 'parts' => null,
2725 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2726 $openingBraceStack[$lastOpeningBrace--] = null;
2728 if ($matchingCount < $piece['count']) {
2729 $piece['count'] -= $matchingCount;
2730 $piece['startAt'] -= $matchingCount;
2731 $piece['partStart'] = $piece['startAt'];
2732 # do we still qualify for any callback with remaining count?
2733 $currentCbList = $callbacks[$piece['brace']]['cb'];
2734 while ( $piece['count'] ) {
2735 if ( array_key_exists( $piece['count'], $currentCbList ) ) {
2736 $lastOpeningBrace++;
2737 $openingBraceStack[$lastOpeningBrace] = $piece;
2738 break;
2740 --$piece['count'];
2743 } elseif ( $found == 'pipe' ) {
2744 # lets set a title if it is a first separator, or next part otherwise
2745 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2746 $openingBraceStack[$lastOpeningBrace]['title'] =
2747 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2748 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2749 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2750 } else {
2751 $openingBraceStack[$lastOpeningBrace]['parts'][] =
2752 substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'],
2753 $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2755 $openingBraceStack[$lastOpeningBrace]['partStart'] = ++$i;
2759 wfProfileOut( __METHOD__ );
2760 return $text;
2764 * Replace magic variables, templates, and template arguments
2765 * with the appropriate text. Templates are substituted recursively,
2766 * taking care to avoid infinite loops.
2768 * Note that the substitution depends on value of $mOutputType:
2769 * OT_WIKI: only {{subst:}} templates
2770 * OT_MSG: only magic variables
2771 * OT_HTML: all templates and magic variables
2773 * @param string $tex The text to transform
2774 * @param array $args Key-value pairs representing template parameters to substitute
2775 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2776 * @private
2778 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2779 # Prevent too big inclusions
2780 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2781 return $text;
2784 $fname = __METHOD__ /*. '-L' . count( $this->mArgStack )*/;
2785 wfProfileIn( $fname );
2787 # This function is called recursively. To keep track of arguments we need a stack:
2788 array_push( $this->mArgStack, $args );
2790 $braceCallbacks = array();
2791 if ( !$argsOnly ) {
2792 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2794 if ( $this->mOutputType != OT_MSG ) {
2795 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2797 if ( $braceCallbacks ) {
2798 $callbacks = array(
2799 '{' => array(
2800 'end' => '}',
2801 'cb' => $braceCallbacks,
2802 'min' => $argsOnly ? 3 : 2,
2803 'max' => isset( $braceCallbacks[3] ) ? 3 : 2,
2805 '[' => array(
2806 'end' => ']',
2807 'cb' => array(2=>null),
2808 'min' => 2,
2809 'max' => 2,
2812 $text = $this->replace_callback ($text, $callbacks);
2814 array_pop( $this->mArgStack );
2816 wfProfileOut( $fname );
2817 return $text;
2821 * Replace magic variables
2822 * @private
2824 function variableSubstitution( $matches ) {
2825 global $wgContLang;
2826 $fname = 'Parser::variableSubstitution';
2827 $varname = $wgContLang->lc($matches[1]);
2828 wfProfileIn( $fname );
2829 $skip = false;
2830 if ( $this->mOutputType == OT_WIKI ) {
2831 # Do only magic variables prefixed by SUBST
2832 $mwSubst =& MagicWord::get( 'subst' );
2833 if (!$mwSubst->matchStartAndRemove( $varname ))
2834 $skip = true;
2835 # Note that if we don't substitute the variable below,
2836 # we don't remove the {{subst:}} magic word, in case
2837 # it is a template rather than a magic variable.
2839 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2840 $id = $this->mVariables[$varname];
2841 # Now check if we did really match, case sensitive or not
2842 $mw =& MagicWord::get( $id );
2843 if ($mw->match($matches[1])) {
2844 $text = $this->getVariableValue( $id );
2845 $this->mOutput->mContainsOldMagic = true;
2846 } else {
2847 $text = $matches[0];
2849 } else {
2850 $text = $matches[0];
2852 wfProfileOut( $fname );
2853 return $text;
2857 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2858 static function createAssocArgs( $args ) {
2859 $assocArgs = array();
2860 $index = 1;
2861 foreach( $args as $arg ) {
2862 $eqpos = strpos( $arg, '=' );
2863 if ( $eqpos === false ) {
2864 $assocArgs[$index++] = $arg;
2865 } else {
2866 $name = trim( substr( $arg, 0, $eqpos ) );
2867 $value = trim( substr( $arg, $eqpos+1 ) );
2868 if ( $value === false ) {
2869 $value = '';
2871 if ( $name !== false ) {
2872 $assocArgs[$name] = $value;
2877 return $assocArgs;
2881 * Return the text of a template, after recursively
2882 * replacing any variables or templates within the template.
2884 * @param array $piece The parts of the template
2885 * $piece['text']: matched text
2886 * $piece['title']: the title, i.e. the part before the |
2887 * $piece['parts']: the parameter array
2888 * @return string the text of the template
2889 * @private
2891 function braceSubstitution( $piece ) {
2892 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2893 $fname = __METHOD__ /*. '-L' . count( $this->mArgStack )*/;
2894 wfProfileIn( $fname );
2895 wfProfileIn( __METHOD__.'-setup' );
2897 # Flags
2898 $found = false; # $text has been filled
2899 $nowiki = false; # wiki markup in $text should be escaped
2900 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2901 $noargs = false; # Don't replace triple-brace arguments in $text
2902 $replaceHeadings = false; # Make the edit section links go to the template not the article
2903 $headingOffset = 0; # Skip headings when number, to account for those that weren't transcluded.
2904 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2905 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2907 # Title object, where $text came from
2908 $title = NULL;
2910 $linestart = '';
2913 # $part1 is the bit before the first |, and must contain only title characters
2914 # $args is a list of arguments, starting from index 0, not including $part1
2916 $titleText = $part1 = $piece['title'];
2917 # If the third subpattern matched anything, it will start with |
2919 if (null == $piece['parts']) {
2920 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2921 if ($replaceWith != $piece['text']) {
2922 $text = $replaceWith;
2923 $found = true;
2924 $noparse = true;
2925 $noargs = true;
2929 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2930 wfProfileOut( __METHOD__.'-setup' );
2932 # SUBST
2933 wfProfileIn( __METHOD__.'-modifiers' );
2934 if ( !$found ) {
2935 $mwSubst =& MagicWord::get( 'subst' );
2936 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2937 # One of two possibilities is true:
2938 # 1) Found SUBST but not in the PST phase
2939 # 2) Didn't find SUBST and in the PST phase
2940 # In either case, return without further processing
2941 $text = $piece['text'];
2942 $found = true;
2943 $noparse = true;
2944 $noargs = true;
2948 # MSG, MSGNW and RAW
2949 if ( !$found ) {
2950 # Check for MSGNW:
2951 $mwMsgnw =& MagicWord::get( 'msgnw' );
2952 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2953 $nowiki = true;
2954 } else {
2955 # Remove obsolete MSG:
2956 $mwMsg =& MagicWord::get( 'msg' );
2957 $mwMsg->matchStartAndRemove( $part1 );
2960 # Check for RAW:
2961 $mwRaw =& MagicWord::get( 'raw' );
2962 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2963 $forceRawInterwiki = true;
2966 wfProfileOut( __METHOD__.'-modifiers' );
2968 //save path level before recursing into functions & templates.
2969 $lastPathLevel = $this->mTemplatePath;
2971 # Parser functions
2972 if ( !$found ) {
2973 wfProfileIn( __METHOD__ . '-pfunc' );
2975 $colonPos = strpos( $part1, ':' );
2976 if ( $colonPos !== false ) {
2977 # Case sensitive functions
2978 $function = substr( $part1, 0, $colonPos );
2979 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2980 $function = $this->mFunctionSynonyms[1][$function];
2981 } else {
2982 # Case insensitive functions
2983 $function = strtolower( $function );
2984 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2985 $function = $this->mFunctionSynonyms[0][$function];
2986 } else {
2987 $function = false;
2990 if ( $function ) {
2991 $funcArgs = array_map( 'trim', $args );
2992 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos + 1 ) ) ), $funcArgs );
2993 $result = call_user_func_array( $this->mFunctionHooks[$function], $funcArgs );
2994 $found = true;
2996 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2997 //$noargs = true;
2998 //$noparse = true;
3000 if ( is_array( $result ) ) {
3001 if ( isset( $result[0] ) ) {
3002 $text = $linestart . $result[0];
3003 unset( $result[0] );
3006 // Extract flags into the local scope
3007 // This allows callers to set flags such as nowiki, noparse, found, etc.
3008 extract( $result );
3009 } else {
3010 $text = $linestart . $result;
3014 wfProfileOut( __METHOD__ . '-pfunc' );
3017 # Template table test
3019 # Did we encounter this template already? If yes, it is in the cache
3020 # and we need to check for loops.
3021 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
3022 $found = true;
3024 # Infinite loop test
3025 if ( isset( $this->mTemplatePath[$part1] ) ) {
3026 $noparse = true;
3027 $noargs = true;
3028 $found = true;
3029 $text = $linestart .
3030 "[[$part1]]<!-- WARNING: template loop detected -->";
3031 wfDebug( __METHOD__.": template loop broken at '$part1'\n" );
3032 } else {
3033 # set $text to cached message.
3034 $text = $linestart . $this->mTemplates[$piece['title']];
3035 #treat title for cached page the same as others
3036 $ns = NS_TEMPLATE;
3037 $subpage = '';
3038 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3039 if ($subpage !== '') {
3040 $ns = $this->mTitle->getNamespace();
3042 $title = Title::newFromText( $part1, $ns );
3043 //used by include size checking
3044 $titleText = $title->getPrefixedText();
3045 //used by edit section links
3046 $replaceHeadings = true;
3051 # Load from database
3052 if ( !$found ) {
3053 wfProfileIn( __METHOD__ . '-loadtpl' );
3054 $ns = NS_TEMPLATE;
3055 # declaring $subpage directly in the function call
3056 # does not work correctly with references and breaks
3057 # {{/subpage}}-style inclusions
3058 $subpage = '';
3059 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3060 if ($subpage !== '') {
3061 $ns = $this->mTitle->getNamespace();
3063 $title = Title::newFromText( $part1, $ns );
3066 if ( !is_null( $title ) ) {
3067 $titleText = $title->getPrefixedText();
3068 # Check for language variants if the template is not found
3069 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3070 $wgContLang->findVariantLink($part1, $title);
3073 if ( !$title->isExternal() ) {
3074 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
3075 $text = SpecialPage::capturePath( $title );
3076 if ( is_string( $text ) ) {
3077 $found = true;
3078 $noparse = true;
3079 $noargs = true;
3080 $isHTML = true;
3081 $this->disableCache();
3083 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3084 $found = false; //access denied
3085 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3086 } else {
3087 $articleContent = $this->fetchTemplate( $title );
3088 if ( $articleContent !== false ) {
3089 $found = true;
3090 $text = $articleContent;
3091 $replaceHeadings = true;
3095 # If the title is valid but undisplayable, make a link to it
3096 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3097 $text = "[[:$titleText]]";
3098 $found = true;
3100 } elseif ( $title->isTrans() ) {
3101 // Interwiki transclusion
3102 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3103 $text = $this->interwikiTransclude( $title, 'render' );
3104 $isHTML = true;
3105 $noparse = true;
3106 } else {
3107 $text = $this->interwikiTransclude( $title, 'raw' );
3108 $replaceHeadings = true;
3110 $found = true;
3113 # Template cache array insertion
3114 # Use the original $piece['title'] not the mangled $part1, so that
3115 # modifiers such as RAW: produce separate cache entries
3116 if( $found ) {
3117 if( $isHTML ) {
3118 // A special page; don't store it in the template cache.
3119 } else {
3120 $this->mTemplates[$piece['title']] = $text;
3122 $text = $linestart . $text;
3125 wfProfileOut( __METHOD__ . '-loadtpl' );
3128 if ( $found && !$this->incrementIncludeSize( 'pre-expand', strlen( $text ) ) ) {
3129 # Error, oversize inclusion
3130 $text = $linestart .
3131 "[[$titleText]]<!-- WARNING: template omitted, pre-expand include size too large -->";
3132 $noparse = true;
3133 $noargs = true;
3136 # Recursive parsing, escaping and link table handling
3137 # Only for HTML output
3138 if ( $nowiki && $found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3139 $text = wfEscapeWikiText( $text );
3140 } elseif ( !$this->ot['msg'] && $found ) {
3141 if ( $noargs ) {
3142 $assocArgs = array();
3143 } else {
3144 # Clean up argument array
3145 $assocArgs = self::createAssocArgs($args);
3146 # Add a new element to the templace recursion path
3147 $this->mTemplatePath[$part1] = 1;
3150 if ( !$noparse ) {
3151 # If there are any <onlyinclude> tags, only include them
3152 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3153 $replacer = new OnlyIncludeReplacer;
3154 StringUtils::delimiterReplaceCallback( '<onlyinclude>', '</onlyinclude>',
3155 array( &$replacer, 'replace' ), $text );
3156 $text = $replacer->output;
3158 # Remove <noinclude> sections and <includeonly> tags
3159 $text = StringUtils::delimiterReplace( '<noinclude>', '</noinclude>', '', $text );
3160 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3162 if( $this->ot['html'] || $this->ot['pre'] ) {
3163 # Strip <nowiki>, <pre>, etc.
3164 $text = $this->strip( $text, $this->mStripState );
3165 if ( $this->ot['html'] ) {
3166 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3167 } elseif ( $this->ot['pre'] && $this->mOptions->getRemoveComments() ) {
3168 $text = Sanitizer::removeHTMLcomments( $text );
3171 $text = $this->replaceVariables( $text, $assocArgs );
3173 # If the template begins with a table or block-level
3174 # element, it should be treated as beginning a new line.
3175 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) /*}*/{
3176 $text = "\n" . $text;
3178 } elseif ( !$noargs ) {
3179 # $noparse and !$noargs
3180 # Just replace the arguments, not any double-brace items
3181 # This is used for rendered interwiki transclusion
3182 $text = $this->replaceVariables( $text, $assocArgs, true );
3185 # Prune lower levels off the recursion check path
3186 $this->mTemplatePath = $lastPathLevel;
3188 if ( $found && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3189 # Error, oversize inclusion
3190 $text = $linestart .
3191 "[[$titleText]]<!-- WARNING: template omitted, post-expand include size too large -->";
3192 $noparse = true;
3193 $noargs = true;
3196 if ( !$found ) {
3197 wfProfileOut( $fname );
3198 return $piece['text'];
3199 } else {
3200 wfProfileIn( __METHOD__ . '-placeholders' );
3201 if ( $isHTML ) {
3202 # Replace raw HTML by a placeholder
3203 # Add a blank line preceding, to prevent it from mucking up
3204 # immediately preceding headings
3205 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
3206 } else {
3207 # replace ==section headers==
3208 # XXX this needs to go away once we have a better parser.
3209 if ( !$this->ot['wiki'] && !$this->ot['pre'] && $replaceHeadings ) {
3210 if( !is_null( $title ) )
3211 $encodedname = base64_encode($title->getPrefixedDBkey());
3212 else
3213 $encodedname = base64_encode("");
3214 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3215 PREG_SPLIT_DELIM_CAPTURE);
3216 $text = '';
3217 $nsec = $headingOffset;
3218 for( $i = 0; $i < count($m); $i += 2 ) {
3219 $text .= $m[$i];
3220 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
3221 $hl = $m[$i + 1];
3222 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3223 $text .= $hl;
3224 continue;
3226 $m2 = array();
3227 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3228 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3229 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3231 $nsec++;
3235 wfProfileOut( __METHOD__ . '-placeholders' );
3238 # Prune lower levels off the recursion check path
3239 $this->mTemplatePath = $lastPathLevel;
3241 if ( !$found ) {
3242 wfProfileOut( $fname );
3243 return $piece['text'];
3244 } else {
3245 wfProfileOut( $fname );
3246 return $text;
3251 * Fetch the unparsed text of a template and register a reference to it.
3253 function fetchTemplate( $title ) {
3254 $text = false;
3255 // Loop to fetch the article, with up to 1 redirect
3256 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3257 $rev = Revision::newFromTitle( $title );
3258 $this->mOutput->addTemplate( $title, $title->getArticleID() );
3259 if ( $rev ) {
3260 $text = $rev->getText();
3261 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3262 global $wgLang;
3263 $message = $wgLang->lcfirst( $title->getText() );
3264 $text = wfMsgForContentNoTrans( $message );
3265 if( wfEmptyMsg( $message, $text ) ) {
3266 $text = false;
3267 break;
3269 } else {
3270 break;
3272 if ( $text === false ) {
3273 break;
3275 // Redirect?
3276 $title = Title::newFromRedirect( $text );
3278 return $text;
3282 * Transclude an interwiki link.
3284 function interwikiTransclude( $title, $action ) {
3285 global $wgEnableScaryTranscluding;
3287 if (!$wgEnableScaryTranscluding)
3288 return wfMsg('scarytranscludedisabled');
3290 $url = $title->getFullUrl( "action=$action" );
3292 if (strlen($url) > 255)
3293 return wfMsg('scarytranscludetoolong');
3294 return $this->fetchScaryTemplateMaybeFromCache($url);
3297 function fetchScaryTemplateMaybeFromCache($url) {
3298 global $wgTranscludeCacheExpiry;
3299 $dbr = wfGetDB(DB_SLAVE);
3300 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3301 array('tc_url' => $url));
3302 if ($obj) {
3303 $time = $obj->tc_time;
3304 $text = $obj->tc_contents;
3305 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3306 return $text;
3310 $text = Http::get($url);
3311 if (!$text)
3312 return wfMsg('scarytranscludefailed', $url);
3314 $dbw = wfGetDB(DB_MASTER);
3315 $dbw->replace('transcache', array('tc_url'), array(
3316 'tc_url' => $url,
3317 'tc_time' => time(),
3318 'tc_contents' => $text));
3319 return $text;
3324 * Triple brace replacement -- used for template arguments
3325 * @private
3327 function argSubstitution( $matches ) {
3328 $arg = trim( $matches['title'] );
3329 $text = $matches['text'];
3330 $inputArgs = end( $this->mArgStack );
3332 if ( array_key_exists( $arg, $inputArgs ) ) {
3333 $text = $inputArgs[$arg];
3334 } else if (($this->mOutputType == OT_HTML || $this->mOutputType == OT_PREPROCESS ) &&
3335 null != $matches['parts'] && count($matches['parts']) > 0) {
3336 $text = $matches['parts'][0];
3338 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3339 $text = $matches['text'] .
3340 '<!-- WARNING: argument omitted, expansion size too large -->';
3343 return $text;
3347 * Increment an include size counter
3349 * @param string $type The type of expansion
3350 * @param integer $size The size of the text
3351 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3353 function incrementIncludeSize( $type, $size ) {
3354 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3355 return false;
3356 } else {
3357 $this->mIncludeSizes[$type] += $size;
3358 return true;
3363 * Detect __NOGALLERY__ magic word and set a placeholder
3365 function stripNoGallery( &$text ) {
3366 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3367 # do not add TOC
3368 $mw = MagicWord::get( 'nogallery' );
3369 $this->mOutput->mNoGallery = $mw->matchAndRemove( $text ) ;
3373 * Detect __TOC__ magic word and set a placeholder
3375 function stripToc( $text ) {
3376 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3377 # do not add TOC
3378 $mw = MagicWord::get( 'notoc' );
3379 if( $mw->matchAndRemove( $text ) ) {
3380 $this->mShowToc = false;
3383 $mw = MagicWord::get( 'toc' );
3384 if( $mw->match( $text ) ) {
3385 $this->mShowToc = true;
3386 $this->mForceTocPosition = true;
3388 // Set a placeholder. At the end we'll fill it in with the TOC.
3389 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3391 // Only keep the first one.
3392 $text = $mw->replace( '', $text );
3394 return $text;
3398 * This function accomplishes several tasks:
3399 * 1) Auto-number headings if that option is enabled
3400 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3401 * 3) Add a Table of contents on the top for users who have enabled the option
3402 * 4) Auto-anchor headings
3404 * It loops through all headlines, collects the necessary data, then splits up the
3405 * string and re-inserts the newly formatted headlines.
3407 * @param string $text
3408 * @param boolean $isMain
3409 * @private
3411 function formatHeadings( $text, $isMain=true ) {
3412 global $wgMaxTocLevel, $wgContLang;
3414 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3415 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3416 $showEditLink = 0;
3417 } else {
3418 $showEditLink = $this->mOptions->getEditSection();
3421 # Inhibit editsection links if requested in the page
3422 $esw =& MagicWord::get( 'noeditsection' );
3423 if( $esw->matchAndRemove( $text ) ) {
3424 $showEditLink = 0;
3427 # Get all headlines for numbering them and adding funky stuff like [edit]
3428 # links - this is for later, but we need the number of headlines right now
3429 $matches = array();
3430 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3432 # if there are fewer than 4 headlines in the article, do not show TOC
3433 # unless it's been explicitly enabled.
3434 $enoughToc = $this->mShowToc &&
3435 (($numMatches >= 4) || $this->mForceTocPosition);
3437 # Allow user to stipulate that a page should have a "new section"
3438 # link added via __NEWSECTIONLINK__
3439 $mw =& MagicWord::get( 'newsectionlink' );
3440 if( $mw->matchAndRemove( $text ) )
3441 $this->mOutput->setNewSection( true );
3443 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3444 # override above conditions and always show TOC above first header
3445 $mw =& MagicWord::get( 'forcetoc' );
3446 if ($mw->matchAndRemove( $text ) ) {
3447 $this->mShowToc = true;
3448 $enoughToc = true;
3451 # Never ever show TOC if no headers
3452 if( $numMatches < 1 ) {
3453 $enoughToc = false;
3456 # We need this to perform operations on the HTML
3457 $sk = $this->mOptions->getSkin();
3459 # headline counter
3460 $headlineCount = 0;
3461 $sectionCount = 0; # headlineCount excluding template sections
3463 # Ugh .. the TOC should have neat indentation levels which can be
3464 # passed to the skin functions. These are determined here
3465 $toc = '';
3466 $full = '';
3467 $head = array();
3468 $sublevelCount = array();
3469 $levelCount = array();
3470 $toclevel = 0;
3471 $level = 0;
3472 $prevlevel = 0;
3473 $toclevel = 0;
3474 $prevtoclevel = 0;
3476 foreach( $matches[3] as $headline ) {
3477 $istemplate = 0;
3478 $templatetitle = '';
3479 $templatesection = 0;
3480 $numbering = '';
3481 $mat = array();
3482 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3483 $istemplate = 1;
3484 $templatetitle = base64_decode($mat[1]);
3485 $templatesection = 1 + (int)base64_decode($mat[2]);
3486 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3489 if( $toclevel ) {
3490 $prevlevel = $level;
3491 $prevtoclevel = $toclevel;
3493 $level = $matches[1][$headlineCount];
3495 if( $doNumberHeadings || $enoughToc ) {
3497 if ( $level > $prevlevel ) {
3498 # Increase TOC level
3499 $toclevel++;
3500 $sublevelCount[$toclevel] = 0;
3501 if( $toclevel<$wgMaxTocLevel ) {
3502 $toc .= $sk->tocIndent();
3505 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3506 # Decrease TOC level, find level to jump to
3508 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3509 # Can only go down to level 1
3510 $toclevel = 1;
3511 } else {
3512 for ($i = $toclevel; $i > 0; $i--) {
3513 if ( $levelCount[$i] == $level ) {
3514 # Found last matching level
3515 $toclevel = $i;
3516 break;
3518 elseif ( $levelCount[$i] < $level ) {
3519 # Found first matching level below current level
3520 $toclevel = $i + 1;
3521 break;
3525 if( $toclevel<$wgMaxTocLevel ) {
3526 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3529 else {
3530 # No change in level, end TOC line
3531 if( $toclevel<$wgMaxTocLevel ) {
3532 $toc .= $sk->tocLineEnd();
3536 $levelCount[$toclevel] = $level;
3538 # count number of headlines for each level
3539 @$sublevelCount[$toclevel]++;
3540 $dot = 0;
3541 for( $i = 1; $i <= $toclevel; $i++ ) {
3542 if( !empty( $sublevelCount[$i] ) ) {
3543 if( $dot ) {
3544 $numbering .= '.';
3546 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3547 $dot = 1;
3552 # The canonized header is a version of the header text safe to use for links
3553 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3554 $canonized_headline = $this->mStripState->unstripBoth( $headline );
3556 # Remove link placeholders by the link text.
3557 # <!--LINK number-->
3558 # turns into
3559 # link text with suffix
3560 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3561 "\$this->mLinkHolders['texts'][\$1]",
3562 $canonized_headline );
3563 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3564 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3565 $canonized_headline );
3567 # strip out HTML
3568 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3569 $tocline = trim( $canonized_headline );
3570 # Save headline for section edit hint before it's escaped
3571 $headline_hint = trim( $canonized_headline );
3572 $canonized_headline = Sanitizer::escapeId( $tocline );
3573 $refers[$headlineCount] = $canonized_headline;
3575 # count how many in assoc. array so we can track dupes in anchors
3576 isset( $refers[$canonized_headline] ) ? $refers[$canonized_headline]++ : $refers[$canonized_headline] = 1;
3577 $refcount[$headlineCount]=$refers[$canonized_headline];
3579 # Don't number the heading if it is the only one (looks silly)
3580 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3581 # the two are different if the line contains a link
3582 $headline=$numbering . ' ' . $headline;
3585 # Create the anchor for linking from the TOC to the section
3586 $anchor = $canonized_headline;
3587 if($refcount[$headlineCount] > 1 ) {
3588 $anchor .= '_' . $refcount[$headlineCount];
3590 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3591 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3593 # give headline the correct <h#> tag
3594 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3595 if( $istemplate )
3596 $editlink = $sk->editSectionLinkForOther($templatetitle, $templatesection);
3597 else
3598 $editlink = $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3599 } else {
3600 $editlink = '';
3602 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3604 $headlineCount++;
3605 if( !$istemplate )
3606 $sectionCount++;
3609 if( $enoughToc ) {
3610 if( $toclevel<$wgMaxTocLevel ) {
3611 $toc .= $sk->tocUnindent( $toclevel - 1 );
3613 $toc = $sk->tocList( $toc );
3616 # split up and insert constructed headlines
3618 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3619 $i = 0;
3621 foreach( $blocks as $block ) {
3622 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3623 # This is the [edit] link that appears for the top block of text when
3624 # section editing is enabled
3626 # Disabled because it broke block formatting
3627 # For example, a bullet point in the top line
3628 # $full .= $sk->editSectionLink(0);
3630 $full .= $block;
3631 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3632 # Top anchor now in skin
3633 $full = $full.$toc;
3636 if( !empty( $head[$i] ) ) {
3637 $full .= $head[$i];
3639 $i++;
3641 if( $this->mForceTocPosition ) {
3642 return str_replace( '<!--MWTOC-->', $toc, $full );
3643 } else {
3644 return $full;
3649 * Transform wiki markup when saving a page by doing \r\n -> \n
3650 * conversion, substitting signatures, {{subst:}} templates, etc.
3652 * @param string $text the text to transform
3653 * @param Title &$title the Title object for the current article
3654 * @param User &$user the User object describing the current user
3655 * @param ParserOptions $options parsing options
3656 * @param bool $clearState whether to clear the parser state first
3657 * @return string the altered wiki markup
3658 * @public
3660 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3661 $this->mOptions = $options;
3662 $this->mTitle =& $title;
3663 $this->setOutputType( OT_WIKI );
3665 if ( $clearState ) {
3666 $this->clearState();
3669 $stripState = new StripState;
3670 $pairs = array(
3671 "\r\n" => "\n",
3673 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3674 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3675 $text = $this->pstPass2( $text, $stripState, $user );
3676 $text = $stripState->unstripBoth( $text );
3677 return $text;
3681 * Pre-save transform helper function
3682 * @private
3684 function pstPass2( $text, &$stripState, $user ) {
3685 global $wgContLang, $wgLocaltimezone;
3687 /* Note: This is the timestamp saved as hardcoded wikitext to
3688 * the database, we use $wgContLang here in order to give
3689 * everyone the same signature and use the default one rather
3690 * than the one selected in each user's preferences.
3692 if ( isset( $wgLocaltimezone ) ) {
3693 $oldtz = getenv( 'TZ' );
3694 putenv( 'TZ='.$wgLocaltimezone );
3696 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3697 ' (' . date( 'T' ) . ')';
3698 if ( isset( $wgLocaltimezone ) ) {
3699 putenv( 'TZ='.$oldtz );
3702 # Variable replacement
3703 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3704 $text = $this->replaceVariables( $text );
3706 # Strip out <nowiki> etc. added via replaceVariables
3707 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3709 # Signatures
3710 $sigText = $this->getUserSig( $user );
3711 $text = strtr( $text, array(
3712 '~~~~~' => $d,
3713 '~~~~' => "$sigText $d",
3714 '~~~' => $sigText
3715 ) );
3717 # Context links: [[|name]] and [[name (context)|]]
3719 global $wgLegalTitleChars;
3720 $tc = "[$wgLegalTitleChars]";
3721 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3723 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3724 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3725 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3727 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3728 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3729 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3731 $t = $this->mTitle->getText();
3732 $m = array();
3733 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3734 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3735 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3736 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3737 } else {
3738 # if there's no context, don't bother duplicating the title
3739 $text = preg_replace( $p2, '[[\\1]]', $text );
3742 # Trim trailing whitespace
3743 $text = rtrim( $text );
3745 return $text;
3749 * Fetch the user's signature text, if any, and normalize to
3750 * validated, ready-to-insert wikitext.
3752 * @param User $user
3753 * @return string
3754 * @private
3756 function getUserSig( &$user ) {
3757 $username = $user->getName();
3758 $nickname = $user->getOption( 'nickname' );
3759 $nickname = $nickname === '' ? $username : $nickname;
3761 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3762 # Sig. might contain markup; validate this
3763 if( $this->validateSig( $nickname ) !== false ) {
3764 # Validated; clean up (if needed) and return it
3765 return $this->cleanSig( $nickname, true );
3766 } else {
3767 # Failed to validate; fall back to the default
3768 $nickname = $username;
3769 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3773 // Make sure nickname doesnt get a sig in a sig
3774 $nickname = $this->cleanSigInSig( $nickname );
3776 # If we're still here, make it a link to the user page
3777 $userpage = $user->getUserPage();
3778 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3782 * Check that the user's signature contains no bad XML
3784 * @param string $text
3785 * @return mixed An expanded string, or false if invalid.
3787 function validateSig( $text ) {
3788 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3792 * Clean up signature text
3794 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3795 * 2) Substitute all transclusions
3797 * @param string $text
3798 * @param $parsing Whether we're cleaning (preferences save) or parsing
3799 * @return string Signature text
3801 function cleanSig( $text, $parsing = false ) {
3802 global $wgTitle;
3803 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI : OT_MSG );
3805 $substWord = MagicWord::get( 'subst' );
3806 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3807 $substText = '{{' . $substWord->getSynonym( 0 );
3809 $text = preg_replace( $substRegex, $substText, $text );
3810 $text = $this->cleanSigInSig( $text );
3811 $text = $this->replaceVariables( $text );
3813 $this->clearState();
3814 return $text;
3818 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3819 * @param string $text
3820 * @return string Signature text with /~{3,5}/ removed
3822 function cleanSigInSig( $text ) {
3823 $text = preg_replace( '/~{3,5}/', '', $text );
3824 return $text;
3828 * Set up some variables which are usually set up in parse()
3829 * so that an external function can call some class members with confidence
3830 * @public
3832 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3833 $this->mTitle =& $title;
3834 $this->mOptions = $options;
3835 $this->setOutputType( $outputType );
3836 if ( $clearState ) {
3837 $this->clearState();
3842 * Transform a MediaWiki message by replacing magic variables.
3844 * @param string $text the text to transform
3845 * @param ParserOptions $options options
3846 * @return string the text with variables substituted
3847 * @public
3849 function transformMsg( $text, $options ) {
3850 global $wgTitle;
3851 static $executing = false;
3853 $fname = "Parser::transformMsg";
3855 # Guard against infinite recursion
3856 if ( $executing ) {
3857 return $text;
3859 $executing = true;
3861 wfProfileIn($fname);
3863 if ( $wgTitle && !( $wgTitle instanceof FakeTitle ) ) {
3864 $this->mTitle = $wgTitle;
3865 } else {
3866 $this->mTitle = Title::newFromText('msg');
3868 $this->mOptions = $options;
3869 $this->setOutputType( OT_MSG );
3870 $this->clearState();
3871 $text = $this->replaceVariables( $text );
3873 $executing = false;
3874 wfProfileOut($fname);
3875 return $text;
3879 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3880 * The callback should have the following form:
3881 * function myParserHook( $text, $params, &$parser ) { ... }
3883 * Transform and return $text. Use $parser for any required context, e.g. use
3884 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3886 * @public
3888 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3889 * @param mixed $callback The callback function (and object) to use for the tag
3891 * @return The old value of the mTagHooks array associated with the hook
3893 function setHook( $tag, $callback ) {
3894 $tag = strtolower( $tag );
3895 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
3896 $this->mTagHooks[$tag] = $callback;
3898 return $oldVal;
3902 * Create a function, e.g. {{sum:1|2|3}}
3903 * The callback function should have the form:
3904 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3906 * The callback may either return the text result of the function, or an array with the text
3907 * in element 0, and a number of flags in the other elements. The names of the flags are
3908 * specified in the keys. Valid flags are:
3909 * found The text returned is valid, stop processing the template. This
3910 * is on by default.
3911 * nowiki Wiki markup in the return value should be escaped
3912 * noparse Unsafe HTML tags should not be stripped, etc.
3913 * noargs Don't replace triple-brace arguments in the return value
3914 * isHTML The returned text is HTML, armour it against wikitext transformation
3916 * @public
3918 * @param string $id The magic word ID
3919 * @param mixed $callback The callback function (and object) to use
3920 * @param integer $flags a combination of the following flags:
3921 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3923 * @return The old callback function for this name, if any
3925 function setFunctionHook( $id, $callback, $flags = 0 ) {
3926 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id] : null;
3927 $this->mFunctionHooks[$id] = $callback;
3929 # Add to function cache
3930 $mw = MagicWord::get( $id );
3931 if( !$mw )
3932 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3934 $synonyms = $mw->getSynonyms();
3935 $sensitive = intval( $mw->isCaseSensitive() );
3937 foreach ( $synonyms as $syn ) {
3938 # Case
3939 if ( !$sensitive ) {
3940 $syn = strtolower( $syn );
3942 # Add leading hash
3943 if ( !( $flags & SFH_NO_HASH ) ) {
3944 $syn = '#' . $syn;
3946 # Remove trailing colon
3947 if ( substr( $syn, -1, 1 ) == ':' ) {
3948 $syn = substr( $syn, 0, -1 );
3950 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
3952 return $oldVal;
3956 * Get all registered function hook identifiers
3958 * @return array
3960 function getFunctionHooks() {
3961 return array_keys( $this->mFunctionHooks );
3965 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3966 * Placeholders created in Skin::makeLinkObj()
3967 * Returns an array of links found, indexed by PDBK:
3968 * 0 - broken
3969 * 1 - normal link
3970 * 2 - stub
3971 * $options is a bit field, RLH_FOR_UPDATE to select for update
3973 function replaceLinkHolders( &$text, $options = 0 ) {
3974 global $wgUser;
3975 global $wgContLang;
3977 $fname = 'Parser::replaceLinkHolders';
3978 wfProfileIn( $fname );
3980 $pdbks = array();
3981 $colours = array();
3982 $sk = $this->mOptions->getSkin();
3983 $linkCache =& LinkCache::singleton();
3985 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3986 wfProfileIn( $fname.'-check' );
3987 $dbr = wfGetDB( DB_SLAVE );
3988 $page = $dbr->tableName( 'page' );
3989 $threshold = $wgUser->getOption('stubthreshold');
3991 # Sort by namespace
3992 asort( $this->mLinkHolders['namespaces'] );
3994 # Generate query
3995 $query = false;
3996 $current = null;
3997 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3998 # Make title object
3999 $title = $this->mLinkHolders['titles'][$key];
4001 # Skip invalid entries.
4002 # Result will be ugly, but prevents crash.
4003 if ( is_null( $title ) ) {
4004 continue;
4006 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4008 # Check if it's a static known link, e.g. interwiki
4009 if ( $title->isAlwaysKnown() ) {
4010 $colours[$pdbk] = 1;
4011 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4012 $colours[$pdbk] = 1;
4013 $this->mOutput->addLink( $title, $id );
4014 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4015 $colours[$pdbk] = 0;
4016 } else {
4017 # Not in the link cache, add it to the query
4018 if ( !isset( $current ) ) {
4019 $current = $ns;
4020 $query = "SELECT page_id, page_namespace, page_title";
4021 if ( $threshold > 0 ) {
4022 $query .= ', page_len, page_is_redirect';
4024 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4025 } elseif ( $current != $ns ) {
4026 $current = $ns;
4027 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4028 } else {
4029 $query .= ', ';
4032 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
4035 if ( $query ) {
4036 $query .= '))';
4037 if ( $options & RLH_FOR_UPDATE ) {
4038 $query .= ' FOR UPDATE';
4041 $res = $dbr->query( $query, $fname );
4043 # Fetch data and form into an associative array
4044 # non-existent = broken
4045 # 1 = known
4046 # 2 = stub
4047 while ( $s = $dbr->fetchObject($res) ) {
4048 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
4049 $pdbk = $title->getPrefixedDBkey();
4050 $linkCache->addGoodLinkObj( $s->page_id, $title );
4051 $this->mOutput->addLink( $title, $s->page_id );
4053 if ( $threshold > 0 ) {
4054 $size = $s->page_len;
4055 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
4056 $colours[$pdbk] = 1;
4057 } else {
4058 $colours[$pdbk] = 2;
4060 } else {
4061 $colours[$pdbk] = 1;
4065 wfProfileOut( $fname.'-check' );
4067 # Do a second query for different language variants of links and categories
4068 if($wgContLang->hasVariants()){
4069 $linkBatch = new LinkBatch();
4070 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4071 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4072 $varCategories = array(); // category replacements oldDBkey => newDBkey
4074 $categories = $this->mOutput->getCategoryLinks();
4076 // Add variants of links to link batch
4077 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4078 $title = $this->mLinkHolders['titles'][$key];
4079 if ( is_null( $title ) )
4080 continue;
4082 $pdbk = $title->getPrefixedDBkey();
4083 $titleText = $title->getText();
4085 // generate all variants of the link title text
4086 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4088 // if link was not found (in first query), add all variants to query
4089 if ( !isset($colours[$pdbk]) ){
4090 foreach($allTextVariants as $textVariant){
4091 if($textVariant != $titleText){
4092 $variantTitle = Title::makeTitle( $ns, $textVariant );
4093 if(is_null($variantTitle)) continue;
4094 $linkBatch->addObj( $variantTitle );
4095 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4101 // process categories, check if a category exists in some variant
4102 foreach( $categories as $category){
4103 $variants = $wgContLang->convertLinkToAllVariants($category);
4104 foreach($variants as $variant){
4105 if($variant != $category){
4106 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
4107 if(is_null($variantTitle)) continue;
4108 $linkBatch->addObj( $variantTitle );
4109 $categoryMap[$variant] = $category;
4115 if(!$linkBatch->isEmpty()){
4116 // construct query
4117 $titleClause = $linkBatch->constructSet('page', $dbr);
4119 $variantQuery = "SELECT page_id, page_namespace, page_title";
4120 if ( $threshold > 0 ) {
4121 $variantQuery .= ', page_len, page_is_redirect';
4124 $variantQuery .= " FROM $page WHERE $titleClause";
4125 if ( $options & RLH_FOR_UPDATE ) {
4126 $variantQuery .= ' FOR UPDATE';
4129 $varRes = $dbr->query( $variantQuery, $fname );
4131 // for each found variants, figure out link holders and replace
4132 while ( $s = $dbr->fetchObject($varRes) ) {
4134 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4135 $varPdbk = $variantTitle->getPrefixedDBkey();
4136 $vardbk = $variantTitle->getDBkey();
4138 $holderKeys = array();
4139 if(isset($variantMap[$varPdbk])){
4140 $holderKeys = $variantMap[$varPdbk];
4141 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle );
4142 $this->mOutput->addLink( $variantTitle, $s->page_id );
4145 // loop over link holders
4146 foreach($holderKeys as $key){
4147 $title = $this->mLinkHolders['titles'][$key];
4148 if ( is_null( $title ) ) continue;
4150 $pdbk = $title->getPrefixedDBkey();
4152 if(!isset($colours[$pdbk])){
4153 // found link in some of the variants, replace the link holder data
4154 $this->mLinkHolders['titles'][$key] = $variantTitle;
4155 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4157 // set pdbk and colour
4158 $pdbks[$key] = $varPdbk;
4159 if ( $threshold > 0 ) {
4160 $size = $s->page_len;
4161 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
4162 $colours[$varPdbk] = 1;
4163 } else {
4164 $colours[$varPdbk] = 2;
4167 else {
4168 $colours[$varPdbk] = 1;
4173 // check if the object is a variant of a category
4174 if(isset($categoryMap[$vardbk])){
4175 $oldkey = $categoryMap[$vardbk];
4176 if($oldkey != $vardbk)
4177 $varCategories[$oldkey]=$vardbk;
4181 // rebuild the categories in original order (if there are replacements)
4182 if(count($varCategories)>0){
4183 $newCats = array();
4184 $originalCats = $this->mOutput->getCategories();
4185 foreach($originalCats as $cat => $sortkey){
4186 // make the replacement
4187 if( array_key_exists($cat,$varCategories) )
4188 $newCats[$varCategories[$cat]] = $sortkey;
4189 else $newCats[$cat] = $sortkey;
4191 $this->mOutput->setCategoryLinks($newCats);
4196 # Construct search and replace arrays
4197 wfProfileIn( $fname.'-construct' );
4198 $replacePairs = array();
4199 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4200 $pdbk = $pdbks[$key];
4201 $searchkey = "<!--LINK $key-->";
4202 $title = $this->mLinkHolders['titles'][$key];
4203 if ( empty( $colours[$pdbk] ) ) {
4204 $linkCache->addBadLinkObj( $title );
4205 $colours[$pdbk] = 0;
4206 $this->mOutput->addLink( $title, 0 );
4207 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4208 $this->mLinkHolders['texts'][$key],
4209 $this->mLinkHolders['queries'][$key] );
4210 } elseif ( $colours[$pdbk] == 1 ) {
4211 $replacePairs[$searchkey] = $sk->makeKnownLinkObj( $title,
4212 $this->mLinkHolders['texts'][$key],
4213 $this->mLinkHolders['queries'][$key] );
4214 } elseif ( $colours[$pdbk] == 2 ) {
4215 $replacePairs[$searchkey] = $sk->makeStubLinkObj( $title,
4216 $this->mLinkHolders['texts'][$key],
4217 $this->mLinkHolders['queries'][$key] );
4220 $replacer = new HashtableReplacer( $replacePairs, 1 );
4221 wfProfileOut( $fname.'-construct' );
4223 # Do the thing
4224 wfProfileIn( $fname.'-replace' );
4225 $text = preg_replace_callback(
4226 '/(<!--LINK .*?-->)/',
4227 $replacer->cb(),
4228 $text);
4230 wfProfileOut( $fname.'-replace' );
4233 # Now process interwiki link holders
4234 # This is quite a bit simpler than internal links
4235 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4236 wfProfileIn( $fname.'-interwiki' );
4237 # Make interwiki link HTML
4238 $replacePairs = array();
4239 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4240 $title = $this->mInterwikiLinkHolders['titles'][$key];
4241 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4243 $replacer = new HashtableReplacer( $replacePairs, 1 );
4245 $text = preg_replace_callback(
4246 '/<!--IWLINK (.*?)-->/',
4247 $replacer->cb(),
4248 $text );
4249 wfProfileOut( $fname.'-interwiki' );
4252 wfProfileOut( $fname );
4253 return $colours;
4257 * Replace <!--LINK--> link placeholders with plain text of links
4258 * (not HTML-formatted).
4259 * @param string $text
4260 * @return string
4262 function replaceLinkHoldersText( $text ) {
4263 $fname = 'Parser::replaceLinkHoldersText';
4264 wfProfileIn( $fname );
4266 $text = preg_replace_callback(
4267 '/<!--(LINK|IWLINK) (.*?)-->/',
4268 array( &$this, 'replaceLinkHoldersTextCallback' ),
4269 $text );
4271 wfProfileOut( $fname );
4272 return $text;
4276 * @param array $matches
4277 * @return string
4278 * @private
4280 function replaceLinkHoldersTextCallback( $matches ) {
4281 $type = $matches[1];
4282 $key = $matches[2];
4283 if( $type == 'LINK' ) {
4284 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4285 return $this->mLinkHolders['texts'][$key];
4287 } elseif( $type == 'IWLINK' ) {
4288 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4289 return $this->mInterwikiLinkHolders['texts'][$key];
4292 return $matches[0];
4296 * Tag hook handler for 'pre'.
4298 function renderPreTag( $text, $attribs ) {
4299 // Backwards-compatibility hack
4300 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4302 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4303 return wfOpenElement( 'pre', $attribs ) .
4304 Xml::escapeTagsOnly( $content ) .
4305 '</pre>';
4309 * Renders an image gallery from a text with one line per image.
4310 * text labels may be given by using |-style alternative text. E.g.
4311 * Image:one.jpg|The number "1"
4312 * Image:tree.jpg|A tree
4313 * given as text will return the HTML of a gallery with two images,
4314 * labeled 'The number "1"' and
4315 * 'A tree'.
4317 function renderImageGallery( $text, $params ) {
4318 $ig = new ImageGallery();
4319 $ig->setContextTitle( $this->mTitle );
4320 $ig->setShowBytes( false );
4321 $ig->setShowFilename( false );
4322 $ig->setParsing();
4323 $ig->useSkin( $this->mOptions->getSkin() );
4325 if( isset( $params['caption'] ) ) {
4326 $caption = $params['caption'];
4327 $caption = htmlspecialchars( $caption );
4328 $caption = $this->replaceInternalLinks( $caption );
4329 $ig->setCaptionHtml( $caption );
4331 if( isset( $params['perrow'] ) ) {
4332 $ig->setPerRow( $params['perrow'] );
4334 if( isset( $params['widths'] ) ) {
4335 $ig->setWidths( $params['widths'] );
4337 if( isset( $params['heights'] ) ) {
4338 $ig->setHeights( $params['heights'] );
4341 $lines = explode( "\n", $text );
4342 foreach ( $lines as $line ) {
4343 # match lines like these:
4344 # Image:someimage.jpg|This is some image
4345 $matches = array();
4346 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4347 # Skip empty lines
4348 if ( count( $matches ) == 0 ) {
4349 continue;
4351 $tp = Title::newFromText( $matches[1] );
4352 $nt =& $tp;
4353 if( is_null( $nt ) ) {
4354 # Bogus title. Ignore these so we don't bomb out later.
4355 continue;
4357 if ( isset( $matches[3] ) ) {
4358 $label = $matches[3];
4359 } else {
4360 $label = '';
4363 $pout = $this->parse( $label,
4364 $this->mTitle,
4365 $this->mOptions,
4366 false, // Strip whitespace...?
4367 false // Don't clear state!
4369 $html = $pout->getText();
4371 $ig->add( new Image( $nt ), $html );
4373 # Only add real images (bug #5586)
4374 if ( $nt->getNamespace() == NS_IMAGE ) {
4375 $this->mOutput->addImage( $nt->getDBkey() );
4378 return $ig->toHTML();
4382 * Parse image options text and use it to make an image
4384 function makeImage( $nt, $options ) {
4385 global $wgUseImageResize, $wgDjvuRenderer;
4387 # Check if the options text is of the form "options|alt text"
4388 # Options are:
4389 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4390 # * left no resizing, just left align. label is used for alt= only
4391 # * right same, but right aligned
4392 # * none same, but not aligned
4393 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4394 # * center center the image
4395 # * framed Keep original image size, no magnify-button.
4396 # vertical-align values (no % or length right now):
4397 # * baseline
4398 # * sub
4399 # * super
4400 # * top
4401 # * text-top
4402 # * middle
4403 # * bottom
4404 # * text-bottom
4406 $part = array_map( 'trim', explode( '|', $options) );
4408 $mwAlign = array();
4409 $alignments = array( 'left', 'right', 'center', 'none', 'baseline', 'sub', 'super', 'top', 'text-top', 'middle', 'bottom', 'text-bottom' );
4410 foreach ( $alignments as $alignment ) {
4411 $mwAlign[$alignment] =& MagicWord::get( 'img_'.$alignment );
4413 $mwThumb =& MagicWord::get( 'img_thumbnail' );
4414 $mwManualThumb =& MagicWord::get( 'img_manualthumb' );
4415 $mwWidth =& MagicWord::get( 'img_width' );
4416 $mwFramed =& MagicWord::get( 'img_framed' );
4417 $mwPage =& MagicWord::get( 'img_page' );
4418 $caption = '';
4420 $width = $height = $framed = $thumb = false;
4421 $page = null;
4422 $manual_thumb = '' ;
4423 $align = $valign = '';
4425 foreach( $part as $val ) {
4426 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4427 $thumb=true;
4428 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4429 # use manually specified thumbnail
4430 $thumb=true;
4431 $manual_thumb = $match;
4432 } else {
4433 foreach( $alignments as $alignment ) {
4434 if ( ! is_null( $mwAlign[$alignment]->matchVariableStartToEnd($val) ) ) {
4435 switch ( $alignment ) {
4436 case 'left': case 'right': case 'center': case 'none':
4437 $align = $alignment; break;
4438 default:
4439 $valign = $alignment;
4441 continue 2;
4444 if ( isset( $wgDjvuRenderer ) && $wgDjvuRenderer
4445 && ! is_null( $match = $mwPage->matchVariableStartToEnd($val) ) ) {
4446 # Select a page in a multipage document
4447 $page = $match;
4448 } elseif ( $wgUseImageResize && !$width && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4449 wfDebug( "img_width match: $match\n" );
4450 # $match is the image width in pixels
4451 $m = array();
4452 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4453 $width = intval( $m[1] );
4454 $height = intval( $m[2] );
4455 } else {
4456 $width = intval($match);
4458 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4459 $framed=true;
4460 } else {
4461 $caption = $val;
4465 # Strip bad stuff out of the alt text
4466 $alt = $this->replaceLinkHoldersText( $caption );
4468 # make sure there are no placeholders in thumbnail attributes
4469 # that are later expanded to html- so expand them now and
4470 # remove the tags
4471 $alt = $this->mStripState->unstripBoth( $alt );
4472 $alt = Sanitizer::stripAllTags( $alt );
4474 # Linker does the rest
4475 $sk = $this->mOptions->getSkin();
4476 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb, $page, $valign );
4480 * Set a flag in the output object indicating that the content is dynamic and
4481 * shouldn't be cached.
4483 function disableCache() {
4484 wfDebug( "Parser output marked as uncacheable.\n" );
4485 $this->mOutput->mCacheTime = -1;
4488 /**#@+
4489 * Callback from the Sanitizer for expanding items found in HTML attribute
4490 * values, so they can be safely tested and escaped.
4491 * @param string $text
4492 * @param array $args
4493 * @return string
4494 * @private
4496 function attributeStripCallback( &$text, $args ) {
4497 $text = $this->replaceVariables( $text, $args );
4498 $text = $this->mStripState->unstripBoth( $text );
4499 return $text;
4502 /**#@-*/
4504 /**#@+
4505 * Accessor/mutator
4507 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4508 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4509 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4510 /**#@-*/
4512 /**#@+
4513 * Accessor
4515 function getTags() { return array_keys( $this->mTagHooks ); }
4516 /**#@-*/
4520 * Break wikitext input into sections, and either pull or replace
4521 * some particular section's text.
4523 * External callers should use the getSection and replaceSection methods.
4525 * @param $text Page wikitext
4526 * @param $section Numbered section. 0 pulls the text before the first
4527 * heading; other numbers will pull the given section
4528 * along with its lower-level subsections.
4529 * @param $mode One of "get" or "replace"
4530 * @param $newtext Replacement text for section data.
4531 * @return string for "get", the extracted section text.
4532 * for "replace", the whole page with the section replaced.
4534 private function extractSections( $text, $section, $mode, $newtext='' ) {
4535 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4536 # comments to be stripped as well)
4537 $stripState = new StripState;
4539 $oldOutputType = $this->mOutputType;
4540 $oldOptions = $this->mOptions;
4541 $this->mOptions = new ParserOptions();
4542 $this->setOutputType( OT_WIKI );
4544 $striptext = $this->strip( $text, $stripState, true );
4546 $this->setOutputType( $oldOutputType );
4547 $this->mOptions = $oldOptions;
4549 # now that we can be sure that no pseudo-sections are in the source,
4550 # split it up by section
4551 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4552 $comment = "(?:$uniq-!--.*?QINU)";
4553 $secs = preg_split(
4557 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4558 (=+) # Should this be limited to 6?
4559 .+? # Section title...
4560 \\2 # Ending = count must match start
4561 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4564 <h([1-6])\b.*?>
4566 <\/h\\3\s*>
4568 /mix",
4569 $striptext, -1,
4570 PREG_SPLIT_DELIM_CAPTURE);
4572 if( $mode == "get" ) {
4573 if( $section == 0 ) {
4574 // "Section 0" returns the content before any other section.
4575 $rv = $secs[0];
4576 } else {
4577 //track missing section, will replace if found.
4578 $rv = $newtext;
4580 } elseif( $mode == "replace" ) {
4581 if( $section == 0 ) {
4582 $rv = $newtext . "\n\n";
4583 $remainder = true;
4584 } else {
4585 $rv = $secs[0];
4586 $remainder = false;
4589 $count = 0;
4590 $sectionLevel = 0;
4591 for( $index = 1; $index < count( $secs ); ) {
4592 $headerLine = $secs[$index++];
4593 if( $secs[$index] ) {
4594 // A wiki header
4595 $headerLevel = strlen( $secs[$index++] );
4596 } else {
4597 // An HTML header
4598 $index++;
4599 $headerLevel = intval( $secs[$index++] );
4601 $content = $secs[$index++];
4603 $count++;
4604 if( $mode == "get" ) {
4605 if( $count == $section ) {
4606 $rv = $headerLine . $content;
4607 $sectionLevel = $headerLevel;
4608 } elseif( $count > $section ) {
4609 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4610 $rv .= $headerLine . $content;
4611 } else {
4612 // Broke out to a higher-level section
4613 break;
4616 } elseif( $mode == "replace" ) {
4617 if( $count < $section ) {
4618 $rv .= $headerLine . $content;
4619 } elseif( $count == $section ) {
4620 $rv .= $newtext . "\n\n";
4621 $sectionLevel = $headerLevel;
4622 } elseif( $count > $section ) {
4623 if( $headerLevel <= $sectionLevel ) {
4624 // Passed the section's sub-parts.
4625 $remainder = true;
4627 if( $remainder ) {
4628 $rv .= $headerLine . $content;
4633 if (is_string($rv))
4634 # reinsert stripped tags
4635 $rv = trim( $stripState->unstripBoth( $rv ) );
4637 return $rv;
4641 * This function returns the text of a section, specified by a number ($section).
4642 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4643 * the first section before any such heading (section 0).
4645 * If a section contains subsections, these are also returned.
4647 * @param $text String: text to look in
4648 * @param $section Integer: section number
4649 * @param $deftext: default to return if section is not found
4650 * @return string text of the requested section
4652 public function getSection( $text, $section, $deftext='' ) {
4653 return $this->extractSections( $text, $section, "get", $deftext );
4656 public function replaceSection( $oldtext, $section, $text ) {
4657 return $this->extractSections( $oldtext, $section, "replace", $text );
4661 * Get the timestamp associated with the current revision, adjusted for
4662 * the default server-local timestamp
4664 function getRevisionTimestamp() {
4665 if ( is_null( $this->mRevisionTimestamp ) ) {
4666 wfProfileIn( __METHOD__ );
4667 global $wgContLang;
4668 $dbr = wfGetDB( DB_SLAVE );
4669 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4670 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4672 // Normalize timestamp to internal MW format for timezone processing.
4673 // This has the added side-effect of replacing a null value with
4674 // the current time, which gives us more sensible behavior for
4675 // previews.
4676 $timestamp = wfTimestamp( TS_MW, $timestamp );
4678 // The cryptic '' timezone parameter tells to use the site-default
4679 // timezone offset instead of the user settings.
4681 // Since this value will be saved into the parser cache, served
4682 // to other users, and potentially even used inside links and such,
4683 // it needs to be consistent for all visitors.
4684 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4686 wfProfileOut( __METHOD__ );
4688 return $this->mRevisionTimestamp;
4692 * Mutator for $mDefaultSort
4694 * @param $sort New value
4696 public function setDefaultSort( $sort ) {
4697 $this->mDefaultSort = $sort;
4701 * Accessor for $mDefaultSort
4702 * Will use the title/prefixed title if none is set
4704 * @return string
4706 public function getDefaultSort() {
4707 if( $this->mDefaultSort !== false ) {
4708 return $this->mDefaultSort;
4709 } else {
4710 return $this->mTitle->getNamespace() == NS_CATEGORY
4711 ? $this->mTitle->getText()
4712 : $this->mTitle->getPrefixedText();
4718 class OnlyIncludeReplacer {
4719 var $output = '';
4721 function replace( $matches ) {
4722 if ( substr( $matches[1], -1 ) == "\n" ) {
4723 $this->output .= substr( $matches[1], 0, -1 );
4724 } else {
4725 $this->output .= $matches[1];
4730 class StripState {
4731 var $general, $nowiki;
4733 function __construct() {
4734 $this->general = new ReplacementArray;
4735 $this->nowiki = new ReplacementArray;
4738 function unstripGeneral( $text ) {
4739 wfProfileIn( __METHOD__ );
4740 $text = $this->general->replace( $text );
4741 wfProfileOut( __METHOD__ );
4742 return $text;
4745 function unstripNoWiki( $text ) {
4746 wfProfileIn( __METHOD__ );
4747 $text = $this->nowiki->replace( $text );
4748 wfProfileOut( __METHOD__ );
4749 return $text;
4752 function unstripBoth( $text ) {
4753 wfProfileIn( __METHOD__ );
4754 $text = $this->general->replace( $text );
4755 $text = $this->nowiki->replace( $text );
4756 wfProfileOut( __METHOD__ );
4757 return $text;