Revert r39414. Breaks processing links like [[:wikipedia:nl:User:Siebrand|Dutch langu...
[lhc/web/wiklou.git] / includes / parser / Parser.php
1 <?php
2 /**
3 * @defgroup Parser Parser
4 *
5 * @file
6 * @ingroup Parser
7 * File for Parser and related classes
8 */
9
10
11 /**
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
16 *
17 * <pre>
18 * There are five main entry points into the Parser class:
19 * parse()
20 * produces HTML output
21 * preSaveTransform().
22 * produces altered wiki markup.
23 * preprocess()
24 * removes HTML comments and expands templates
25 * cleanSig()
26 * Cleans a signature before saving it to preferences
27 * extractSections()
28 * Extracts sections from an article for section editing
29 *
30 * Globals used:
31 * objects: $wgLang, $wgContLang
32 *
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
34 *
35 * settings:
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
39 * $wgMaxArticleSize*
40 *
41 * * only within ParserOptions
42 * </pre>
43 *
44 * @ingroup Parser
45 */
46 class Parser
47 {
48 /**
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
52 */
53 const VERSION = '1.6.4';
54
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH = 1;
58 const SFH_OBJECT_ARGS = 2;
59
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
65
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT = 0;
68 const COLON_STATE_TAG = 1;
69 const COLON_STATE_TAGSTART = 2;
70 const COLON_STATE_CLOSETAG = 3;
71 const COLON_STATE_TAGSLASH = 4;
72 const COLON_STATE_COMMENT = 5;
73 const COLON_STATE_COMMENTDASH = 6;
74 const COLON_STATE_COMMENTDASHDASH = 7;
75
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION = 1;
78
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
81 const OT_HTML = 1;
82 const OT_WIKI = 2;
83 const OT_PREPROCESS = 3;
84 const OT_MSG = 3;
85
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX = "-QINU\x7f";
88
89 /**#@+
90 * @private
91 */
92 # Persistent:
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mDefaultStripList, $mVarCache, $mConf;
96
97
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
106
107 # Temporary
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $ot, // Shortcut alias, see setOutputType()
113 $mRevisionId, // ID to display in {{REVISIONID}} tags
114 $mRevisionTimestamp, // The timestamp of the specified revision ID
115 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
116
117 /**#@-*/
118
119 /**
120 * Constructor
121 *
122 * @public
123 */
124 function __construct( $conf = array() ) {
125 $this->mConf = $conf;
126 $this->mTagHooks = array();
127 $this->mTransparentTagHooks = array();
128 $this->mFunctionHooks = array();
129 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
130 $this->mDefaultStripList = $this->mStripList = array( 'nowiki', 'gallery' );
131 $this->mExtLinkBracketedRegex = '/\[(\b(' . wfUrlProtocols() . ')'.
132 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
133 $this->mVarCache = array();
134 if ( isset( $conf['preprocessorClass'] ) ) {
135 $this->mPreprocessorClass = $conf['preprocessorClass'];
136 } elseif ( extension_loaded( 'dom' ) ) {
137 $this->mPreprocessorClass = 'Preprocessor_DOM';
138 } else {
139 $this->mPreprocessorClass = 'Preprocessor_Hash';
140 }
141 $this->mMarkerIndex = 0;
142 $this->mFirstCall = true;
143 }
144
145 /**
146 * Do various kinds of initialisation on the first call of the parser
147 */
148 function firstCallInit() {
149 if ( !$this->mFirstCall ) {
150 return;
151 }
152 $this->mFirstCall = false;
153
154 wfProfileIn( __METHOD__ );
155
156 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
157 CoreParserFunctions::register( $this );
158 $this->initialiseVariables();
159
160 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
161 wfProfileOut( __METHOD__ );
162 }
163
164 /**
165 * Clear Parser state
166 *
167 * @private
168 */
169 function clearState() {
170 wfProfileIn( __METHOD__ );
171 if ( $this->mFirstCall ) {
172 $this->firstCallInit();
173 }
174 $this->mOutput = new ParserOutput;
175 $this->mAutonumber = 0;
176 $this->mLastSection = '';
177 $this->mDTopen = false;
178 $this->mIncludeCount = array();
179 $this->mStripState = new StripState;
180 $this->mArgStack = false;
181 $this->mInPre = false;
182 $this->mInterwikiLinkHolders = array(
183 'texts' => array(),
184 'titles' => array()
185 );
186 $this->mLinkHolders = array(
187 'namespaces' => array(),
188 'dbkeys' => array(),
189 'queries' => array(),
190 'texts' => array(),
191 'titles' => array()
192 );
193 $this->mRevisionTimestamp = $this->mRevisionId = null;
194
195 /**
196 * Prefix for temporary replacement strings for the multipass parser.
197 * \x07 should never appear in input as it's disallowed in XML.
198 * Using it at the front also gives us a little extra robustness
199 * since it shouldn't match when butted up against identifier-like
200 * string constructs.
201 *
202 * Must not consist of all title characters, or else it will change
203 * the behaviour of <nowiki> in a link.
204 */
205 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
206 # Changed to \x7f to allow XML double-parsing -- TS
207 $this->mUniqPrefix = "\x7fUNIQ" . Parser::getRandomString();
208
209
210 # Clear these on every parse, bug 4549
211 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
212
213 $this->mShowToc = true;
214 $this->mForceTocPosition = false;
215 $this->mIncludeSizes = array(
216 'post-expand' => 0,
217 'arg' => 0,
218 );
219 $this->mPPNodeCount = 0;
220 $this->mDefaultSort = false;
221 $this->mHeadings = array();
222 $this->mDoubleUnderscores = array();
223 $this->mExpensiveFunctionCount = 0;
224
225 # Fix cloning
226 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
227 $this->mPreprocessor = null;
228 }
229
230 wfRunHooks( 'ParserClearState', array( &$this ) );
231 wfProfileOut( __METHOD__ );
232 }
233
234 function setOutputType( $ot ) {
235 $this->mOutputType = $ot;
236 // Shortcut alias
237 $this->ot = array(
238 'html' => $ot == self::OT_HTML,
239 'wiki' => $ot == self::OT_WIKI,
240 'pre' => $ot == self::OT_PREPROCESS,
241 );
242 }
243
244 /**
245 * Set the context title
246 */
247 function setTitle( $t ) {
248 if ( !$t || $t instanceof FakeTitle ) {
249 $t = Title::newFromText( 'NO TITLE' );
250 }
251 if ( strval( $t->getFragment() ) !== '' ) {
252 # Strip the fragment to avoid various odd effects
253 $this->mTitle = clone $t;
254 $this->mTitle->setFragment( '' );
255 } else {
256 $this->mTitle = $t;
257 }
258 }
259
260 /**
261 * Accessor for mUniqPrefix.
262 *
263 * @public
264 */
265 function uniqPrefix() {
266 if( !isset( $this->mUniqPrefix ) ) {
267 // @fixme this is probably *horribly wrong*
268 // LanguageConverter seems to want $wgParser's uniqPrefix, however
269 // if this is called for a parser cache hit, the parser may not
270 // have ever been initialized in the first place.
271 // Not really sure what the heck is supposed to be going on here.
272 return '';
273 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
274 }
275 return $this->mUniqPrefix;
276 }
277
278 /**
279 * Convert wikitext to HTML
280 * Do not call this function recursively.
281 *
282 * @param $text String: text we want to parse
283 * @param $title A title object
284 * @param $options ParserOptions
285 * @param $linestart boolean
286 * @param $clearState boolean
287 * @param $revid Int: number to pass in {{REVISIONID}}
288 * @return ParserOutput a ParserOutput
289 */
290 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
291 /**
292 * First pass--just handle <nowiki> sections, pass the rest off
293 * to internalParse() which does all the real work.
294 */
295
296 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
297 $fname = 'Parser::parse-' . wfGetCaller();
298 wfProfileIn( __METHOD__ );
299 wfProfileIn( $fname );
300
301 if ( $clearState ) {
302 $this->clearState();
303 }
304
305 $this->mOptions = $options;
306 $this->setTitle( $title );
307 $oldRevisionId = $this->mRevisionId;
308 $oldRevisionTimestamp = $this->mRevisionTimestamp;
309 if( $revid !== null ) {
310 $this->mRevisionId = $revid;
311 $this->mRevisionTimestamp = null;
312 }
313 $this->setOutputType( self::OT_HTML );
314 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
315 # No more strip!
316 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
317 $text = $this->internalParse( $text );
318 $text = $this->mStripState->unstripGeneral( $text );
319
320 # Clean up special characters, only run once, next-to-last before doBlockLevels
321 $fixtags = array(
322 # french spaces, last one Guillemet-left
323 # only if there is something before the space
324 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&nbsp;\\2',
325 # french spaces, Guillemet-right
326 '/(\\302\\253) /' => '\\1&nbsp;',
327 '/&nbsp;(!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
328 );
329 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
330
331 # only once and last
332 $text = $this->doBlockLevels( $text, $linestart );
333
334 $this->replaceLinkHolders( $text );
335
336 # the position of the parserConvert() call should not be changed. it
337 # assumes that the links are all replaced and the only thing left
338 # is the <nowiki> mark.
339 # Side-effects: this calls $this->mOutput->setTitleText()
340 $text = $wgContLang->parserConvert( $text, $this );
341
342 $text = $this->mStripState->unstripNoWiki( $text );
343
344 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
345
346 //!JF Move to its own function
347
348 $uniq_prefix = $this->mUniqPrefix;
349 $matches = array();
350 $elements = array_keys( $this->mTransparentTagHooks );
351 $text = Parser::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
352
353 foreach( $matches as $marker => $data ) {
354 list( $element, $content, $params, $tag ) = $data;
355 $tagName = strtolower( $element );
356 if( isset( $this->mTransparentTagHooks[$tagName] ) ) {
357 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName],
358 array( $content, $params, $this ) );
359 } else {
360 $output = $tag;
361 }
362 $this->mStripState->general->setPair( $marker, $output );
363 }
364 $text = $this->mStripState->unstripGeneral( $text );
365
366 $text = Sanitizer::normalizeCharReferences( $text );
367
368 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
369 $text = Parser::tidy($text);
370 } else {
371 # attempt to sanitize at least some nesting problems
372 # (bug #2702 and quite a few others)
373 $tidyregs = array(
374 # ''Something [http://www.cool.com cool''] -->
375 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
376 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
377 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
378 # fix up an anchor inside another anchor, only
379 # at least for a single single nested link (bug 3695)
380 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
381 '\\1\\2</a>\\3</a>\\1\\4</a>',
382 # fix div inside inline elements- doBlockLevels won't wrap a line which
383 # contains a div, so fix it up here; replace
384 # div with escaped text
385 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
386 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
387 # remove empty italic or bold tag pairs, some
388 # introduced by rules above
389 '/<([bi])><\/\\1>/' => '',
390 );
391
392 $text = preg_replace(
393 array_keys( $tidyregs ),
394 array_values( $tidyregs ),
395 $text );
396 }
397 global $wgExpensiveParserFunctionLimit;
398 if ( $this->mExpensiveFunctionCount > $wgExpensiveParserFunctionLimit ) {
399 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount, $wgExpensiveParserFunctionLimit );
400 }
401
402 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
403
404 # Information on include size limits, for the benefit of users who try to skirt them
405 if ( $this->mOptions->getEnableLimitReport() ) {
406 global $wgExpensiveParserFunctionLimit;
407 $max = $this->mOptions->getMaxIncludeSize();
408 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
409 $limitReport =
410 "NewPP limit report\n" .
411 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
412 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
413 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
414 $PFreport;
415 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
416 $text .= "\n<!-- \n$limitReport-->\n";
417 }
418 $this->mOutput->setText( $text );
419 $this->mRevisionId = $oldRevisionId;
420 $this->mRevisionTimestamp = $oldRevisionTimestamp;
421 wfProfileOut( $fname );
422 wfProfileOut( __METHOD__ );
423
424 return $this->mOutput;
425 }
426
427 /**
428 * Recursive parser entry point that can be called from an extension tag
429 * hook.
430 */
431 function recursiveTagParse( $text ) {
432 wfProfileIn( __METHOD__ );
433 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
434 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
435 $text = $this->internalParse( $text );
436 wfProfileOut( __METHOD__ );
437 return $text;
438 }
439
440 /**
441 * Expand templates and variables in the text, producing valid, static wikitext.
442 * Also removes comments.
443 */
444 function preprocess( $text, $title, $options, $revid = null ) {
445 wfProfileIn( __METHOD__ );
446 $this->clearState();
447 $this->setOutputType( self::OT_PREPROCESS );
448 $this->mOptions = $options;
449 $this->setTitle( $title );
450 if( $revid !== null ) {
451 $this->mRevisionId = $revid;
452 }
453 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
454 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
455 $text = $this->replaceVariables( $text );
456 $text = $this->mStripState->unstripBoth( $text );
457 wfProfileOut( __METHOD__ );
458 return $text;
459 }
460
461 /**
462 * Get a random string
463 *
464 * @private
465 * @static
466 */
467 function getRandomString() {
468 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
469 }
470
471 function &getTitle() { return $this->mTitle; }
472 function getOptions() { return $this->mOptions; }
473 function getRevisionId() { return $this->mRevisionId; }
474
475 function getFunctionLang() {
476 global $wgLang, $wgContLang;
477
478 $target = $this->mOptions->getTargetLanguage();
479 if ( $target !== null ) {
480 return $target;
481 } else {
482 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
483 }
484 }
485
486 /**
487 * Get a preprocessor object
488 */
489 function getPreprocessor() {
490 if ( !isset( $this->mPreprocessor ) ) {
491 $class = $this->mPreprocessorClass;
492 $this->mPreprocessor = new $class( $this );
493 }
494 return $this->mPreprocessor;
495 }
496
497 /**
498 * Replaces all occurrences of HTML-style comments and the given tags
499 * in the text with a random marker and returns the next text. The output
500 * parameter $matches will be an associative array filled with data in
501 * the form:
502 * 'UNIQ-xxxxx' => array(
503 * 'element',
504 * 'tag content',
505 * array( 'param' => 'x' ),
506 * '<element param="x">tag content</element>' ) )
507 *
508 * @param $elements list of element names. Comments are always extracted.
509 * @param $text Source text string.
510 * @param $uniq_prefix
511 *
512 * @public
513 * @static
514 */
515 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
516 static $n = 1;
517 $stripped = '';
518 $matches = array();
519
520 $taglist = implode( '|', $elements );
521 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
522
523 while ( '' != $text ) {
524 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
525 $stripped .= $p[0];
526 if( count( $p ) < 5 ) {
527 break;
528 }
529 if( count( $p ) > 5 ) {
530 // comment
531 $element = $p[4];
532 $attributes = '';
533 $close = '';
534 $inside = $p[5];
535 } else {
536 // tag
537 $element = $p[1];
538 $attributes = $p[2];
539 $close = $p[3];
540 $inside = $p[4];
541 }
542
543 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++) . self::MARKER_SUFFIX;
544 $stripped .= $marker;
545
546 if ( $close === '/>' ) {
547 // Empty element tag, <tag />
548 $content = null;
549 $text = $inside;
550 $tail = null;
551 } else {
552 if( $element == '!--' ) {
553 $end = '/(-->)/';
554 } else {
555 $end = "/(<\\/$element\\s*>)/i";
556 }
557 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
558 $content = $q[0];
559 if( count( $q ) < 3 ) {
560 # No end tag -- let it run out to the end of the text.
561 $tail = '';
562 $text = '';
563 } else {
564 $tail = $q[1];
565 $text = $q[2];
566 }
567 }
568
569 $matches[$marker] = array( $element,
570 $content,
571 Sanitizer::decodeTagAttributes( $attributes ),
572 "<$element$attributes$close$content$tail" );
573 }
574 return $stripped;
575 }
576
577 /**
578 * Get a list of strippable XML-like elements
579 */
580 function getStripList() {
581 global $wgRawHtml;
582 $elements = $this->mStripList;
583 if( $wgRawHtml ) {
584 $elements[] = 'html';
585 }
586 if( $this->mOptions->getUseTeX() ) {
587 $elements[] = 'math';
588 }
589 return $elements;
590 }
591
592 /**
593 * @deprecated use replaceVariables
594 */
595 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
596 return $text;
597 }
598
599 /**
600 * Restores pre, math, and other extensions removed by strip()
601 *
602 * always call unstripNoWiki() after this one
603 * @private
604 * @deprecated use $this->mStripState->unstrip()
605 */
606 function unstrip( $text, $state ) {
607 return $state->unstripGeneral( $text );
608 }
609
610 /**
611 * Always call this after unstrip() to preserve the order
612 *
613 * @private
614 * @deprecated use $this->mStripState->unstrip()
615 */
616 function unstripNoWiki( $text, $state ) {
617 return $state->unstripNoWiki( $text );
618 }
619
620 /**
621 * @deprecated use $this->mStripState->unstripBoth()
622 */
623 function unstripForHTML( $text ) {
624 return $this->mStripState->unstripBoth( $text );
625 }
626
627 /**
628 * Add an item to the strip state
629 * Returns the unique tag which must be inserted into the stripped text
630 * The tag will be replaced with the original text in unstrip()
631 *
632 * @private
633 */
634 function insertStripItem( $text ) {
635 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
636 $this->mMarkerIndex++;
637 $this->mStripState->general->setPair( $rnd, $text );
638 return $rnd;
639 }
640
641 /**
642 * Interface with html tidy, used if $wgUseTidy = true.
643 * If tidy isn't able to correct the markup, the original will be
644 * returned in all its glory with a warning comment appended.
645 *
646 * Either the external tidy program or the in-process tidy extension
647 * will be used depending on availability. Override the default
648 * $wgTidyInternal setting to disable the internal if it's not working.
649 *
650 * @param string $text Hideous HTML input
651 * @return string Corrected HTML output
652 * @public
653 * @static
654 */
655 function tidy( $text ) {
656 global $wgTidyInternal;
657 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
658 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
659 '<head><title>test</title></head><body>'.$text.'</body></html>';
660 if( $wgTidyInternal ) {
661 $correctedtext = Parser::internalTidy( $wrappedtext );
662 } else {
663 $correctedtext = Parser::externalTidy( $wrappedtext );
664 }
665 if( is_null( $correctedtext ) ) {
666 wfDebug( "Tidy error detected!\n" );
667 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
668 }
669 return $correctedtext;
670 }
671
672 /**
673 * Spawn an external HTML tidy process and get corrected markup back from it.
674 *
675 * @private
676 * @static
677 */
678 function externalTidy( $text ) {
679 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
680 $fname = 'Parser::externalTidy';
681 wfProfileIn( $fname );
682
683 $cleansource = '';
684 $opts = ' -utf8';
685
686 $descriptorspec = array(
687 0 => array('pipe', 'r'),
688 1 => array('pipe', 'w'),
689 2 => array('file', wfGetNull(), 'a')
690 );
691 $pipes = array();
692 if( function_exists('proc_open') ) {
693 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
694 if (is_resource($process)) {
695 // Theoretically, this style of communication could cause a deadlock
696 // here. If the stdout buffer fills up, then writes to stdin could
697 // block. This doesn't appear to happen with tidy, because tidy only
698 // writes to stdout after it's finished reading from stdin. Search
699 // for tidyParseStdin and tidySaveStdout in console/tidy.c
700 fwrite($pipes[0], $text);
701 fclose($pipes[0]);
702 while (!feof($pipes[1])) {
703 $cleansource .= fgets($pipes[1], 1024);
704 }
705 fclose($pipes[1]);
706 proc_close($process);
707 }
708 }
709
710 wfProfileOut( $fname );
711
712 if( $cleansource == '' && $text != '') {
713 // Some kind of error happened, so we couldn't get the corrected text.
714 // Just give up; we'll use the source text and append a warning.
715 return null;
716 } else {
717 return $cleansource;
718 }
719 }
720
721 /**
722 * Use the HTML tidy PECL extension to use the tidy library in-process,
723 * saving the overhead of spawning a new process.
724 *
725 * 'pear install tidy' should be able to compile the extension module.
726 *
727 * @private
728 * @static
729 */
730 function internalTidy( $text ) {
731 global $wgTidyConf, $IP, $wgDebugTidy;
732 $fname = 'Parser::internalTidy';
733 wfProfileIn( $fname );
734
735 $tidy = new tidy;
736 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
737 $tidy->cleanRepair();
738 if( $tidy->getStatus() == 2 ) {
739 // 2 is magic number for fatal error
740 // http://www.php.net/manual/en/function.tidy-get-status.php
741 $cleansource = null;
742 } else {
743 $cleansource = tidy_get_output( $tidy );
744 }
745 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
746 $cleansource .= "<!--\nTidy reports:\n" .
747 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
748 "\n-->";
749 }
750
751 wfProfileOut( $fname );
752 return $cleansource;
753 }
754
755 /**
756 * parse the wiki syntax used to render tables
757 *
758 * @private
759 */
760 function doTableStuff ( $text ) {
761 $fname = 'Parser::doTableStuff';
762 wfProfileIn( $fname );
763
764 $lines = explode ( "\n" , $text );
765 $td_history = array (); // Is currently a td tag open?
766 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
767 $tr_history = array (); // Is currently a tr tag open?
768 $tr_attributes = array (); // history of tr attributes
769 $has_opened_tr = array(); // Did this table open a <tr> element?
770 $indent_level = 0; // indent level of the table
771 foreach ( $lines as $key => $line )
772 {
773 $line = trim ( $line );
774
775 if( $line == '' ) { // empty line, go to next line
776 continue;
777 }
778 $first_character = $line{0};
779 $matches = array();
780
781 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
782 // First check if we are starting a new table
783 $indent_level = strlen( $matches[1] );
784
785 $attributes = $this->mStripState->unstripBoth( $matches[2] );
786 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'table' );
787
788 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
789 array_push ( $td_history , false );
790 array_push ( $last_tag_history , '' );
791 array_push ( $tr_history , false );
792 array_push ( $tr_attributes , '' );
793 array_push ( $has_opened_tr , false );
794 } else if ( count ( $td_history ) == 0 ) {
795 // Don't do any of the following
796 continue;
797 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
798 // We are ending a table
799 $line = '</table>' . substr ( $line , 2 );
800 $last_tag = array_pop ( $last_tag_history );
801
802 if ( !array_pop ( $has_opened_tr ) ) {
803 $line = "<tr><td></td></tr>{$line}";
804 }
805
806 if ( array_pop ( $tr_history ) ) {
807 $line = "</tr>{$line}";
808 }
809
810 if ( array_pop ( $td_history ) ) {
811 $line = "</{$last_tag}>{$line}";
812 }
813 array_pop ( $tr_attributes );
814 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
815 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
816 // Now we have a table row
817 $line = preg_replace( '#^\|-+#', '', $line );
818
819 // Whats after the tag is now only attributes
820 $attributes = $this->mStripState->unstripBoth( $line );
821 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'tr' );
822 array_pop ( $tr_attributes );
823 array_push ( $tr_attributes , $attributes );
824
825 $line = '';
826 $last_tag = array_pop ( $last_tag_history );
827 array_pop ( $has_opened_tr );
828 array_push ( $has_opened_tr , true );
829
830 if ( array_pop ( $tr_history ) ) {
831 $line = '</tr>';
832 }
833
834 if ( array_pop ( $td_history ) ) {
835 $line = "</{$last_tag}>{$line}";
836 }
837
838 $lines[$key] = $line;
839 array_push ( $tr_history , false );
840 array_push ( $td_history , false );
841 array_push ( $last_tag_history , '' );
842 }
843 else if ( $first_character == '|' || $first_character == '!' || substr ( $line , 0 , 2 ) == '|+' ) {
844 // This might be cell elements, td, th or captions
845 if ( substr ( $line , 0 , 2 ) == '|+' ) {
846 $first_character = '+';
847 $line = substr ( $line , 1 );
848 }
849
850 $line = substr ( $line , 1 );
851
852 if ( $first_character == '!' ) {
853 $line = str_replace ( '!!' , '||' , $line );
854 }
855
856 // Split up multiple cells on the same line.
857 // FIXME : This can result in improper nesting of tags processed
858 // by earlier parser steps, but should avoid splitting up eg
859 // attribute values containing literal "||".
860 $cells = StringUtils::explodeMarkup( '||' , $line );
861
862 $lines[$key] = '';
863
864 // Loop through each table cell
865 foreach ( $cells as $cell )
866 {
867 $previous = '';
868 if ( $first_character != '+' )
869 {
870 $tr_after = array_pop ( $tr_attributes );
871 if ( !array_pop ( $tr_history ) ) {
872 $previous = "<tr{$tr_after}>\n";
873 }
874 array_push ( $tr_history , true );
875 array_push ( $tr_attributes , '' );
876 array_pop ( $has_opened_tr );
877 array_push ( $has_opened_tr , true );
878 }
879
880 $last_tag = array_pop ( $last_tag_history );
881
882 if ( array_pop ( $td_history ) ) {
883 $previous = "</{$last_tag}>{$previous}";
884 }
885
886 if ( $first_character == '|' ) {
887 $last_tag = 'td';
888 } else if ( $first_character == '!' ) {
889 $last_tag = 'th';
890 } else if ( $first_character == '+' ) {
891 $last_tag = 'caption';
892 } else {
893 $last_tag = '';
894 }
895
896 array_push ( $last_tag_history , $last_tag );
897
898 // A cell could contain both parameters and data
899 $cell_data = explode ( '|' , $cell , 2 );
900
901 // Bug 553: Note that a '|' inside an invalid link should not
902 // be mistaken as delimiting cell parameters
903 if ( strpos( $cell_data[0], '[[' ) !== false ) {
904 $cell = "{$previous}<{$last_tag}>{$cell}";
905 } else if ( count ( $cell_data ) == 1 )
906 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
907 else {
908 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
909 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
910 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
911 }
912
913 $lines[$key] .= $cell;
914 array_push ( $td_history , true );
915 }
916 }
917 }
918
919 // Closing open td, tr && table
920 while ( count ( $td_history ) > 0 )
921 {
922 if ( array_pop ( $td_history ) ) {
923 $lines[] = '</td>' ;
924 }
925 if ( array_pop ( $tr_history ) ) {
926 $lines[] = '</tr>' ;
927 }
928 if ( !array_pop ( $has_opened_tr ) ) {
929 $lines[] = "<tr><td></td></tr>" ;
930 }
931
932 $lines[] = '</table>' ;
933 }
934
935 $output = implode ( "\n" , $lines ) ;
936
937 // special case: don't return empty table
938 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
939 $output = '';
940 }
941
942 wfProfileOut( $fname );
943
944 return $output;
945 }
946
947 /**
948 * Helper function for parse() that transforms wiki markup into
949 * HTML. Only called for $mOutputType == self::OT_HTML.
950 *
951 * @private
952 */
953 function internalParse( $text ) {
954 $isMain = true;
955 $fname = 'Parser::internalParse';
956 wfProfileIn( $fname );
957
958 # Hook to suspend the parser in this state
959 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
960 wfProfileOut( $fname );
961 return $text ;
962 }
963
964 $text = $this->replaceVariables( $text );
965 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
966 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
967
968 // Tables need to come after variable replacement for things to work
969 // properly; putting them before other transformations should keep
970 // exciting things like link expansions from showing up in surprising
971 // places.
972 $text = $this->doTableStuff( $text );
973
974 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
975
976 $text = $this->doDoubleUnderscore( $text );
977 $text = $this->doHeadings( $text );
978 if($this->mOptions->getUseDynamicDates()) {
979 $df = DateFormatter::getInstance();
980 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
981 }
982 $text = $this->doAllQuotes( $text );
983 $text = $this->replaceInternalLinks( $text );
984 $text = $this->replaceExternalLinks( $text );
985
986 # replaceInternalLinks may sometimes leave behind
987 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
988 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
989
990 $text = $this->doMagicLinks( $text );
991 $text = $this->formatHeadings( $text, $isMain );
992
993 wfProfileOut( $fname );
994 return $text;
995 }
996
997 /**
998 * Replace special strings like "ISBN xxx" and "RFC xxx" with
999 * magic external links.
1000 *
1001 * @private
1002 */
1003 function doMagicLinks( $text ) {
1004 wfProfileIn( __METHOD__ );
1005 $text = preg_replace_callback(
1006 '!(?: # Start cases
1007 <a.*?</a> | # Skip link text
1008 <.*?> | # Skip stuff inside HTML elements
1009 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
1010 ISBN\s+(\b # ISBN, capture number as m[2]
1011 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1012 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1013 [0-9Xx] # check digit
1014 \b)
1015 )!x', array( &$this, 'magicLinkCallback' ), $text );
1016 wfProfileOut( __METHOD__ );
1017 return $text;
1018 }
1019
1020 function magicLinkCallback( $m ) {
1021 if ( substr( $m[0], 0, 1 ) == '<' ) {
1022 # Skip HTML element
1023 return $m[0];
1024 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
1025 $isbn = $m[2];
1026 $num = strtr( $isbn, array(
1027 '-' => '',
1028 ' ' => '',
1029 'x' => 'X',
1030 ));
1031 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1032 $text = '<a href="' .
1033 $titleObj->escapeLocalUrl() .
1034 "\" class=\"internal\">ISBN $isbn</a>";
1035 } else {
1036 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1037 $keyword = 'RFC';
1038 $urlmsg = 'rfcurl';
1039 $id = $m[1];
1040 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1041 $keyword = 'PMID';
1042 $urlmsg = 'pubmedurl';
1043 $id = $m[1];
1044 } else {
1045 throw new MWException( __METHOD__.': unrecognised match type "' .
1046 substr($m[0], 0, 20 ) . '"' );
1047 }
1048
1049 $url = wfMsg( $urlmsg, $id);
1050 $sk = $this->mOptions->getSkin();
1051 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1052 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1053 }
1054 return $text;
1055 }
1056
1057 /**
1058 * Parse headers and return html
1059 *
1060 * @private
1061 */
1062 function doHeadings( $text ) {
1063 $fname = 'Parser::doHeadings';
1064 wfProfileIn( $fname );
1065 for ( $i = 6; $i >= 1; --$i ) {
1066 $h = str_repeat( '=', $i );
1067 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1068 "<h$i>\\1</h$i>", $text );
1069 }
1070 wfProfileOut( $fname );
1071 return $text;
1072 }
1073
1074 /**
1075 * Replace single quotes with HTML markup
1076 * @private
1077 * @return string the altered text
1078 */
1079 function doAllQuotes( $text ) {
1080 $fname = 'Parser::doAllQuotes';
1081 wfProfileIn( $fname );
1082 $outtext = '';
1083 $lines = explode( "\n", $text );
1084 foreach ( $lines as $line ) {
1085 $outtext .= $this->doQuotes ( $line ) . "\n";
1086 }
1087 $outtext = substr($outtext, 0,-1);
1088 wfProfileOut( $fname );
1089 return $outtext;
1090 }
1091
1092 /**
1093 * Helper function for doAllQuotes()
1094 */
1095 public function doQuotes( $text ) {
1096 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1097 if ( count( $arr ) == 1 )
1098 return $text;
1099 else
1100 {
1101 # First, do some preliminary work. This may shift some apostrophes from
1102 # being mark-up to being text. It also counts the number of occurrences
1103 # of bold and italics mark-ups.
1104 $i = 0;
1105 $numbold = 0;
1106 $numitalics = 0;
1107 foreach ( $arr as $r )
1108 {
1109 if ( ( $i % 2 ) == 1 )
1110 {
1111 # If there are ever four apostrophes, assume the first is supposed to
1112 # be text, and the remaining three constitute mark-up for bold text.
1113 if ( strlen( $arr[$i] ) == 4 )
1114 {
1115 $arr[$i-1] .= "'";
1116 $arr[$i] = "'''";
1117 }
1118 # If there are more than 5 apostrophes in a row, assume they're all
1119 # text except for the last 5.
1120 else if ( strlen( $arr[$i] ) > 5 )
1121 {
1122 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1123 $arr[$i] = "'''''";
1124 }
1125 # Count the number of occurrences of bold and italics mark-ups.
1126 # We are not counting sequences of five apostrophes.
1127 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++; }
1128 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++; }
1129 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
1130 }
1131 $i++;
1132 }
1133
1134 # If there is an odd number of both bold and italics, it is likely
1135 # that one of the bold ones was meant to be an apostrophe followed
1136 # by italics. Which one we cannot know for certain, but it is more
1137 # likely to be one that has a single-letter word before it.
1138 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
1139 {
1140 $i = 0;
1141 $firstsingleletterword = -1;
1142 $firstmultiletterword = -1;
1143 $firstspace = -1;
1144 foreach ( $arr as $r )
1145 {
1146 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
1147 {
1148 $x1 = substr ($arr[$i-1], -1);
1149 $x2 = substr ($arr[$i-1], -2, 1);
1150 if ($x1 == ' ') {
1151 if ($firstspace == -1) $firstspace = $i;
1152 } else if ($x2 == ' ') {
1153 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1154 } else {
1155 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1156 }
1157 }
1158 $i++;
1159 }
1160
1161 # If there is a single-letter word, use it!
1162 if ($firstsingleletterword > -1)
1163 {
1164 $arr [ $firstsingleletterword ] = "''";
1165 $arr [ $firstsingleletterword-1 ] .= "'";
1166 }
1167 # If not, but there's a multi-letter word, use that one.
1168 else if ($firstmultiletterword > -1)
1169 {
1170 $arr [ $firstmultiletterword ] = "''";
1171 $arr [ $firstmultiletterword-1 ] .= "'";
1172 }
1173 # ... otherwise use the first one that has neither.
1174 # (notice that it is possible for all three to be -1 if, for example,
1175 # there is only one pentuple-apostrophe in the line)
1176 else if ($firstspace > -1)
1177 {
1178 $arr [ $firstspace ] = "''";
1179 $arr [ $firstspace-1 ] .= "'";
1180 }
1181 }
1182
1183 # Now let's actually convert our apostrophic mush to HTML!
1184 $output = '';
1185 $buffer = '';
1186 $state = '';
1187 $i = 0;
1188 foreach ($arr as $r)
1189 {
1190 if (($i % 2) == 0)
1191 {
1192 if ($state == 'both')
1193 $buffer .= $r;
1194 else
1195 $output .= $r;
1196 }
1197 else
1198 {
1199 if (strlen ($r) == 2)
1200 {
1201 if ($state == 'i')
1202 { $output .= '</i>'; $state = ''; }
1203 else if ($state == 'bi')
1204 { $output .= '</i>'; $state = 'b'; }
1205 else if ($state == 'ib')
1206 { $output .= '</b></i><b>'; $state = 'b'; }
1207 else if ($state == 'both')
1208 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1209 else # $state can be 'b' or ''
1210 { $output .= '<i>'; $state .= 'i'; }
1211 }
1212 else if (strlen ($r) == 3)
1213 {
1214 if ($state == 'b')
1215 { $output .= '</b>'; $state = ''; }
1216 else if ($state == 'bi')
1217 { $output .= '</i></b><i>'; $state = 'i'; }
1218 else if ($state == 'ib')
1219 { $output .= '</b>'; $state = 'i'; }
1220 else if ($state == 'both')
1221 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1222 else # $state can be 'i' or ''
1223 { $output .= '<b>'; $state .= 'b'; }
1224 }
1225 else if (strlen ($r) == 5)
1226 {
1227 if ($state == 'b')
1228 { $output .= '</b><i>'; $state = 'i'; }
1229 else if ($state == 'i')
1230 { $output .= '</i><b>'; $state = 'b'; }
1231 else if ($state == 'bi')
1232 { $output .= '</i></b>'; $state = ''; }
1233 else if ($state == 'ib')
1234 { $output .= '</b></i>'; $state = ''; }
1235 else if ($state == 'both')
1236 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1237 else # ($state == '')
1238 { $buffer = ''; $state = 'both'; }
1239 }
1240 }
1241 $i++;
1242 }
1243 # Now close all remaining tags. Notice that the order is important.
1244 if ($state == 'b' || $state == 'ib')
1245 $output .= '</b>';
1246 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1247 $output .= '</i>';
1248 if ($state == 'bi')
1249 $output .= '</b>';
1250 # There might be lonely ''''', so make sure we have a buffer
1251 if ($state == 'both' && $buffer)
1252 $output .= '<b><i>'.$buffer.'</i></b>';
1253 return $output;
1254 }
1255 }
1256
1257 /**
1258 * Replace external links
1259 *
1260 * Note: this is all very hackish and the order of execution matters a lot.
1261 * Make sure to run maintenance/parserTests.php if you change this code.
1262 *
1263 * @private
1264 */
1265 function replaceExternalLinks( $text ) {
1266 global $wgContLang;
1267 $fname = 'Parser::replaceExternalLinks';
1268 wfProfileIn( $fname );
1269
1270 $sk = $this->mOptions->getSkin();
1271
1272 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1273
1274 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1275
1276 $i = 0;
1277 while ( $i<count( $bits ) ) {
1278 $url = $bits[$i++];
1279 $protocol = $bits[$i++];
1280 $text = $bits[$i++];
1281 $trail = $bits[$i++];
1282
1283 # The characters '<' and '>' (which were escaped by
1284 # removeHTMLtags()) should not be included in
1285 # URLs, per RFC 2396.
1286 $m2 = array();
1287 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1288 $text = substr($url, $m2[0][1]) . ' ' . $text;
1289 $url = substr($url, 0, $m2[0][1]);
1290 }
1291
1292 # If the link text is an image URL, replace it with an <img> tag
1293 # This happened by accident in the original parser, but some people used it extensively
1294 $img = $this->maybeMakeExternalImage( $text );
1295 if ( $img !== false ) {
1296 $text = $img;
1297 }
1298
1299 $dtrail = '';
1300
1301 # Set linktype for CSS - if URL==text, link is essentially free
1302 $linktype = ($text == $url) ? 'free' : 'text';
1303
1304 # No link text, e.g. [http://domain.tld/some.link]
1305 if ( $text == '' ) {
1306 # Autonumber if allowed. See bug #5918
1307 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1308 $text = '[' . ++$this->mAutonumber . ']';
1309 $linktype = 'autonumber';
1310 } else {
1311 # Otherwise just use the URL
1312 $text = htmlspecialchars( $url );
1313 $linktype = 'free';
1314 }
1315 } else {
1316 # Have link text, e.g. [http://domain.tld/some.link text]s
1317 # Check for trail
1318 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1319 }
1320
1321 $text = $wgContLang->markNoConversion($text);
1322
1323 $url = Sanitizer::cleanUrl( $url );
1324
1325 # Process the trail (i.e. everything after this link up until start of the next link),
1326 # replacing any non-bracketed links
1327 $trail = $this->replaceFreeExternalLinks( $trail );
1328
1329 # Use the encoded URL
1330 # This means that users can paste URLs directly into the text
1331 # Funny characters like &ouml; aren't valid in URLs anyway
1332 # This was changed in August 2004
1333 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle->getNamespace() ) . $dtrail . $trail;
1334
1335 # Register link in the output object.
1336 # Replace unnecessary URL escape codes with the referenced character
1337 # This prevents spammers from hiding links from the filters
1338 $pasteurized = Parser::replaceUnusualEscapes( $url );
1339 $this->mOutput->addExternalLink( $pasteurized );
1340 }
1341
1342 wfProfileOut( $fname );
1343 return $s;
1344 }
1345
1346 /**
1347 * Replace anything that looks like a URL with a link
1348 * @private
1349 */
1350 function replaceFreeExternalLinks( $text ) {
1351 global $wgContLang;
1352 $fname = 'Parser::replaceFreeExternalLinks';
1353 wfProfileIn( $fname );
1354
1355 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1356 $s = array_shift( $bits );
1357 $i = 0;
1358
1359 $sk = $this->mOptions->getSkin();
1360
1361 while ( $i < count( $bits ) ){
1362 $protocol = $bits[$i++];
1363 $remainder = $bits[$i++];
1364
1365 $m = array();
1366 if ( preg_match( '/^('.self::EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1367 # Found some characters after the protocol that look promising
1368 $url = $protocol . $m[1];
1369 $trail = $m[2];
1370
1371 # special case: handle urls as url args:
1372 # http://www.example.com/foo?=http://www.example.com/bar
1373 if(strlen($trail) == 0 &&
1374 isset($bits[$i]) &&
1375 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1376 preg_match( '/^('.self::EXT_LINK_URL_CLASS.'+)(.*)$/s', $bits[$i + 1], $m ))
1377 {
1378 # add protocol, arg
1379 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1380 $i += 2;
1381 $trail = $m[2];
1382 }
1383
1384 # The characters '<' and '>' (which were escaped by
1385 # removeHTMLtags()) should not be included in
1386 # URLs, per RFC 2396.
1387 $m2 = array();
1388 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1389 $trail = substr($url, $m2[0][1]) . $trail;
1390 $url = substr($url, 0, $m2[0][1]);
1391 }
1392
1393 # Move trailing punctuation to $trail
1394 $sep = ',;\.:!?';
1395 # If there is no left bracket, then consider right brackets fair game too
1396 if ( strpos( $url, '(' ) === false ) {
1397 $sep .= ')';
1398 }
1399
1400 $numSepChars = strspn( strrev( $url ), $sep );
1401 if ( $numSepChars ) {
1402 $trail = substr( $url, -$numSepChars ) . $trail;
1403 $url = substr( $url, 0, -$numSepChars );
1404 }
1405
1406 $url = Sanitizer::cleanUrl( $url );
1407
1408 # Is this an external image?
1409 $text = $this->maybeMakeExternalImage( $url );
1410 if ( $text === false ) {
1411 # Not an image, make a link
1412 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle->getNamespace() );
1413 # Register it in the output object...
1414 # Replace unnecessary URL escape codes with their equivalent characters
1415 $pasteurized = Parser::replaceUnusualEscapes( $url );
1416 $this->mOutput->addExternalLink( $pasteurized );
1417 }
1418 $s .= $text . $trail;
1419 } else {
1420 $s .= $protocol . $remainder;
1421 }
1422 }
1423 wfProfileOut( $fname );
1424 return $s;
1425 }
1426
1427 /**
1428 * Replace unusual URL escape codes with their equivalent characters
1429 * @param string
1430 * @return string
1431 * @static
1432 * @todo This can merge genuinely required bits in the path or query string,
1433 * breaking legit URLs. A proper fix would treat the various parts of
1434 * the URL differently; as a workaround, just use the output for
1435 * statistical records, not for actual linking/output.
1436 */
1437 static function replaceUnusualEscapes( $url ) {
1438 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1439 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1440 }
1441
1442 /**
1443 * Callback function used in replaceUnusualEscapes().
1444 * Replaces unusual URL escape codes with their equivalent character
1445 * @static
1446 * @private
1447 */
1448 private static function replaceUnusualEscapesCallback( $matches ) {
1449 $char = urldecode( $matches[0] );
1450 $ord = ord( $char );
1451 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1452 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1453 // No, shouldn't be escaped
1454 return $char;
1455 } else {
1456 // Yes, leave it escaped
1457 return $matches[0];
1458 }
1459 }
1460
1461 /**
1462 * make an image if it's allowed, either through the global
1463 * option or through the exception
1464 * @private
1465 */
1466 function maybeMakeExternalImage( $url ) {
1467 $sk = $this->mOptions->getSkin();
1468 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1469 $imagesexception = !empty($imagesfrom);
1470 $text = false;
1471 if ( $this->mOptions->getAllowExternalImages()
1472 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1473 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1474 # Image found
1475 $text = $sk->makeExternalImage( $url );
1476 }
1477 }
1478 return $text;
1479 }
1480
1481 /**
1482 * Process [[ ]] wikilinks
1483 *
1484 * @private
1485 */
1486 function replaceInternalLinks( $s ) {
1487 global $wgContLang;
1488 static $fname = 'Parser::replaceInternalLinks' ;
1489
1490 wfProfileIn( $fname );
1491
1492 wfProfileIn( $fname.'-setup' );
1493 static $tc = FALSE;
1494 # the % is needed to support urlencoded titles as well
1495 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1496
1497 $sk = $this->mOptions->getSkin();
1498
1499 #split the entire text string on occurences of [[
1500 $a = explode( '[[', ' ' . $s );
1501 #get the first element (all text up to first [[), and remove the space we added
1502 $s = array_shift( $a );
1503 $s = substr( $s, 1 );
1504
1505 # Match a link having the form [[namespace:link|alternate]]trail
1506 static $e1 = FALSE;
1507 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1508 # Match cases where there is no "]]", which might still be images
1509 static $e1_img = FALSE;
1510 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1511
1512 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1513 $e2 = null;
1514 if ( $useLinkPrefixExtension ) {
1515 # Match the end of a line for a word that's not followed by whitespace,
1516 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1517 $e2 = wfMsgForContent( 'linkprefix' );
1518 }
1519
1520 if( is_null( $this->mTitle ) ) {
1521 wfProfileOut( $fname );
1522 wfProfileOut( $fname.'-setup' );
1523 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1524 }
1525 $nottalk = !$this->mTitle->isTalkPage();
1526
1527 if ( $useLinkPrefixExtension ) {
1528 $m = array();
1529 if ( preg_match( $e2, $s, $m ) ) {
1530 $first_prefix = $m[2];
1531 } else {
1532 $first_prefix = false;
1533 }
1534 } else {
1535 $prefix = '';
1536 }
1537
1538 if($wgContLang->hasVariants()) {
1539 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1540 } else {
1541 $selflink = array($this->mTitle->getPrefixedText());
1542 }
1543 $useSubpages = $this->areSubpagesAllowed();
1544 wfProfileOut( $fname.'-setup' );
1545
1546 # Loop for each link
1547 for ($k = 0; isset( $a[$k] ); $k++) {
1548 $line = $a[$k];
1549 if ( $useLinkPrefixExtension ) {
1550 wfProfileIn( $fname.'-prefixhandling' );
1551 if ( preg_match( $e2, $s, $m ) ) {
1552 $prefix = $m[2];
1553 $s = $m[1];
1554 } else {
1555 $prefix='';
1556 }
1557 # first link
1558 if($first_prefix) {
1559 $prefix = $first_prefix;
1560 $first_prefix = false;
1561 }
1562 wfProfileOut( $fname.'-prefixhandling' );
1563 }
1564
1565 $might_be_img = false;
1566
1567 wfProfileIn( "$fname-e1" );
1568 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1569 $text = $m[2];
1570 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1571 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1572 # the real problem is with the $e1 regex
1573 # See bug 1300.
1574 #
1575 # Still some problems for cases where the ] is meant to be outside punctuation,
1576 # and no image is in sight. See bug 2095.
1577 #
1578 if( $text !== '' &&
1579 substr( $m[3], 0, 1 ) === ']' &&
1580 strpos($text, '[') !== false
1581 )
1582 {
1583 $text .= ']'; # so that replaceExternalLinks($text) works later
1584 $m[3] = substr( $m[3], 1 );
1585 }
1586 # fix up urlencoded title texts
1587 if( strpos( $m[1], '%' ) !== false ) {
1588 # Should anchors '#' also be rejected?
1589 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1590 }
1591 $trail = $m[3];
1592 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1593 $might_be_img = true;
1594 $text = $m[2];
1595 if ( strpos( $m[1], '%' ) !== false ) {
1596 $m[1] = urldecode($m[1]);
1597 }
1598 $trail = "";
1599 } else { # Invalid form; output directly
1600 $s .= $prefix . '[[' . $line ;
1601 wfProfileOut( "$fname-e1" );
1602 continue;
1603 }
1604 wfProfileOut( "$fname-e1" );
1605 wfProfileIn( "$fname-misc" );
1606
1607 # Don't allow internal links to pages containing
1608 # PROTO: where PROTO is a valid URL protocol; these
1609 # should be external links.
1610 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1611 $s .= $prefix . '[[' . $line ;
1612 wfProfileOut( "$fname-misc" );
1613 continue;
1614 }
1615
1616 # Make subpage if necessary
1617 if( $useSubpages ) {
1618 $link = $this->maybeDoSubpageLink( $m[1], $text );
1619 } else {
1620 $link = $m[1];
1621 }
1622
1623 $noforce = (substr($m[1], 0, 1) != ':');
1624 if (!$noforce) {
1625 # Strip off leading ':'
1626 $link = substr($link, 1);
1627 }
1628
1629 wfProfileOut( "$fname-misc" );
1630 wfProfileIn( "$fname-title" );
1631 $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
1632 if( !$nt ) {
1633 $s .= $prefix . '[[' . $line;
1634 wfProfileOut( "$fname-title" );
1635 continue;
1636 }
1637
1638 $ns = $nt->getNamespace();
1639 $iw = $nt->getInterWiki();
1640 wfProfileOut( "$fname-title" );
1641
1642 if ($might_be_img) { # if this is actually an invalid link
1643 wfProfileIn( "$fname-might_be_img" );
1644 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1645 $found = false;
1646 while (isset ($a[$k+1]) ) {
1647 #look at the next 'line' to see if we can close it there
1648 $spliced = array_splice( $a, $k + 1, 1 );
1649 $next_line = array_shift( $spliced );
1650 $m = explode( ']]', $next_line, 3 );
1651 if ( count( $m ) == 3 ) {
1652 # the first ]] closes the inner link, the second the image
1653 $found = true;
1654 $text .= "[[{$m[0]}]]{$m[1]}";
1655 $trail = $m[2];
1656 break;
1657 } elseif ( count( $m ) == 2 ) {
1658 #if there's exactly one ]] that's fine, we'll keep looking
1659 $text .= "[[{$m[0]}]]{$m[1]}";
1660 } else {
1661 #if $next_line is invalid too, we need look no further
1662 $text .= '[[' . $next_line;
1663 break;
1664 }
1665 }
1666 if ( !$found ) {
1667 # we couldn't find the end of this imageLink, so output it raw
1668 #but don't ignore what might be perfectly normal links in the text we've examined
1669 $text = $this->replaceInternalLinks($text);
1670 $s .= "{$prefix}[[$link|$text";
1671 # note: no $trail, because without an end, there *is* no trail
1672 wfProfileOut( "$fname-might_be_img" );
1673 continue;
1674 }
1675 } else { #it's not an image, so output it raw
1676 $s .= "{$prefix}[[$link|$text";
1677 # note: no $trail, because without an end, there *is* no trail
1678 wfProfileOut( "$fname-might_be_img" );
1679 continue;
1680 }
1681 wfProfileOut( "$fname-might_be_img" );
1682 }
1683
1684 $wasblank = ( '' == $text );
1685 if( $wasblank ) $text = $link;
1686
1687 # Link not escaped by : , create the various objects
1688 if( $noforce ) {
1689
1690 # Interwikis
1691 wfProfileIn( "$fname-interwiki" );
1692 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1693 $this->mOutput->addLanguageLink( $nt->getFullText() );
1694 $s = rtrim($s . $prefix);
1695 $s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
1696 wfProfileOut( "$fname-interwiki" );
1697 continue;
1698 }
1699 wfProfileOut( "$fname-interwiki" );
1700
1701 if ( $ns == NS_IMAGE ) {
1702 wfProfileIn( "$fname-image" );
1703 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1704 # recursively parse links inside the image caption
1705 # actually, this will parse them in any other parameters, too,
1706 # but it might be hard to fix that, and it doesn't matter ATM
1707 $text = $this->replaceExternalLinks($text);
1708 $text = $this->replaceInternalLinks($text);
1709
1710 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1711 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1712 $this->mOutput->addImage( $nt->getDBkey() );
1713
1714 wfProfileOut( "$fname-image" );
1715 continue;
1716 } else {
1717 # We still need to record the image's presence on the page
1718 $this->mOutput->addImage( $nt->getDBkey() );
1719 }
1720 wfProfileOut( "$fname-image" );
1721
1722 }
1723
1724 if ( $ns == NS_CATEGORY ) {
1725 wfProfileIn( "$fname-category" );
1726 $s = rtrim($s . "\n"); # bug 87
1727
1728 if ( $wasblank ) {
1729 $sortkey = $this->getDefaultSort();
1730 } else {
1731 $sortkey = $text;
1732 }
1733 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1734 $sortkey = str_replace( "\n", '', $sortkey );
1735 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1736 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1737
1738 /**
1739 * Strip the whitespace Category links produce, see bug 87
1740 * @todo We might want to use trim($tmp, "\n") here.
1741 */
1742 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1743
1744 wfProfileOut( "$fname-category" );
1745 continue;
1746 }
1747 }
1748
1749 # Self-link checking
1750 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL ) {
1751 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1752 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1753 continue;
1754 }
1755 }
1756
1757 # Special and Media are pseudo-namespaces; no pages actually exist in them
1758 if( $ns == NS_MEDIA ) {
1759 # Give extensions a chance to select the file revision for us
1760 $skip = $time = false;
1761 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1762 if ( $skip ) {
1763 $link = $sk->link( $nt );
1764 } else {
1765 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1766 }
1767 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1768 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1769 $this->mOutput->addImage( $nt->getDBkey() );
1770 continue;
1771 } elseif( $ns == NS_SPECIAL ) {
1772 if( SpecialPage::exists( $nt->getDBkey() ) ) {
1773 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1774 } else {
1775 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1776 }
1777 continue;
1778 } elseif( $ns == NS_IMAGE ) {
1779 $img = wfFindFile( $nt );
1780 if( $img ) {
1781 // Force a blue link if the file exists; may be a remote
1782 // upload on the shared repository, and we want to see its
1783 // auto-generated page.
1784 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1785 $this->mOutput->addLink( $nt );
1786 continue;
1787 }
1788 }
1789 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1790 }
1791 wfProfileOut( $fname );
1792 return $s;
1793 }
1794
1795 /**
1796 * Make a link placeholder. The text returned can be later resolved to a real link with
1797 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1798 * parsing of interwiki links, and secondly to allow all existence checks and
1799 * article length checks (for stub links) to be bundled into a single query.
1800 *
1801 */
1802 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1803 wfProfileIn( __METHOD__ );
1804 if ( ! is_object($nt) ) {
1805 # Fail gracefully
1806 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1807 } else {
1808 # Separate the link trail from the rest of the link
1809 list( $inside, $trail ) = Linker::splitTrail( $trail );
1810
1811 if ( $nt->isExternal() ) {
1812 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1813 $this->mInterwikiLinkHolders['titles'][] = $nt;
1814 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1815 } else {
1816 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1817 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1818 $this->mLinkHolders['queries'][] = $query;
1819 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1820 $this->mLinkHolders['titles'][] = $nt;
1821
1822 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1823 }
1824 }
1825 wfProfileOut( __METHOD__ );
1826 return $retVal;
1827 }
1828
1829 /**
1830 * Render a forced-blue link inline; protect against double expansion of
1831 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1832 * Since this little disaster has to split off the trail text to avoid
1833 * breaking URLs in the following text without breaking trails on the
1834 * wiki links, it's been made into a horrible function.
1835 *
1836 * @param Title $nt
1837 * @param string $text
1838 * @param string $query
1839 * @param string $trail
1840 * @param string $prefix
1841 * @return string HTML-wikitext mix oh yuck
1842 */
1843 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1844 list( $inside, $trail ) = Linker::splitTrail( $trail );
1845 $sk = $this->mOptions->getSkin();
1846 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1847 return $this->armorLinks( $link ) . $trail;
1848 }
1849
1850 /**
1851 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1852 * going to go through further parsing steps before inline URL expansion.
1853 *
1854 * In particular this is important when using action=render, which causes
1855 * full URLs to be included.
1856 *
1857 * Oh man I hate our multi-layer parser!
1858 *
1859 * @param string more-or-less HTML
1860 * @return string less-or-more HTML with NOPARSE bits
1861 */
1862 function armorLinks( $text ) {
1863 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1864 "{$this->mUniqPrefix}NOPARSE$1", $text );
1865 }
1866
1867 /**
1868 * Return true if subpage links should be expanded on this page.
1869 * @return bool
1870 */
1871 function areSubpagesAllowed() {
1872 # Some namespaces don't allow subpages
1873 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
1874 }
1875
1876 /**
1877 * Handle link to subpage if necessary
1878 * @param string $target the source of the link
1879 * @param string &$text the link text, modified as necessary
1880 * @return string the full name of the link
1881 * @private
1882 */
1883 function maybeDoSubpageLink($target, &$text) {
1884 # Valid link forms:
1885 # Foobar -- normal
1886 # :Foobar -- override special treatment of prefix (images, language links)
1887 # /Foobar -- convert to CurrentPage/Foobar
1888 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1889 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1890 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1891
1892 $fname = 'Parser::maybeDoSubpageLink';
1893 wfProfileIn( $fname );
1894 $ret = $target; # default return value is no change
1895
1896 # Some namespaces don't allow subpages,
1897 # so only perform processing if subpages are allowed
1898 if( $this->areSubpagesAllowed() ) {
1899 $hash = strpos( $target, '#' );
1900 if( $hash !== false ) {
1901 $suffix = substr( $target, $hash );
1902 $target = substr( $target, 0, $hash );
1903 } else {
1904 $suffix = '';
1905 }
1906 # bug 7425
1907 $target = trim( $target );
1908 # Look at the first character
1909 if( $target != '' && $target{0} == '/' ) {
1910 # / at end means we don't want the slash to be shown
1911 $m = array();
1912 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1913 if( $trailingSlashes ) {
1914 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1915 } else {
1916 $noslash = substr( $target, 1 );
1917 }
1918
1919 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1920 if( '' === $text ) {
1921 $text = $target . $suffix;
1922 } # this might be changed for ugliness reasons
1923 } else {
1924 # check for .. subpage backlinks
1925 $dotdotcount = 0;
1926 $nodotdot = $target;
1927 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1928 ++$dotdotcount;
1929 $nodotdot = substr( $nodotdot, 3 );
1930 }
1931 if($dotdotcount > 0) {
1932 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1933 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1934 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1935 # / at the end means don't show full path
1936 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1937 $nodotdot = substr( $nodotdot, 0, -1 );
1938 if( '' === $text ) {
1939 $text = $nodotdot . $suffix;
1940 }
1941 }
1942 $nodotdot = trim( $nodotdot );
1943 if( $nodotdot != '' ) {
1944 $ret .= '/' . $nodotdot;
1945 }
1946 $ret .= $suffix;
1947 }
1948 }
1949 }
1950 }
1951
1952 wfProfileOut( $fname );
1953 return $ret;
1954 }
1955
1956 /**#@+
1957 * Used by doBlockLevels()
1958 * @private
1959 */
1960 /* private */ function closeParagraph() {
1961 $result = '';
1962 if ( '' != $this->mLastSection ) {
1963 $result = '</' . $this->mLastSection . ">\n";
1964 }
1965 $this->mInPre = false;
1966 $this->mLastSection = '';
1967 return $result;
1968 }
1969 # getCommon() returns the length of the longest common substring
1970 # of both arguments, starting at the beginning of both.
1971 #
1972 /* private */ function getCommon( $st1, $st2 ) {
1973 $fl = strlen( $st1 );
1974 $shorter = strlen( $st2 );
1975 if ( $fl < $shorter ) { $shorter = $fl; }
1976
1977 for ( $i = 0; $i < $shorter; ++$i ) {
1978 if ( $st1{$i} != $st2{$i} ) { break; }
1979 }
1980 return $i;
1981 }
1982 # These next three functions open, continue, and close the list
1983 # element appropriate to the prefix character passed into them.
1984 #
1985 /* private */ function openList( $char ) {
1986 $result = $this->closeParagraph();
1987
1988 if ( '*' == $char ) { $result .= '<ul><li>'; }
1989 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1990 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1991 else if ( ';' == $char ) {
1992 $result .= '<dl><dt>';
1993 $this->mDTopen = true;
1994 }
1995 else { $result = '<!-- ERR 1 -->'; }
1996
1997 return $result;
1998 }
1999
2000 /* private */ function nextItem( $char ) {
2001 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
2002 else if ( ':' == $char || ';' == $char ) {
2003 $close = '</dd>';
2004 if ( $this->mDTopen ) { $close = '</dt>'; }
2005 if ( ';' == $char ) {
2006 $this->mDTopen = true;
2007 return $close . '<dt>';
2008 } else {
2009 $this->mDTopen = false;
2010 return $close . '<dd>';
2011 }
2012 }
2013 return '<!-- ERR 2 -->';
2014 }
2015
2016 /* private */ function closeList( $char ) {
2017 if ( '*' == $char ) { $text = '</li></ul>'; }
2018 else if ( '#' == $char ) { $text = '</li></ol>'; }
2019 else if ( ':' == $char ) {
2020 if ( $this->mDTopen ) {
2021 $this->mDTopen = false;
2022 $text = '</dt></dl>';
2023 } else {
2024 $text = '</dd></dl>';
2025 }
2026 }
2027 else { return '<!-- ERR 3 -->'; }
2028 return $text."\n";
2029 }
2030 /**#@-*/
2031
2032 /**
2033 * Make lists from lines starting with ':', '*', '#', etc.
2034 *
2035 * @private
2036 * @return string the lists rendered as HTML
2037 */
2038 function doBlockLevels( $text, $linestart ) {
2039 $fname = 'Parser::doBlockLevels';
2040 wfProfileIn( $fname );
2041
2042 # Parsing through the text line by line. The main thing
2043 # happening here is handling of block-level elements p, pre,
2044 # and making lists from lines starting with * # : etc.
2045 #
2046 $textLines = explode( "\n", $text );
2047
2048 $lastPrefix = $output = '';
2049 $this->mDTopen = $inBlockElem = false;
2050 $prefixLength = 0;
2051 $paragraphStack = false;
2052
2053 if ( !$linestart ) {
2054 $output .= array_shift( $textLines );
2055 }
2056 foreach ( $textLines as $oLine ) {
2057 $lastPrefixLength = strlen( $lastPrefix );
2058 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2059 $preOpenMatch = preg_match('/<pre/i', $oLine );
2060 if ( !$this->mInPre ) {
2061 # Multiple prefixes may abut each other for nested lists.
2062 $prefixLength = strspn( $oLine, '*#:;' );
2063 $pref = substr( $oLine, 0, $prefixLength );
2064
2065 # eh?
2066 $pref2 = str_replace( ';', ':', $pref );
2067 $t = substr( $oLine, $prefixLength );
2068 $this->mInPre = !empty($preOpenMatch);
2069 } else {
2070 # Don't interpret any other prefixes in preformatted text
2071 $prefixLength = 0;
2072 $pref = $pref2 = '';
2073 $t = $oLine;
2074 }
2075
2076 # List generation
2077 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2078 # Same as the last item, so no need to deal with nesting or opening stuff
2079 $output .= $this->nextItem( substr( $pref, -1 ) );
2080 $paragraphStack = false;
2081
2082 if ( substr( $pref, -1 ) == ';') {
2083 # The one nasty exception: definition lists work like this:
2084 # ; title : definition text
2085 # So we check for : in the remainder text to split up the
2086 # title and definition, without b0rking links.
2087 $term = $t2 = '';
2088 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2089 $t = $t2;
2090 $output .= $term . $this->nextItem( ':' );
2091 }
2092 }
2093 } elseif( $prefixLength || $lastPrefixLength ) {
2094 # Either open or close a level...
2095 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2096 $paragraphStack = false;
2097
2098 while( $commonPrefixLength < $lastPrefixLength ) {
2099 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2100 --$lastPrefixLength;
2101 }
2102 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2103 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2104 }
2105 while ( $prefixLength > $commonPrefixLength ) {
2106 $char = substr( $pref, $commonPrefixLength, 1 );
2107 $output .= $this->openList( $char );
2108
2109 if ( ';' == $char ) {
2110 # FIXME: This is dupe of code above
2111 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2112 $t = $t2;
2113 $output .= $term . $this->nextItem( ':' );
2114 }
2115 }
2116 ++$commonPrefixLength;
2117 }
2118 $lastPrefix = $pref2;
2119 }
2120 if( 0 == $prefixLength ) {
2121 wfProfileIn( "$fname-paragraph" );
2122 # No prefix (not in list)--go to paragraph mode
2123 // XXX: use a stack for nestable elements like span, table and div
2124 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2125 $closematch = preg_match(
2126 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2127 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2128 if ( $openmatch or $closematch ) {
2129 $paragraphStack = false;
2130 # TODO bug 5718: paragraph closed
2131 $output .= $this->closeParagraph();
2132 if ( $preOpenMatch and !$preCloseMatch ) {
2133 $this->mInPre = true;
2134 }
2135 if ( $closematch ) {
2136 $inBlockElem = false;
2137 } else {
2138 $inBlockElem = true;
2139 }
2140 } else if ( !$inBlockElem && !$this->mInPre ) {
2141 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
2142 // pre
2143 if ($this->mLastSection != 'pre') {
2144 $paragraphStack = false;
2145 $output .= $this->closeParagraph().'<pre>';
2146 $this->mLastSection = 'pre';
2147 }
2148 $t = substr( $t, 1 );
2149 } else {
2150 // paragraph
2151 if ( '' == trim($t) ) {
2152 if ( $paragraphStack ) {
2153 $output .= $paragraphStack.'<br />';
2154 $paragraphStack = false;
2155 $this->mLastSection = 'p';
2156 } else {
2157 if ($this->mLastSection != 'p' ) {
2158 $output .= $this->closeParagraph();
2159 $this->mLastSection = '';
2160 $paragraphStack = '<p>';
2161 } else {
2162 $paragraphStack = '</p><p>';
2163 }
2164 }
2165 } else {
2166 if ( $paragraphStack ) {
2167 $output .= $paragraphStack;
2168 $paragraphStack = false;
2169 $this->mLastSection = 'p';
2170 } else if ($this->mLastSection != 'p') {
2171 $output .= $this->closeParagraph().'<p>';
2172 $this->mLastSection = 'p';
2173 }
2174 }
2175 }
2176 }
2177 wfProfileOut( "$fname-paragraph" );
2178 }
2179 // somewhere above we forget to get out of pre block (bug 785)
2180 if($preCloseMatch && $this->mInPre) {
2181 $this->mInPre = false;
2182 }
2183 if ($paragraphStack === false) {
2184 $output .= $t."\n";
2185 }
2186 }
2187 while ( $prefixLength ) {
2188 $output .= $this->closeList( $pref2{$prefixLength-1} );
2189 --$prefixLength;
2190 }
2191 if ( '' != $this->mLastSection ) {
2192 $output .= '</' . $this->mLastSection . '>';
2193 $this->mLastSection = '';
2194 }
2195
2196 wfProfileOut( $fname );
2197 return $output;
2198 }
2199
2200 /**
2201 * Split up a string on ':', ignoring any occurences inside tags
2202 * to prevent illegal overlapping.
2203 * @param string $str the string to split
2204 * @param string &$before set to everything before the ':'
2205 * @param string &$after set to everything after the ':'
2206 * return string the position of the ':', or false if none found
2207 */
2208 function findColonNoLinks($str, &$before, &$after) {
2209 $fname = 'Parser::findColonNoLinks';
2210 wfProfileIn( $fname );
2211
2212 $pos = strpos( $str, ':' );
2213 if( $pos === false ) {
2214 // Nothing to find!
2215 wfProfileOut( $fname );
2216 return false;
2217 }
2218
2219 $lt = strpos( $str, '<' );
2220 if( $lt === false || $lt > $pos ) {
2221 // Easy; no tag nesting to worry about
2222 $before = substr( $str, 0, $pos );
2223 $after = substr( $str, $pos+1 );
2224 wfProfileOut( $fname );
2225 return $pos;
2226 }
2227
2228 // Ugly state machine to walk through avoiding tags.
2229 $state = self::COLON_STATE_TEXT;
2230 $stack = 0;
2231 $len = strlen( $str );
2232 for( $i = 0; $i < $len; $i++ ) {
2233 $c = $str{$i};
2234
2235 switch( $state ) {
2236 // (Using the number is a performance hack for common cases)
2237 case 0: // self::COLON_STATE_TEXT:
2238 switch( $c ) {
2239 case "<":
2240 // Could be either a <start> tag or an </end> tag
2241 $state = self::COLON_STATE_TAGSTART;
2242 break;
2243 case ":":
2244 if( $stack == 0 ) {
2245 // We found it!
2246 $before = substr( $str, 0, $i );
2247 $after = substr( $str, $i + 1 );
2248 wfProfileOut( $fname );
2249 return $i;
2250 }
2251 // Embedded in a tag; don't break it.
2252 break;
2253 default:
2254 // Skip ahead looking for something interesting
2255 $colon = strpos( $str, ':', $i );
2256 if( $colon === false ) {
2257 // Nothing else interesting
2258 wfProfileOut( $fname );
2259 return false;
2260 }
2261 $lt = strpos( $str, '<', $i );
2262 if( $stack === 0 ) {
2263 if( $lt === false || $colon < $lt ) {
2264 // We found it!
2265 $before = substr( $str, 0, $colon );
2266 $after = substr( $str, $colon + 1 );
2267 wfProfileOut( $fname );
2268 return $i;
2269 }
2270 }
2271 if( $lt === false ) {
2272 // Nothing else interesting to find; abort!
2273 // We're nested, but there's no close tags left. Abort!
2274 break 2;
2275 }
2276 // Skip ahead to next tag start
2277 $i = $lt;
2278 $state = self::COLON_STATE_TAGSTART;
2279 }
2280 break;
2281 case 1: // self::COLON_STATE_TAG:
2282 // In a <tag>
2283 switch( $c ) {
2284 case ">":
2285 $stack++;
2286 $state = self::COLON_STATE_TEXT;
2287 break;
2288 case "/":
2289 // Slash may be followed by >?
2290 $state = self::COLON_STATE_TAGSLASH;
2291 break;
2292 default:
2293 // ignore
2294 }
2295 break;
2296 case 2: // self::COLON_STATE_TAGSTART:
2297 switch( $c ) {
2298 case "/":
2299 $state = self::COLON_STATE_CLOSETAG;
2300 break;
2301 case "!":
2302 $state = self::COLON_STATE_COMMENT;
2303 break;
2304 case ">":
2305 // Illegal early close? This shouldn't happen D:
2306 $state = self::COLON_STATE_TEXT;
2307 break;
2308 default:
2309 $state = self::COLON_STATE_TAG;
2310 }
2311 break;
2312 case 3: // self::COLON_STATE_CLOSETAG:
2313 // In a </tag>
2314 if( $c == ">" ) {
2315 $stack--;
2316 if( $stack < 0 ) {
2317 wfDebug( "Invalid input in $fname; too many close tags\n" );
2318 wfProfileOut( $fname );
2319 return false;
2320 }
2321 $state = self::COLON_STATE_TEXT;
2322 }
2323 break;
2324 case self::COLON_STATE_TAGSLASH:
2325 if( $c == ">" ) {
2326 // Yes, a self-closed tag <blah/>
2327 $state = self::COLON_STATE_TEXT;
2328 } else {
2329 // Probably we're jumping the gun, and this is an attribute
2330 $state = self::COLON_STATE_TAG;
2331 }
2332 break;
2333 case 5: // self::COLON_STATE_COMMENT:
2334 if( $c == "-" ) {
2335 $state = self::COLON_STATE_COMMENTDASH;
2336 }
2337 break;
2338 case self::COLON_STATE_COMMENTDASH:
2339 if( $c == "-" ) {
2340 $state = self::COLON_STATE_COMMENTDASHDASH;
2341 } else {
2342 $state = self::COLON_STATE_COMMENT;
2343 }
2344 break;
2345 case self::COLON_STATE_COMMENTDASHDASH:
2346 if( $c == ">" ) {
2347 $state = self::COLON_STATE_TEXT;
2348 } else {
2349 $state = self::COLON_STATE_COMMENT;
2350 }
2351 break;
2352 default:
2353 throw new MWException( "State machine error in $fname" );
2354 }
2355 }
2356 if( $stack > 0 ) {
2357 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2358 return false;
2359 }
2360 wfProfileOut( $fname );
2361 return false;
2362 }
2363
2364 /**
2365 * Return value of a magic variable (like PAGENAME)
2366 *
2367 * @private
2368 */
2369 function getVariableValue( $index ) {
2370 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2371
2372 /**
2373 * Some of these require message or data lookups and can be
2374 * expensive to check many times.
2375 */
2376 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2377 if ( isset( $this->mVarCache[$index] ) ) {
2378 return $this->mVarCache[$index];
2379 }
2380 }
2381
2382 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2383 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2384
2385 # Use the time zone
2386 global $wgLocaltimezone;
2387 if ( isset( $wgLocaltimezone ) ) {
2388 $oldtz = getenv( 'TZ' );
2389 putenv( 'TZ='.$wgLocaltimezone );
2390 }
2391
2392 wfSuppressWarnings(); // E_STRICT system time bitching
2393 $localTimestamp = date( 'YmdHis', $ts );
2394 $localMonth = date( 'm', $ts );
2395 $localMonthName = date( 'n', $ts );
2396 $localDay = date( 'j', $ts );
2397 $localDay2 = date( 'd', $ts );
2398 $localDayOfWeek = date( 'w', $ts );
2399 $localWeek = date( 'W', $ts );
2400 $localYear = date( 'Y', $ts );
2401 $localHour = date( 'H', $ts );
2402 if ( isset( $wgLocaltimezone ) ) {
2403 putenv( 'TZ='.$oldtz );
2404 }
2405 wfRestoreWarnings();
2406
2407 switch ( $index ) {
2408 case 'currentmonth':
2409 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2410 case 'currentmonthname':
2411 return $this->mVarCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2412 case 'currentmonthnamegen':
2413 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2414 case 'currentmonthabbrev':
2415 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2416 case 'currentday':
2417 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2418 case 'currentday2':
2419 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2420 case 'localmonth':
2421 return $this->mVarCache[$index] = $wgContLang->formatNum( $localMonth );
2422 case 'localmonthname':
2423 return $this->mVarCache[$index] = $wgContLang->getMonthName( $localMonthName );
2424 case 'localmonthnamegen':
2425 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2426 case 'localmonthabbrev':
2427 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2428 case 'localday':
2429 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay );
2430 case 'localday2':
2431 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay2 );
2432 case 'pagename':
2433 return wfEscapeWikiText( $this->mTitle->getText() );
2434 case 'pagenamee':
2435 return $this->mTitle->getPartialURL();
2436 case 'fullpagename':
2437 return wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2438 case 'fullpagenamee':
2439 return $this->mTitle->getPrefixedURL();
2440 case 'subpagename':
2441 return wfEscapeWikiText( $this->mTitle->getSubpageText() );
2442 case 'subpagenamee':
2443 return $this->mTitle->getSubpageUrlForm();
2444 case 'basepagename':
2445 return wfEscapeWikiText( $this->mTitle->getBaseText() );
2446 case 'basepagenamee':
2447 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2448 case 'talkpagename':
2449 if( $this->mTitle->canTalk() ) {
2450 $talkPage = $this->mTitle->getTalkPage();
2451 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2452 } else {
2453 return '';
2454 }
2455 case 'talkpagenamee':
2456 if( $this->mTitle->canTalk() ) {
2457 $talkPage = $this->mTitle->getTalkPage();
2458 return $talkPage->getPrefixedUrl();
2459 } else {
2460 return '';
2461 }
2462 case 'subjectpagename':
2463 $subjPage = $this->mTitle->getSubjectPage();
2464 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2465 case 'subjectpagenamee':
2466 $subjPage = $this->mTitle->getSubjectPage();
2467 return $subjPage->getPrefixedUrl();
2468 case 'revisionid':
2469 // Let the edit saving system know we should parse the page
2470 // *after* a revision ID has been assigned.
2471 $this->mOutput->setFlag( 'vary-revision' );
2472 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2473 return $this->mRevisionId;
2474 case 'revisionday':
2475 // Let the edit saving system know we should parse the page
2476 // *after* a revision ID has been assigned. This is for null edits.
2477 $this->mOutput->setFlag( 'vary-revision' );
2478 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2479 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2480 case 'revisionday2':
2481 // Let the edit saving system know we should parse the page
2482 // *after* a revision ID has been assigned. This is for null edits.
2483 $this->mOutput->setFlag( 'vary-revision' );
2484 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2485 return substr( $this->getRevisionTimestamp(), 6, 2 );
2486 case 'revisionmonth':
2487 // Let the edit saving system know we should parse the page
2488 // *after* a revision ID has been assigned. This is for null edits.
2489 $this->mOutput->setFlag( 'vary-revision' );
2490 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2491 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2492 case 'revisionyear':
2493 // Let the edit saving system know we should parse the page
2494 // *after* a revision ID has been assigned. This is for null edits.
2495 $this->mOutput->setFlag( 'vary-revision' );
2496 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2497 return substr( $this->getRevisionTimestamp(), 0, 4 );
2498 case 'revisiontimestamp':
2499 // Let the edit saving system know we should parse the page
2500 // *after* a revision ID has been assigned. This is for null edits.
2501 $this->mOutput->setFlag( 'vary-revision' );
2502 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2503 return $this->getRevisionTimestamp();
2504 case 'namespace':
2505 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2506 case 'namespacee':
2507 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2508 case 'talkspace':
2509 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2510 case 'talkspacee':
2511 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2512 case 'subjectspace':
2513 return $this->mTitle->getSubjectNsText();
2514 case 'subjectspacee':
2515 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2516 case 'currentdayname':
2517 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2518 case 'currentyear':
2519 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2520 case 'currenttime':
2521 return $this->mVarCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2522 case 'currenthour':
2523 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2524 case 'currentweek':
2525 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2526 // int to remove the padding
2527 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2528 case 'currentdow':
2529 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2530 case 'localdayname':
2531 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2532 case 'localyear':
2533 return $this->mVarCache[$index] = $wgContLang->formatNum( $localYear, true );
2534 case 'localtime':
2535 return $this->mVarCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2536 case 'localhour':
2537 return $this->mVarCache[$index] = $wgContLang->formatNum( $localHour, true );
2538 case 'localweek':
2539 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2540 // int to remove the padding
2541 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2542 case 'localdow':
2543 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2544 case 'numberofarticles':
2545 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2546 case 'numberoffiles':
2547 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2548 case 'numberofusers':
2549 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2550 case 'numberofpages':
2551 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2552 case 'numberofadmins':
2553 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::numberingroup('sysop') );
2554 case 'numberofedits':
2555 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::edits() );
2556 case 'currenttimestamp':
2557 return $this->mVarCache[$index] = wfTimestamp( TS_MW, $ts );
2558 case 'localtimestamp':
2559 return $this->mVarCache[$index] = $localTimestamp;
2560 case 'currentversion':
2561 return $this->mVarCache[$index] = SpecialVersion::getVersion();
2562 case 'sitename':
2563 return $wgSitename;
2564 case 'server':
2565 return $wgServer;
2566 case 'servername':
2567 return $wgServerName;
2568 case 'scriptpath':
2569 return $wgScriptPath;
2570 case 'directionmark':
2571 return $wgContLang->getDirMark();
2572 case 'contentlanguage':
2573 global $wgContLanguageCode;
2574 return $wgContLanguageCode;
2575 default:
2576 $ret = null;
2577 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret ) ) )
2578 return $ret;
2579 else
2580 return null;
2581 }
2582 }
2583
2584 /**
2585 * initialise the magic variables (like CURRENTMONTHNAME)
2586 *
2587 * @private
2588 */
2589 function initialiseVariables() {
2590 $fname = 'Parser::initialiseVariables';
2591 wfProfileIn( $fname );
2592 $variableIDs = MagicWord::getVariableIDs();
2593
2594 $this->mVariables = new MagicWordArray( $variableIDs );
2595 wfProfileOut( $fname );
2596 }
2597
2598 /**
2599 * Preprocess some wikitext and return the document tree.
2600 * This is the ghost of replace_variables().
2601 *
2602 * @param string $text The text to parse
2603 * @param integer flags Bitwise combination of:
2604 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2605 * included. Default is to assume a direct page view.
2606 *
2607 * The generated DOM tree must depend only on the input text and the flags.
2608 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2609 *
2610 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2611 * change in the DOM tree for a given text, must be passed through the section identifier
2612 * in the section edit link and thus back to extractSections().
2613 *
2614 * The output of this function is currently only cached in process memory, but a persistent
2615 * cache may be implemented at a later date which takes further advantage of these strict
2616 * dependency requirements.
2617 *
2618 * @private
2619 */
2620 function preprocessToDom ( $text, $flags = 0 ) {
2621 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2622 return $dom;
2623 }
2624
2625 /*
2626 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2627 */
2628 public static function splitWhitespace( $s ) {
2629 $ltrimmed = ltrim( $s );
2630 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2631 $trimmed = rtrim( $ltrimmed );
2632 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2633 if ( $diff > 0 ) {
2634 $w2 = substr( $ltrimmed, -$diff );
2635 } else {
2636 $w2 = '';
2637 }
2638 return array( $w1, $trimmed, $w2 );
2639 }
2640
2641 /**
2642 * Replace magic variables, templates, and template arguments
2643 * with the appropriate text. Templates are substituted recursively,
2644 * taking care to avoid infinite loops.
2645 *
2646 * Note that the substitution depends on value of $mOutputType:
2647 * self::OT_WIKI: only {{subst:}} templates
2648 * self::OT_PREPROCESS: templates but not extension tags
2649 * self::OT_HTML: all templates and extension tags
2650 *
2651 * @param string $tex The text to transform
2652 * @param PPFrame $frame Object describing the arguments passed to the template.
2653 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2654 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2655 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2656 * @private
2657 */
2658 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2659 # Prevent too big inclusions
2660 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2661 return $text;
2662 }
2663
2664 $fname = __METHOD__;
2665 wfProfileIn( $fname );
2666
2667 if ( $frame === false ) {
2668 $frame = $this->getPreprocessor()->newFrame();
2669 } elseif ( !( $frame instanceof PPFrame ) ) {
2670 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2671 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2672 }
2673
2674 $dom = $this->preprocessToDom( $text );
2675 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2676 $text = $frame->expand( $dom, $flags );
2677
2678 wfProfileOut( $fname );
2679 return $text;
2680 }
2681
2682 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2683 static function createAssocArgs( $args ) {
2684 $assocArgs = array();
2685 $index = 1;
2686 foreach( $args as $arg ) {
2687 $eqpos = strpos( $arg, '=' );
2688 if ( $eqpos === false ) {
2689 $assocArgs[$index++] = $arg;
2690 } else {
2691 $name = trim( substr( $arg, 0, $eqpos ) );
2692 $value = trim( substr( $arg, $eqpos+1 ) );
2693 if ( $value === false ) {
2694 $value = '';
2695 }
2696 if ( $name !== false ) {
2697 $assocArgs[$name] = $value;
2698 }
2699 }
2700 }
2701
2702 return $assocArgs;
2703 }
2704
2705 /**
2706 * Warn the user when a parser limitation is reached
2707 * Will warn at most once the user per limitation type
2708 *
2709 * @param string $limitationType, should be one of:
2710 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2711 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2712 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2713 * @params int $current, $max When an explicit limit has been
2714 * exceeded, provide the values (optional)
2715 */
2716 function limitationWarn( $limitationType, $current=null, $max=null) {
2717 $msgName = $limitationType . '-warning';
2718 //does no harm if $current and $max are present but are unnecessary for the message
2719 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2720 $this->mOutput->addWarning( $warning );
2721 $cat = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( $limitationType . '-category' ) );
2722 if ( $cat ) {
2723 $this->mOutput->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2724 }
2725 }
2726
2727 /**
2728 * Return the text of a template, after recursively
2729 * replacing any variables or templates within the template.
2730 *
2731 * @param array $piece The parts of the template
2732 * $piece['title']: the title, i.e. the part before the |
2733 * $piece['parts']: the parameter array
2734 * $piece['lineStart']: whether the brace was at the start of a line
2735 * @param PPFrame The current frame, contains template arguments
2736 * @return string the text of the template
2737 * @private
2738 */
2739 function braceSubstitution( $piece, $frame ) {
2740 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2741 $fname = __METHOD__;
2742 wfProfileIn( $fname );
2743 wfProfileIn( __METHOD__.'-setup' );
2744
2745 # Flags
2746 $found = false; # $text has been filled
2747 $nowiki = false; # wiki markup in $text should be escaped
2748 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2749 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2750 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2751 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2752
2753 # Title object, where $text came from
2754 $title = NULL;
2755
2756 # $part1 is the bit before the first |, and must contain only title characters.
2757 # Various prefixes will be stripped from it later.
2758 $titleWithSpaces = $frame->expand( $piece['title'] );
2759 $part1 = trim( $titleWithSpaces );
2760 $titleText = false;
2761
2762 # Original title text preserved for various purposes
2763 $originalTitle = $part1;
2764
2765 # $args is a list of argument nodes, starting from index 0, not including $part1
2766 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2767 wfProfileOut( __METHOD__.'-setup' );
2768
2769 # SUBST
2770 wfProfileIn( __METHOD__.'-modifiers' );
2771 if ( !$found ) {
2772 $mwSubst = MagicWord::get( 'subst' );
2773 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2774 # One of two possibilities is true:
2775 # 1) Found SUBST but not in the PST phase
2776 # 2) Didn't find SUBST and in the PST phase
2777 # In either case, return without further processing
2778 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2779 $isLocalObj = true;
2780 $found = true;
2781 }
2782 }
2783
2784 # Variables
2785 if ( !$found && $args->getLength() == 0 ) {
2786 $id = $this->mVariables->matchStartToEnd( $part1 );
2787 if ( $id !== false ) {
2788 $text = $this->getVariableValue( $id );
2789 if (MagicWord::getCacheTTL($id)>-1)
2790 $this->mOutput->mContainsOldMagic = true;
2791 $found = true;
2792 }
2793 }
2794
2795 # MSG, MSGNW and RAW
2796 if ( !$found ) {
2797 # Check for MSGNW:
2798 $mwMsgnw = MagicWord::get( 'msgnw' );
2799 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2800 $nowiki = true;
2801 } else {
2802 # Remove obsolete MSG:
2803 $mwMsg = MagicWord::get( 'msg' );
2804 $mwMsg->matchStartAndRemove( $part1 );
2805 }
2806
2807 # Check for RAW:
2808 $mwRaw = MagicWord::get( 'raw' );
2809 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2810 $forceRawInterwiki = true;
2811 }
2812 }
2813 wfProfileOut( __METHOD__.'-modifiers' );
2814
2815 # Parser functions
2816 if ( !$found ) {
2817 wfProfileIn( __METHOD__ . '-pfunc' );
2818
2819 $colonPos = strpos( $part1, ':' );
2820 if ( $colonPos !== false ) {
2821 # Case sensitive functions
2822 $function = substr( $part1, 0, $colonPos );
2823 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2824 $function = $this->mFunctionSynonyms[1][$function];
2825 } else {
2826 # Case insensitive functions
2827 $function = strtolower( $function );
2828 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2829 $function = $this->mFunctionSynonyms[0][$function];
2830 } else {
2831 $function = false;
2832 }
2833 }
2834 if ( $function ) {
2835 list( $callback, $flags ) = $this->mFunctionHooks[$function];
2836 $initialArgs = array( &$this );
2837 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
2838 if ( $flags & SFH_OBJECT_ARGS ) {
2839 # Add a frame parameter, and pass the arguments as an array
2840 $allArgs = $initialArgs;
2841 $allArgs[] = $frame;
2842 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2843 $funcArgs[] = $args->item( $i );
2844 }
2845 $allArgs[] = $funcArgs;
2846 } else {
2847 # Convert arguments to plain text
2848 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2849 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2850 }
2851 $allArgs = array_merge( $initialArgs, $funcArgs );
2852 }
2853
2854 # Workaround for PHP bug 35229 and similar
2855 if ( !is_callable( $callback ) ) {
2856 throw new MWException( "Tag hook for $name is not callable\n" );
2857 }
2858 $result = call_user_func_array( $callback, $allArgs );
2859 $found = true;
2860 $noparse = true;
2861 $preprocessFlags = 0;
2862
2863 if ( is_array( $result ) ) {
2864 if ( isset( $result[0] ) ) {
2865 $text = $result[0];
2866 unset( $result[0] );
2867 }
2868
2869 // Extract flags into the local scope
2870 // This allows callers to set flags such as nowiki, found, etc.
2871 extract( $result );
2872 } else {
2873 $text = $result;
2874 }
2875 if ( !$noparse ) {
2876 $text = $this->preprocessToDom( $text, $preprocessFlags );
2877 $isChildObj = true;
2878 }
2879 }
2880 }
2881 wfProfileOut( __METHOD__ . '-pfunc' );
2882 }
2883
2884 # Finish mangling title and then check for loops.
2885 # Set $title to a Title object and $titleText to the PDBK
2886 if ( !$found ) {
2887 $ns = NS_TEMPLATE;
2888 # Split the title into page and subpage
2889 $subpage = '';
2890 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2891 if ($subpage !== '') {
2892 $ns = $this->mTitle->getNamespace();
2893 }
2894 $title = Title::newFromText( $part1, $ns );
2895 if ( $title ) {
2896 $titleText = $title->getPrefixedText();
2897 # Check for language variants if the template is not found
2898 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2899 $wgContLang->findVariantLink($part1, $title);
2900 }
2901 # Do infinite loop check
2902 if ( !$frame->loopCheck( $title ) ) {
2903 $found = true;
2904 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2905 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
2906 }
2907 # Do recursion depth check
2908 $limit = $this->mOptions->getMaxTemplateDepth();
2909 if ( $frame->depth >= $limit ) {
2910 $found = true;
2911 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2912 }
2913 }
2914 }
2915
2916 # Load from database
2917 if ( !$found && $title ) {
2918 wfProfileIn( __METHOD__ . '-loadtpl' );
2919 if ( !$title->isExternal() ) {
2920 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
2921 $text = SpecialPage::capturePath( $title );
2922 if ( is_string( $text ) ) {
2923 $found = true;
2924 $isHTML = true;
2925 $this->disableCache();
2926 }
2927 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2928 $found = false; //access denied
2929 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2930 } else {
2931 list( $text, $title ) = $this->getTemplateDom( $title );
2932 if ( $text !== false ) {
2933 $found = true;
2934 $isChildObj = true;
2935 }
2936 }
2937
2938 # If the title is valid but undisplayable, make a link to it
2939 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2940 $text = "[[:$titleText]]";
2941 $found = true;
2942 }
2943 } elseif ( $title->isTrans() ) {
2944 // Interwiki transclusion
2945 if ( $this->ot['html'] && !$forceRawInterwiki ) {
2946 $text = $this->interwikiTransclude( $title, 'render' );
2947 $isHTML = true;
2948 } else {
2949 $text = $this->interwikiTransclude( $title, 'raw' );
2950 // Preprocess it like a template
2951 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
2952 $isChildObj = true;
2953 }
2954 $found = true;
2955 }
2956 wfProfileOut( __METHOD__ . '-loadtpl' );
2957 }
2958
2959 # If we haven't found text to substitute by now, we're done
2960 # Recover the source wikitext and return it
2961 if ( !$found ) {
2962 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2963 wfProfileOut( $fname );
2964 return array( 'object' => $text );
2965 }
2966
2967 # Expand DOM-style return values in a child frame
2968 if ( $isChildObj ) {
2969 # Clean up argument array
2970 $newFrame = $frame->newChild( $args, $title );
2971
2972 if ( $nowiki ) {
2973 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
2974 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2975 # Expansion is eligible for the empty-frame cache
2976 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
2977 $text = $this->mTplExpandCache[$titleText];
2978 } else {
2979 $text = $newFrame->expand( $text );
2980 $this->mTplExpandCache[$titleText] = $text;
2981 }
2982 } else {
2983 # Uncached expansion
2984 $text = $newFrame->expand( $text );
2985 }
2986 }
2987 if ( $isLocalObj && $nowiki ) {
2988 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
2989 $isLocalObj = false;
2990 }
2991
2992 # Replace raw HTML by a placeholder
2993 # Add a blank line preceding, to prevent it from mucking up
2994 # immediately preceding headings
2995 if ( $isHTML ) {
2996 $text = "\n\n" . $this->insertStripItem( $text );
2997 }
2998 # Escape nowiki-style return values
2999 elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3000 $text = wfEscapeWikiText( $text );
3001 }
3002 # Bug 529: if the template begins with a table or block-level
3003 # element, it should be treated as beginning a new line.
3004 # This behaviour is somewhat controversial.
3005 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3006 $text = "\n" . $text;
3007 }
3008
3009 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3010 # Error, oversize inclusion
3011 $text = "[[$originalTitle]]" .
3012 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3013 $this->limitationWarn( 'post-expand-template-inclusion' );
3014 }
3015
3016 if ( $isLocalObj ) {
3017 $ret = array( 'object' => $text );
3018 } else {
3019 $ret = array( 'text' => $text );
3020 }
3021
3022 wfProfileOut( $fname );
3023 return $ret;
3024 }
3025
3026 /**
3027 * Get the semi-parsed DOM representation of a template with a given title,
3028 * and its redirect destination title. Cached.
3029 */
3030 function getTemplateDom( $title ) {
3031 $cacheTitle = $title;
3032 $titleText = $title->getPrefixedDBkey();
3033
3034 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3035 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3036 $title = Title::makeTitle( $ns, $dbk );
3037 $titleText = $title->getPrefixedDBkey();
3038 }
3039 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3040 return array( $this->mTplDomCache[$titleText], $title );
3041 }
3042
3043 // Cache miss, go to the database
3044 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3045
3046 if ( $text === false ) {
3047 $this->mTplDomCache[$titleText] = false;
3048 return array( false, $title );
3049 }
3050
3051 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3052 $this->mTplDomCache[ $titleText ] = $dom;
3053
3054 if (! $title->equals($cacheTitle)) {
3055 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3056 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3057 }
3058
3059 return array( $dom, $title );
3060 }
3061
3062 /**
3063 * Fetch the unparsed text of a template and register a reference to it.
3064 */
3065 function fetchTemplateAndTitle( $title ) {
3066 $templateCb = $this->mOptions->getTemplateCallback();
3067 $stuff = call_user_func( $templateCb, $title, $this );
3068 $text = $stuff['text'];
3069 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3070 if ( isset( $stuff['deps'] ) ) {
3071 foreach ( $stuff['deps'] as $dep ) {
3072 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3073 }
3074 }
3075 return array($text,$finalTitle);
3076 }
3077
3078 function fetchTemplate( $title ) {
3079 $rv = $this->fetchTemplateAndTitle($title);
3080 return $rv[0];
3081 }
3082
3083 /**
3084 * Static function to get a template
3085 * Can be overridden via ParserOptions::setTemplateCallback().
3086 */
3087 static function statelessFetchTemplate( $title, $parser=false ) {
3088 $text = $skip = false;
3089 $finalTitle = $title;
3090 $deps = array();
3091
3092 // Loop to fetch the article, with up to 1 redirect
3093 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3094 # Give extensions a chance to select the revision instead
3095 $id = false; // Assume current
3096 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3097
3098 if( $skip ) {
3099 $text = false;
3100 $deps[] = array(
3101 'title' => $title,
3102 'page_id' => $title->getArticleID(),
3103 'rev_id' => null );
3104 break;
3105 }
3106 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3107 $rev_id = $rev ? $rev->getId() : 0;
3108 // If there is no current revision, there is no page
3109 if( $id === false && !$rev ) {
3110 $linkCache = LinkCache::singleton();
3111 $linkCache->addBadLinkObj( $title );
3112 }
3113
3114 $deps[] = array(
3115 'title' => $title,
3116 'page_id' => $title->getArticleID(),
3117 'rev_id' => $rev_id );
3118
3119 if( $rev ) {
3120 $text = $rev->getText();
3121 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3122 global $wgLang;
3123 $message = $wgLang->lcfirst( $title->getText() );
3124 $text = wfMsgForContentNoTrans( $message );
3125 if( wfEmptyMsg( $message, $text ) ) {
3126 $text = false;
3127 break;
3128 }
3129 } else {
3130 break;
3131 }
3132 if ( $text === false ) {
3133 break;
3134 }
3135 // Redirect?
3136 $finalTitle = $title;
3137 $title = Title::newFromRedirect( $text );
3138 }
3139 return array(
3140 'text' => $text,
3141 'finalTitle' => $finalTitle,
3142 'deps' => $deps );
3143 }
3144
3145 /**
3146 * Transclude an interwiki link.
3147 */
3148 function interwikiTransclude( $title, $action ) {
3149 global $wgEnableScaryTranscluding;
3150
3151 if (!$wgEnableScaryTranscluding)
3152 return wfMsg('scarytranscludedisabled');
3153
3154 $url = $title->getFullUrl( "action=$action" );
3155
3156 if (strlen($url) > 255)
3157 return wfMsg('scarytranscludetoolong');
3158 return $this->fetchScaryTemplateMaybeFromCache($url);
3159 }
3160
3161 function fetchScaryTemplateMaybeFromCache($url) {
3162 global $wgTranscludeCacheExpiry;
3163 $dbr = wfGetDB(DB_SLAVE);
3164 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3165 array('tc_url' => $url));
3166 if ($obj) {
3167 $time = $obj->tc_time;
3168 $text = $obj->tc_contents;
3169 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3170 return $text;
3171 }
3172 }
3173
3174 $text = Http::get($url);
3175 if (!$text)
3176 return wfMsg('scarytranscludefailed', $url);
3177
3178 $dbw = wfGetDB(DB_MASTER);
3179 $dbw->replace('transcache', array('tc_url'), array(
3180 'tc_url' => $url,
3181 'tc_time' => time(),
3182 'tc_contents' => $text));
3183 return $text;
3184 }
3185
3186
3187 /**
3188 * Triple brace replacement -- used for template arguments
3189 * @private
3190 */
3191 function argSubstitution( $piece, $frame ) {
3192 wfProfileIn( __METHOD__ );
3193
3194 $error = false;
3195 $parts = $piece['parts'];
3196 $nameWithSpaces = $frame->expand( $piece['title'] );
3197 $argName = trim( $nameWithSpaces );
3198 $object = false;
3199 $text = $frame->getArgument( $argName );
3200 if ( $text === false && $parts->getLength() > 0
3201 && (
3202 $this->ot['html']
3203 || $this->ot['pre']
3204 || ( $this->ot['wiki'] && $frame->isTemplate() )
3205 )
3206 ) {
3207 # No match in frame, use the supplied default
3208 $object = $parts->item( 0 )->getChildren();
3209 }
3210 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3211 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3212 $this->limitationWarn( 'post-expand-template-argument' );
3213 }
3214
3215 if ( $text === false && $object === false ) {
3216 # No match anywhere
3217 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3218 }
3219 if ( $error !== false ) {
3220 $text .= $error;
3221 }
3222 if ( $object !== false ) {
3223 $ret = array( 'object' => $object );
3224 } else {
3225 $ret = array( 'text' => $text );
3226 }
3227
3228 wfProfileOut( __METHOD__ );
3229 return $ret;
3230 }
3231
3232 /**
3233 * Return the text to be used for a given extension tag.
3234 * This is the ghost of strip().
3235 *
3236 * @param array $params Associative array of parameters:
3237 * name PPNode for the tag name
3238 * attr PPNode for unparsed text where tag attributes are thought to be
3239 * attributes Optional associative array of parsed attributes
3240 * inner Contents of extension element
3241 * noClose Original text did not have a close tag
3242 * @param PPFrame $frame
3243 */
3244 function extensionSubstitution( $params, $frame ) {
3245 global $wgRawHtml, $wgContLang;
3246
3247 $name = $frame->expand( $params['name'] );
3248 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3249 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3250
3251 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++) . self::MARKER_SUFFIX;
3252
3253 if ( $this->ot['html'] ) {
3254 $name = strtolower( $name );
3255
3256 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3257 if ( isset( $params['attributes'] ) ) {
3258 $attributes = $attributes + $params['attributes'];
3259 }
3260 switch ( $name ) {
3261 case 'html':
3262 if( $wgRawHtml ) {
3263 $output = $content;
3264 break;
3265 } else {
3266 throw new MWException( '<html> extension tag encountered unexpectedly' );
3267 }
3268 case 'nowiki':
3269 $output = Xml::escapeTagsOnly( $content );
3270 break;
3271 case 'math':
3272 $output = $wgContLang->armourMath(
3273 MathRenderer::renderMath( $content, $attributes ) );
3274 break;
3275 case 'gallery':
3276 $output = $this->renderImageGallery( $content, $attributes );
3277 break;
3278 default:
3279 if( isset( $this->mTagHooks[$name] ) ) {
3280 # Workaround for PHP bug 35229 and similar
3281 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3282 throw new MWException( "Tag hook for $name is not callable\n" );
3283 }
3284 $output = call_user_func_array( $this->mTagHooks[$name],
3285 array( $content, $attributes, $this ) );
3286 } else {
3287 $output = '<span class="error">Invalid tag extension name: ' .
3288 htmlspecialchars( $name ) . '</span>';
3289 }
3290 }
3291 } else {
3292 if ( is_null( $attrText ) ) {
3293 $attrText = '';
3294 }
3295 if ( isset( $params['attributes'] ) ) {
3296 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3297 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3298 htmlspecialchars( $attrValue ) . '"';
3299 }
3300 }
3301 if ( $content === null ) {
3302 $output = "<$name$attrText/>";
3303 } else {
3304 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3305 $output = "<$name$attrText>$content$close";
3306 }
3307 }
3308
3309 if ( $name == 'html' || $name == 'nowiki' ) {
3310 $this->mStripState->nowiki->setPair( $marker, $output );
3311 } else {
3312 $this->mStripState->general->setPair( $marker, $output );
3313 }
3314 return $marker;
3315 }
3316
3317 /**
3318 * Increment an include size counter
3319 *
3320 * @param string $type The type of expansion
3321 * @param integer $size The size of the text
3322 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3323 */
3324 function incrementIncludeSize( $type, $size ) {
3325 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3326 return false;
3327 } else {
3328 $this->mIncludeSizes[$type] += $size;
3329 return true;
3330 }
3331 }
3332
3333 /**
3334 * Increment the expensive function count
3335 *
3336 * @return boolean False if the limit has been exceeded
3337 */
3338 function incrementExpensiveFunctionCount() {
3339 global $wgExpensiveParserFunctionLimit;
3340 $this->mExpensiveFunctionCount++;
3341 if($this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit) {
3342 return true;
3343 }
3344 return false;
3345 }
3346
3347 /**
3348 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3349 * Fills $this->mDoubleUnderscores, returns the modified text
3350 */
3351 function doDoubleUnderscore( $text ) {
3352 // The position of __TOC__ needs to be recorded
3353 $mw = MagicWord::get( 'toc' );
3354 if( $mw->match( $text ) ) {
3355 $this->mShowToc = true;
3356 $this->mForceTocPosition = true;
3357
3358 // Set a placeholder. At the end we'll fill it in with the TOC.
3359 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3360
3361 // Only keep the first one.
3362 $text = $mw->replace( '', $text );
3363 }
3364
3365 // Now match and remove the rest of them
3366 $mwa = MagicWord::getDoubleUnderscoreArray();
3367 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3368
3369 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3370 $this->mOutput->mNoGallery = true;
3371 }
3372 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3373 $this->mShowToc = false;
3374 }
3375 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3376 $this->mOutput->setProperty( 'hiddencat', 'y' );
3377
3378 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( 'hidden-category-category' ) );
3379 if ( $containerCategory ) {
3380 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3381 } else {
3382 wfDebug( __METHOD__.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3383 }
3384 }
3385 # (bug 8068) Allow control over whether robots index a page.
3386 #
3387 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3388 # is not desirable, the last one on the page should win.
3389 if( isset( $this->mDoubleUnderscores['noindex'] ) ) {
3390 $this->mOutput->setIndexPolicy( 'noindex' );
3391 } elseif( isset( $this->mDoubleUnderscores['index'] ) ) {
3392 $this->mOutput->setIndexPolicy( 'index' );
3393 }
3394
3395 return $text;
3396 }
3397
3398 /**
3399 * This function accomplishes several tasks:
3400 * 1) Auto-number headings if that option is enabled
3401 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3402 * 3) Add a Table of contents on the top for users who have enabled the option
3403 * 4) Auto-anchor headings
3404 *
3405 * It loops through all headlines, collects the necessary data, then splits up the
3406 * string and re-inserts the newly formatted headlines.
3407 *
3408 * @param string $text
3409 * @param boolean $isMain
3410 * @private
3411 */
3412 function formatHeadings( $text, $isMain=true ) {
3413 global $wgMaxTocLevel, $wgContLang;
3414
3415 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3416 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3417 $showEditLink = 0;
3418 } else {
3419 $showEditLink = $this->mOptions->getEditSection();
3420 }
3421
3422 # Inhibit editsection links if requested in the page
3423 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3424 $showEditLink = 0;
3425 }
3426
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 );
3431
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);
3436
3437 # Allow user to stipulate that a page should have a "new section"
3438 # link added via __NEWSECTIONLINK__
3439 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3440 $this->mOutput->setNewSection( true );
3441 }
3442
3443 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3444 # override above conditions and always show TOC above first header
3445 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3446 $this->mShowToc = true;
3447 $enoughToc = true;
3448 }
3449
3450 # We need this to perform operations on the HTML
3451 $sk = $this->mOptions->getSkin();
3452
3453 # headline counter
3454 $headlineCount = 0;
3455 $numVisible = 0;
3456
3457 # Ugh .. the TOC should have neat indentation levels which can be
3458 # passed to the skin functions. These are determined here
3459 $toc = '';
3460 $full = '';
3461 $head = array();
3462 $sublevelCount = array();
3463 $levelCount = array();
3464 $toclevel = 0;
3465 $level = 0;
3466 $prevlevel = 0;
3467 $toclevel = 0;
3468 $prevtoclevel = 0;
3469 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3470 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3471 $tocraw = array();
3472
3473 foreach( $matches[3] as $headline ) {
3474 $isTemplate = false;
3475 $titleText = false;
3476 $sectionIndex = false;
3477 $numbering = '';
3478 $markerMatches = array();
3479 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3480 $serial = $markerMatches[1];
3481 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3482 $isTemplate = ($titleText != $baseTitleText);
3483 $headline = preg_replace("/^$markerRegex/", "", $headline);
3484 }
3485
3486 if( $toclevel ) {
3487 $prevlevel = $level;
3488 $prevtoclevel = $toclevel;
3489 }
3490 $level = $matches[1][$headlineCount];
3491
3492 if( $doNumberHeadings || $enoughToc ) {
3493
3494 if ( $level > $prevlevel ) {
3495 # Increase TOC level
3496 $toclevel++;
3497 $sublevelCount[$toclevel] = 0;
3498 if( $toclevel<$wgMaxTocLevel ) {
3499 $prevtoclevel = $toclevel;
3500 $toc .= $sk->tocIndent();
3501 $numVisible++;
3502 }
3503 }
3504 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3505 # Decrease TOC level, find level to jump to
3506
3507 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3508 # Can only go down to level 1
3509 $toclevel = 1;
3510 } else {
3511 for ($i = $toclevel; $i > 0; $i--) {
3512 if ( $levelCount[$i] == $level ) {
3513 # Found last matching level
3514 $toclevel = $i;
3515 break;
3516 }
3517 elseif ( $levelCount[$i] < $level ) {
3518 # Found first matching level below current level
3519 $toclevel = $i + 1;
3520 break;
3521 }
3522 }
3523 }
3524 if( $toclevel<$wgMaxTocLevel ) {
3525 if($prevtoclevel < $wgMaxTocLevel) {
3526 # Unindent only if the previous toc level was shown :p
3527 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3528 $prevtoclevel = $toclevel;
3529 } else {
3530 $toc .= $sk->tocLineEnd();
3531 }
3532 }
3533 }
3534 else {
3535 # No change in level, end TOC line
3536 if( $toclevel<$wgMaxTocLevel ) {
3537 $toc .= $sk->tocLineEnd();
3538 }
3539 }
3540
3541 $levelCount[$toclevel] = $level;
3542
3543 # count number of headlines for each level
3544 @$sublevelCount[$toclevel]++;
3545 $dot = 0;
3546 for( $i = 1; $i <= $toclevel; $i++ ) {
3547 if( !empty( $sublevelCount[$i] ) ) {
3548 if( $dot ) {
3549 $numbering .= '.';
3550 }
3551 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3552 $dot = 1;
3553 }
3554 }
3555 }
3556
3557 # The safe header is a version of the header text safe to use for links
3558 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3559 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3560
3561 # Remove link placeholders by the link text.
3562 # <!--LINK number-->
3563 # turns into
3564 # link text with suffix
3565 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3566 "\$this->mLinkHolders['texts'][\$1]",
3567 $safeHeadline );
3568 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3569 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3570 $safeHeadline );
3571
3572 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3573 $tocline = preg_replace(
3574 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3575 array( '', '<$1>'),
3576 $safeHeadline
3577 );
3578 $tocline = trim( $tocline );
3579
3580 # For the anchor, strip out HTML-y stuff period
3581 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3582 $safeHeadline = trim( $safeHeadline );
3583
3584 # Save headline for section edit hint before it's escaped
3585 $headlineHint = $safeHeadline;
3586 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3587 # HTML names must be case-insensitively unique (bug 10721)
3588 $arrayKey = strtolower( $safeHeadline );
3589
3590 # count how many in assoc. array so we can track dupes in anchors
3591 isset( $refers[$arrayKey] ) ? $refers[$arrayKey]++ : $refers[$arrayKey] = 1;
3592 $refcount[$headlineCount] = $refers[$arrayKey];
3593
3594 # Don't number the heading if it is the only one (looks silly)
3595 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3596 # the two are different if the line contains a link
3597 $headline=$numbering . ' ' . $headline;
3598 }
3599
3600 # Create the anchor for linking from the TOC to the section
3601 $anchor = $safeHeadline;
3602 if($refcount[$headlineCount] > 1 ) {
3603 $anchor .= '_' . $refcount[$headlineCount];
3604 }
3605 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3606 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3607 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3608 }
3609 # give headline the correct <h#> tag
3610 if( $showEditLink && $sectionIndex !== false ) {
3611 if( $isTemplate ) {
3612 # Put a T flag in the section identifier, to indicate to extractSections()
3613 # that sections inside <includeonly> should be counted.
3614 $editlink = $sk->doEditSectionLink(Title::newFromText( $titleText ), "T-$sectionIndex");
3615 } else {
3616 $editlink = $sk->doEditSectionLink($this->mTitle, $sectionIndex, $headlineHint);
3617 }
3618 } else {
3619 $editlink = '';
3620 }
3621 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3622
3623 $headlineCount++;
3624 }
3625
3626 $this->mOutput->setSections( $tocraw );
3627
3628 # Never ever show TOC if no headers
3629 if( $numVisible < 1 ) {
3630 $enoughToc = false;
3631 }
3632
3633 if( $enoughToc ) {
3634 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3635 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3636 }
3637 $toc = $sk->tocList( $toc );
3638 }
3639
3640 # split up and insert constructed headlines
3641
3642 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3643 $i = 0;
3644
3645 foreach( $blocks as $block ) {
3646 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3647 # This is the [edit] link that appears for the top block of text when
3648 # section editing is enabled
3649
3650 # Disabled because it broke block formatting
3651 # For example, a bullet point in the top line
3652 # $full .= $sk->editSectionLink(0);
3653 }
3654 $full .= $block;
3655 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3656 # Top anchor now in skin
3657 $full = $full.$toc;
3658 }
3659
3660 if( !empty( $head[$i] ) ) {
3661 $full .= $head[$i];
3662 }
3663 $i++;
3664 }
3665 if( $this->mForceTocPosition ) {
3666 return str_replace( '<!--MWTOC-->', $toc, $full );
3667 } else {
3668 return $full;
3669 }
3670 }
3671
3672 /**
3673 * Transform wiki markup when saving a page by doing \r\n -> \n
3674 * conversion, substitting signatures, {{subst:}} templates, etc.
3675 *
3676 * @param string $text the text to transform
3677 * @param Title &$title the Title object for the current article
3678 * @param User &$user the User object describing the current user
3679 * @param ParserOptions $options parsing options
3680 * @param bool $clearState whether to clear the parser state first
3681 * @return string the altered wiki markup
3682 * @public
3683 */
3684 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3685 $this->mOptions = $options;
3686 $this->setTitle( $title );
3687 $this->setOutputType( self::OT_WIKI );
3688
3689 if ( $clearState ) {
3690 $this->clearState();
3691 }
3692
3693 $pairs = array(
3694 "\r\n" => "\n",
3695 );
3696 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3697 $text = $this->pstPass2( $text, $user );
3698 $text = $this->mStripState->unstripBoth( $text );
3699 return $text;
3700 }
3701
3702 /**
3703 * Pre-save transform helper function
3704 * @private
3705 */
3706 function pstPass2( $text, $user ) {
3707 global $wgContLang, $wgLocaltimezone;
3708
3709 /* Note: This is the timestamp saved as hardcoded wikitext to
3710 * the database, we use $wgContLang here in order to give
3711 * everyone the same signature and use the default one rather
3712 * than the one selected in each user's preferences.
3713 *
3714 * (see also bug 12815)
3715 */
3716 $ts = $this->mOptions->getTimestamp();
3717 $tz = wfMsgForContent( 'timezone-utc' );
3718 if ( isset( $wgLocaltimezone ) ) {
3719 $unixts = wfTimestamp( TS_UNIX, $ts );
3720 $oldtz = getenv( 'TZ' );
3721 putenv( 'TZ='.$wgLocaltimezone );
3722 $ts = date( 'YmdHis', $unixts );
3723 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3724 putenv( 'TZ='.$oldtz );
3725 }
3726
3727 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3728
3729 # Variable replacement
3730 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3731 $text = $this->replaceVariables( $text );
3732
3733 # Signatures
3734 $sigText = $this->getUserSig( $user );
3735 $text = strtr( $text, array(
3736 '~~~~~' => $d,
3737 '~~~~' => "$sigText $d",
3738 '~~~' => $sigText
3739 ) );
3740
3741 # Context links: [[|name]] and [[name (context)|]]
3742 #
3743 global $wgLegalTitleChars;
3744 $tc = "[$wgLegalTitleChars]";
3745 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3746
3747 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3748 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3749 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3750
3751 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3752 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3753 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3754
3755 $t = $this->mTitle->getText();
3756 $m = array();
3757 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3758 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3759 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3760 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3761 } else {
3762 # if there's no context, don't bother duplicating the title
3763 $text = preg_replace( $p2, '[[\\1]]', $text );
3764 }
3765
3766 # Trim trailing whitespace
3767 $text = rtrim( $text );
3768
3769 return $text;
3770 }
3771
3772 /**
3773 * Fetch the user's signature text, if any, and normalize to
3774 * validated, ready-to-insert wikitext.
3775 *
3776 * @param User $user
3777 * @return string
3778 * @private
3779 */
3780 function getUserSig( &$user ) {
3781 global $wgMaxSigChars;
3782
3783 $username = $user->getName();
3784 $nickname = $user->getOption( 'nickname' );
3785 $nickname = $nickname === '' ? $username : $nickname;
3786
3787 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3788 $nickname = $username;
3789 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
3790 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3791 # Sig. might contain markup; validate this
3792 if( $this->validateSig( $nickname ) !== false ) {
3793 # Validated; clean up (if needed) and return it
3794 return $this->cleanSig( $nickname, true );
3795 } else {
3796 # Failed to validate; fall back to the default
3797 $nickname = $username;
3798 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3799 }
3800 }
3801
3802 // Make sure nickname doesnt get a sig in a sig
3803 $nickname = $this->cleanSigInSig( $nickname );
3804
3805 # If we're still here, make it a link to the user page
3806 $userText = wfEscapeWikiText( $username );
3807 $nickText = wfEscapeWikiText( $nickname );
3808 if ( $user->isAnon() ) {
3809 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3810 } else {
3811 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3812 }
3813 }
3814
3815 /**
3816 * Check that the user's signature contains no bad XML
3817 *
3818 * @param string $text
3819 * @return mixed An expanded string, or false if invalid.
3820 */
3821 function validateSig( $text ) {
3822 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3823 }
3824
3825 /**
3826 * Clean up signature text
3827 *
3828 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3829 * 2) Substitute all transclusions
3830 *
3831 * @param string $text
3832 * @param $parsing Whether we're cleaning (preferences save) or parsing
3833 * @return string Signature text
3834 */
3835 function cleanSig( $text, $parsing = false ) {
3836 if ( !$parsing ) {
3837 global $wgTitle;
3838 $this->clearState();
3839 $this->setTitle( $wgTitle );
3840 $this->mOptions = new ParserOptions;
3841 $this->setOutputType = self::OT_PREPROCESS;
3842 }
3843
3844 # Option to disable this feature
3845 if ( !$this->mOptions->getCleanSignatures() ) {
3846 return $text;
3847 }
3848
3849 # FIXME: regex doesn't respect extension tags or nowiki
3850 # => Move this logic to braceSubstitution()
3851 $substWord = MagicWord::get( 'subst' );
3852 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3853 $substText = '{{' . $substWord->getSynonym( 0 );
3854
3855 $text = preg_replace( $substRegex, $substText, $text );
3856 $text = $this->cleanSigInSig( $text );
3857 $dom = $this->preprocessToDom( $text );
3858 $frame = $this->getPreprocessor()->newFrame();
3859 $text = $frame->expand( $dom );
3860
3861 if ( !$parsing ) {
3862 $text = $this->mStripState->unstripBoth( $text );
3863 }
3864
3865 return $text;
3866 }
3867
3868 /**
3869 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3870 * @param string $text
3871 * @return string Signature text with /~{3,5}/ removed
3872 */
3873 function cleanSigInSig( $text ) {
3874 $text = preg_replace( '/~{3,5}/', '', $text );
3875 return $text;
3876 }
3877
3878 /**
3879 * Set up some variables which are usually set up in parse()
3880 * so that an external function can call some class members with confidence
3881 * @public
3882 */
3883 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3884 $this->setTitle( $title );
3885 $this->mOptions = $options;
3886 $this->setOutputType( $outputType );
3887 if ( $clearState ) {
3888 $this->clearState();
3889 }
3890 }
3891
3892 /**
3893 * Wrapper for preprocess()
3894 *
3895 * @param string $text the text to preprocess
3896 * @param ParserOptions $options options
3897 * @return string
3898 * @public
3899 */
3900 function transformMsg( $text, $options ) {
3901 global $wgTitle;
3902 static $executing = false;
3903
3904 $fname = "Parser::transformMsg";
3905
3906 # Guard against infinite recursion
3907 if ( $executing ) {
3908 return $text;
3909 }
3910 $executing = true;
3911
3912 wfProfileIn($fname);
3913 $text = $this->preprocess( $text, $wgTitle, $options );
3914
3915 $executing = false;
3916 wfProfileOut($fname);
3917 return $text;
3918 }
3919
3920 /**
3921 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3922 * The callback should have the following form:
3923 * function myParserHook( $text, $params, &$parser ) { ... }
3924 *
3925 * Transform and return $text. Use $parser for any required context, e.g. use
3926 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3927 *
3928 * @public
3929 *
3930 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3931 * @param mixed $callback The callback function (and object) to use for the tag
3932 *
3933 * @return The old value of the mTagHooks array associated with the hook
3934 */
3935 function setHook( $tag, $callback ) {
3936 $tag = strtolower( $tag );
3937 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
3938 $this->mTagHooks[$tag] = $callback;
3939 if( !in_array( $tag, $this->mStripList ) ) {
3940 $this->mStripList[] = $tag;
3941 }
3942
3943 return $oldVal;
3944 }
3945
3946 function setTransparentTagHook( $tag, $callback ) {
3947 $tag = strtolower( $tag );
3948 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
3949 $this->mTransparentTagHooks[$tag] = $callback;
3950
3951 return $oldVal;
3952 }
3953
3954 /**
3955 * Remove all tag hooks
3956 */
3957 function clearTagHooks() {
3958 $this->mTagHooks = array();
3959 $this->mStripList = $this->mDefaultStripList;
3960 }
3961
3962 /**
3963 * Create a function, e.g. {{sum:1|2|3}}
3964 * The callback function should have the form:
3965 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3966 *
3967 * Or with SFH_OBJECT_ARGS:
3968 * function myParserFunction( $parser, $frame, $args ) { ... }
3969 *
3970 * The callback may either return the text result of the function, or an array with the text
3971 * in element 0, and a number of flags in the other elements. The names of the flags are
3972 * specified in the keys. Valid flags are:
3973 * found The text returned is valid, stop processing the template. This
3974 * is on by default.
3975 * nowiki Wiki markup in the return value should be escaped
3976 * isHTML The returned text is HTML, armour it against wikitext transformation
3977 *
3978 * @public
3979 *
3980 * @param string $id The magic word ID
3981 * @param mixed $callback The callback function (and object) to use
3982 * @param integer $flags a combination of the following flags:
3983 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3984 *
3985 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
3986 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
3987 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
3988 * the arguments, and to control the way they are expanded.
3989 *
3990 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
3991 * arguments, for instance:
3992 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
3993 *
3994 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
3995 * future versions. Please call $frame->expand() on it anyway so that your code keeps
3996 * working if/when this is changed.
3997 *
3998 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
3999 * expansion.
4000 *
4001 * Please read the documentation in includes/parser/Preprocessor.php for more information
4002 * about the methods available in PPFrame and PPNode.
4003 *
4004 * @return The old callback function for this name, if any
4005 */
4006 function setFunctionHook( $id, $callback, $flags = 0 ) {
4007 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4008 $this->mFunctionHooks[$id] = array( $callback, $flags );
4009
4010 # Add to function cache
4011 $mw = MagicWord::get( $id );
4012 if( !$mw )
4013 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4014
4015 $synonyms = $mw->getSynonyms();
4016 $sensitive = intval( $mw->isCaseSensitive() );
4017
4018 foreach ( $synonyms as $syn ) {
4019 # Case
4020 if ( !$sensitive ) {
4021 $syn = strtolower( $syn );
4022 }
4023 # Add leading hash
4024 if ( !( $flags & SFH_NO_HASH ) ) {
4025 $syn = '#' . $syn;
4026 }
4027 # Remove trailing colon
4028 if ( substr( $syn, -1, 1 ) == ':' ) {
4029 $syn = substr( $syn, 0, -1 );
4030 }
4031 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4032 }
4033 return $oldVal;
4034 }
4035
4036 /**
4037 * Get all registered function hook identifiers
4038 *
4039 * @return array
4040 */
4041 function getFunctionHooks() {
4042 return array_keys( $this->mFunctionHooks );
4043 }
4044
4045 /**
4046 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4047 * Placeholders created in Skin::makeLinkObj()
4048 * Returns an array of link CSS classes, indexed by PDBK.
4049 * $options is a bit field, RLH_FOR_UPDATE to select for update
4050 */
4051 function replaceLinkHolders( &$text, $options = 0 ) {
4052 global $wgUser;
4053 global $wgContLang;
4054
4055 $fname = 'Parser::replaceLinkHolders';
4056 wfProfileIn( $fname );
4057
4058 $pdbks = array();
4059 $colours = array();
4060 $linkcolour_ids = array();
4061 $sk = $this->mOptions->getSkin();
4062 $linkCache = LinkCache::singleton();
4063
4064 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
4065 wfProfileIn( $fname.'-check' );
4066 $dbr = wfGetDB( DB_SLAVE );
4067 $page = $dbr->tableName( 'page' );
4068 $threshold = $wgUser->getOption('stubthreshold');
4069
4070 # Sort by namespace
4071 asort( $this->mLinkHolders['namespaces'] );
4072
4073 # Generate query
4074 $query = false;
4075 $current = null;
4076 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4077 # Make title object
4078 $title = $this->mLinkHolders['titles'][$key];
4079
4080 # Skip invalid entries.
4081 # Result will be ugly, but prevents crash.
4082 if ( is_null( $title ) ) {
4083 continue;
4084 }
4085 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4086
4087 # Check if it's a static known link, e.g. interwiki
4088 if ( $title->isAlwaysKnown() ) {
4089 $colours[$pdbk] = '';
4090 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4091 $colours[$pdbk] = '';
4092 $this->mOutput->addLink( $title, $id );
4093 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4094 $colours[$pdbk] = 'new';
4095 } elseif ( $title->getNamespace() == NS_SPECIAL && !SpecialPage::exists( $pdbk ) ) {
4096 $colours[$pdbk] = 'new';
4097 } else {
4098 # Not in the link cache, add it to the query
4099 if ( !isset( $current ) ) {
4100 $current = $ns;
4101 $query = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
4102 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4103 } elseif ( $current != $ns ) {
4104 $current = $ns;
4105 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4106 } else {
4107 $query .= ', ';
4108 }
4109
4110 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
4111 }
4112 }
4113 if ( $query ) {
4114 $query .= '))';
4115 if ( $options & RLH_FOR_UPDATE ) {
4116 $query .= ' FOR UPDATE';
4117 }
4118
4119 $res = $dbr->query( $query, $fname );
4120
4121 # Fetch data and form into an associative array
4122 # non-existent = broken
4123 while ( $s = $dbr->fetchObject($res) ) {
4124 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
4125 $pdbk = $title->getPrefixedDBkey();
4126 $linkCache->addGoodLinkObj( $s->page_id, $title, $s->page_len, $s->page_is_redirect );
4127 $this->mOutput->addLink( $title, $s->page_id );
4128 $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
4129 //add id to the extension todolist
4130 $linkcolour_ids[$s->page_id] = $pdbk;
4131 }
4132 //pass an array of page_ids to an extension
4133 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4134 }
4135 wfProfileOut( $fname.'-check' );
4136
4137 # Do a second query for different language variants of links and categories
4138 if($wgContLang->hasVariants()){
4139 $linkBatch = new LinkBatch();
4140 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4141 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4142 $varCategories = array(); // category replacements oldDBkey => newDBkey
4143
4144 $categories = $this->mOutput->getCategoryLinks();
4145
4146 // Add variants of links to link batch
4147 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4148 $title = $this->mLinkHolders['titles'][$key];
4149 if ( is_null( $title ) )
4150 continue;
4151
4152 $pdbk = $title->getPrefixedDBkey();
4153 $titleText = $title->getText();
4154
4155 // generate all variants of the link title text
4156 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4157
4158 // if link was not found (in first query), add all variants to query
4159 if ( !isset($colours[$pdbk]) ){
4160 foreach($allTextVariants as $textVariant){
4161 if($textVariant != $titleText){
4162 $variantTitle = Title::makeTitle( $ns, $textVariant );
4163 if(is_null($variantTitle)) continue;
4164 $linkBatch->addObj( $variantTitle );
4165 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4166 }
4167 }
4168 }
4169 }
4170
4171 // process categories, check if a category exists in some variant
4172 foreach( $categories as $category ){
4173 $variants = $wgContLang->convertLinkToAllVariants($category);
4174 foreach($variants as $variant){
4175 if($variant != $category){
4176 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
4177 if(is_null($variantTitle)) continue;
4178 $linkBatch->addObj( $variantTitle );
4179 $categoryMap[$variant] = $category;
4180 }
4181 }
4182 }
4183
4184
4185 if(!$linkBatch->isEmpty()){
4186 // construct query
4187 $titleClause = $linkBatch->constructSet('page', $dbr);
4188
4189 $variantQuery = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
4190
4191 $variantQuery .= " FROM $page WHERE $titleClause";
4192 if ( $options & RLH_FOR_UPDATE ) {
4193 $variantQuery .= ' FOR UPDATE';
4194 }
4195
4196 $varRes = $dbr->query( $variantQuery, $fname );
4197
4198 // for each found variants, figure out link holders and replace
4199 while ( $s = $dbr->fetchObject($varRes) ) {
4200
4201 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4202 $varPdbk = $variantTitle->getPrefixedDBkey();
4203 $vardbk = $variantTitle->getDBkey();
4204
4205 $holderKeys = array();
4206 if(isset($variantMap[$varPdbk])){
4207 $holderKeys = $variantMap[$varPdbk];
4208 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle, $s->page_len, $s->page_is_redirect );
4209 $this->mOutput->addLink( $variantTitle, $s->page_id );
4210 }
4211
4212 // loop over link holders
4213 foreach($holderKeys as $key){
4214 $title = $this->mLinkHolders['titles'][$key];
4215 if ( is_null( $title ) ) continue;
4216
4217 $pdbk = $title->getPrefixedDBkey();
4218
4219 if(!isset($colours[$pdbk])){
4220 // found link in some of the variants, replace the link holder data
4221 $this->mLinkHolders['titles'][$key] = $variantTitle;
4222 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4223
4224 // set pdbk and colour
4225 $pdbks[$key] = $varPdbk;
4226 $colours[$varPdbk] = $sk->getLinkColour( $variantTitle, $threshold );
4227 $linkcolour_ids[$s->page_id] = $pdbk;
4228 }
4229 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4230 }
4231
4232 // check if the object is a variant of a category
4233 if(isset($categoryMap[$vardbk])){
4234 $oldkey = $categoryMap[$vardbk];
4235 if($oldkey != $vardbk)
4236 $varCategories[$oldkey]=$vardbk;
4237 }
4238 }
4239
4240 // rebuild the categories in original order (if there are replacements)
4241 if(count($varCategories)>0){
4242 $newCats = array();
4243 $originalCats = $this->mOutput->getCategories();
4244 foreach($originalCats as $cat => $sortkey){
4245 // make the replacement
4246 if( array_key_exists($cat,$varCategories) )
4247 $newCats[$varCategories[$cat]] = $sortkey;
4248 else $newCats[$cat] = $sortkey;
4249 }
4250 $this->mOutput->setCategoryLinks($newCats);
4251 }
4252 }
4253 }
4254
4255 # Construct search and replace arrays
4256 wfProfileIn( $fname.'-construct' );
4257 $replacePairs = array();
4258 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4259 $pdbk = $pdbks[$key];
4260 $searchkey = "<!--LINK $key-->";
4261 $title = $this->mLinkHolders['titles'][$key];
4262 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] == 'new' ) {
4263 $linkCache->addBadLinkObj( $title );
4264 $colours[$pdbk] = 'new';
4265 $this->mOutput->addLink( $title, 0 );
4266 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4267 $this->mLinkHolders['texts'][$key],
4268 $this->mLinkHolders['queries'][$key] );
4269 } else {
4270 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4271 $this->mLinkHolders['texts'][$key],
4272 $this->mLinkHolders['queries'][$key] );
4273 }
4274 }
4275 $replacer = new HashtableReplacer( $replacePairs, 1 );
4276 wfProfileOut( $fname.'-construct' );
4277
4278 # Do the thing
4279 wfProfileIn( $fname.'-replace' );
4280 $text = preg_replace_callback(
4281 '/(<!--LINK .*?-->)/',
4282 $replacer->cb(),
4283 $text);
4284
4285 wfProfileOut( $fname.'-replace' );
4286 }
4287
4288 # Now process interwiki link holders
4289 # This is quite a bit simpler than internal links
4290 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4291 wfProfileIn( $fname.'-interwiki' );
4292 # Make interwiki link HTML
4293 $replacePairs = array();
4294 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4295 $title = $this->mInterwikiLinkHolders['titles'][$key];
4296 $replacePairs[$key] = $sk->link( $title, $link );
4297 }
4298 $replacer = new HashtableReplacer( $replacePairs, 1 );
4299
4300 $text = preg_replace_callback(
4301 '/<!--IWLINK (.*?)-->/',
4302 $replacer->cb(),
4303 $text );
4304 wfProfileOut( $fname.'-interwiki' );
4305 }
4306
4307 wfProfileOut( $fname );
4308 return $colours;
4309 }
4310
4311 /**
4312 * Replace <!--LINK--> link placeholders with plain text of links
4313 * (not HTML-formatted).
4314 * @param string $text
4315 * @return string
4316 */
4317 function replaceLinkHoldersText( $text ) {
4318 $fname = 'Parser::replaceLinkHoldersText';
4319 wfProfileIn( $fname );
4320
4321 $text = preg_replace_callback(
4322 '/<!--(LINK|IWLINK) (.*?)-->/',
4323 array( &$this, 'replaceLinkHoldersTextCallback' ),
4324 $text );
4325
4326 wfProfileOut( $fname );
4327 return $text;
4328 }
4329
4330 /**
4331 * @param array $matches
4332 * @return string
4333 * @private
4334 */
4335 function replaceLinkHoldersTextCallback( $matches ) {
4336 $type = $matches[1];
4337 $key = $matches[2];
4338 if( $type == 'LINK' ) {
4339 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4340 return $this->mLinkHolders['texts'][$key];
4341 }
4342 } elseif( $type == 'IWLINK' ) {
4343 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4344 return $this->mInterwikiLinkHolders['texts'][$key];
4345 }
4346 }
4347 return $matches[0];
4348 }
4349
4350 /**
4351 * Tag hook handler for 'pre'.
4352 */
4353 function renderPreTag( $text, $attribs ) {
4354 // Backwards-compatibility hack
4355 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4356
4357 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4358 return wfOpenElement( 'pre', $attribs ) .
4359 Xml::escapeTagsOnly( $content ) .
4360 '</pre>';
4361 }
4362
4363 /**
4364 * Renders an image gallery from a text with one line per image.
4365 * text labels may be given by using |-style alternative text. E.g.
4366 * Image:one.jpg|The number "1"
4367 * Image:tree.jpg|A tree
4368 * given as text will return the HTML of a gallery with two images,
4369 * labeled 'The number "1"' and
4370 * 'A tree'.
4371 */
4372 function renderImageGallery( $text, $params ) {
4373 $ig = new ImageGallery();
4374 $ig->setContextTitle( $this->mTitle );
4375 $ig->setShowBytes( false );
4376 $ig->setShowFilename( false );
4377 $ig->setParser( $this );
4378 $ig->setHideBadImages();
4379 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4380 $ig->useSkin( $this->mOptions->getSkin() );
4381 $ig->mRevisionId = $this->mRevisionId;
4382
4383 if( isset( $params['caption'] ) ) {
4384 $caption = $params['caption'];
4385 $caption = htmlspecialchars( $caption );
4386 $caption = $this->replaceInternalLinks( $caption );
4387 $ig->setCaptionHtml( $caption );
4388 }
4389 if( isset( $params['perrow'] ) ) {
4390 $ig->setPerRow( $params['perrow'] );
4391 }
4392 if( isset( $params['widths'] ) ) {
4393 $ig->setWidths( $params['widths'] );
4394 }
4395 if( isset( $params['heights'] ) ) {
4396 $ig->setHeights( $params['heights'] );
4397 }
4398
4399 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4400
4401 $lines = explode( "\n", $text );
4402 foreach ( $lines as $line ) {
4403 # match lines like these:
4404 # Image:someimage.jpg|This is some image
4405 $matches = array();
4406 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4407 # Skip empty lines
4408 if ( count( $matches ) == 0 ) {
4409 continue;
4410 }
4411
4412 if ( strpos( $matches[0], '%' ) !== false )
4413 $matches[1] = urldecode( $matches[1] );
4414 $tp = Title::newFromText( $matches[1] );
4415 $nt =& $tp;
4416 if( is_null( $nt ) ) {
4417 # Bogus title. Ignore these so we don't bomb out later.
4418 continue;
4419 }
4420 if ( isset( $matches[3] ) ) {
4421 $label = $matches[3];
4422 } else {
4423 $label = '';
4424 }
4425
4426 $html = $this->recursiveTagParse( trim( $label ) );
4427
4428 $ig->add( $nt, $html );
4429
4430 # Only add real images (bug #5586)
4431 if ( $nt->getNamespace() == NS_IMAGE ) {
4432 $this->mOutput->addImage( $nt->getDBkey() );
4433 }
4434 }
4435 return $ig->toHTML();
4436 }
4437
4438 function getImageParams( $handler ) {
4439 if ( $handler ) {
4440 $handlerClass = get_class( $handler );
4441 } else {
4442 $handlerClass = '';
4443 }
4444 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4445 // Initialise static lists
4446 static $internalParamNames = array(
4447 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4448 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4449 'bottom', 'text-bottom' ),
4450 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4451 'upright', 'border' ),
4452 );
4453 static $internalParamMap;
4454 if ( !$internalParamMap ) {
4455 $internalParamMap = array();
4456 foreach ( $internalParamNames as $type => $names ) {
4457 foreach ( $names as $name ) {
4458 $magicName = str_replace( '-', '_', "img_$name" );
4459 $internalParamMap[$magicName] = array( $type, $name );
4460 }
4461 }
4462 }
4463
4464 // Add handler params
4465 $paramMap = $internalParamMap;
4466 if ( $handler ) {
4467 $handlerParamMap = $handler->getParamMap();
4468 foreach ( $handlerParamMap as $magic => $paramName ) {
4469 $paramMap[$magic] = array( 'handler', $paramName );
4470 }
4471 }
4472 $this->mImageParams[$handlerClass] = $paramMap;
4473 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4474 }
4475 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4476 }
4477
4478 /**
4479 * Parse image options text and use it to make an image
4480 */
4481 function makeImage( $title, $options ) {
4482 # Check if the options text is of the form "options|alt text"
4483 # Options are:
4484 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4485 # * left no resizing, just left align. label is used for alt= only
4486 # * right same, but right aligned
4487 # * none same, but not aligned
4488 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4489 # * center center the image
4490 # * framed Keep original image size, no magnify-button.
4491 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4492 # * upright reduce width for upright images, rounded to full __0 px
4493 # * border draw a 1px border around the image
4494 # vertical-align values (no % or length right now):
4495 # * baseline
4496 # * sub
4497 # * super
4498 # * top
4499 # * text-top
4500 # * middle
4501 # * bottom
4502 # * text-bottom
4503
4504 $parts = array_map( 'trim', explode( '|', $options) );
4505 $sk = $this->mOptions->getSkin();
4506
4507 # Give extensions a chance to select the file revision for us
4508 $skip = $time = $descQuery = false;
4509 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4510
4511 if ( $skip ) {
4512 return $sk->link( $title );
4513 }
4514
4515 # Get parameter map
4516 $file = wfFindFile( $title, $time );
4517 $handler = $file ? $file->getHandler() : false;
4518
4519 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4520
4521 # Process the input parameters
4522 $caption = '';
4523 $params = array( 'frame' => array(), 'handler' => array(),
4524 'horizAlign' => array(), 'vertAlign' => array() );
4525 foreach( $parts as $part ) {
4526 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4527 $validated = false;
4528 if( isset( $paramMap[$magicName] ) ) {
4529 list( $type, $paramName ) = $paramMap[$magicName];
4530
4531 // Special case; width and height come in one variable together
4532 if( $type == 'handler' && $paramName == 'width' ) {
4533 $m = array();
4534 # (bug 13500) In both cases (width/height and width only),
4535 # permit trailing "px" for backward compatibility.
4536 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4537 $width = intval( $m[1] );
4538 $height = intval( $m[2] );
4539 if ( $handler->validateParam( 'width', $width ) ) {
4540 $params[$type]['width'] = $width;
4541 $validated = true;
4542 }
4543 if ( $handler->validateParam( 'height', $height ) ) {
4544 $params[$type]['height'] = $height;
4545 $validated = true;
4546 }
4547 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4548 $width = intval( $value );
4549 if ( $handler->validateParam( 'width', $width ) ) {
4550 $params[$type]['width'] = $width;
4551 $validated = true;
4552 }
4553 } // else no validation -- bug 13436
4554 } else {
4555 if ( $type == 'handler' ) {
4556 # Validate handler parameter
4557 $validated = $handler->validateParam( $paramName, $value );
4558 } else {
4559 # Validate internal parameters
4560 switch( $paramName ) {
4561 case "manualthumb":
4562 /// @fixme - possibly check validity here?
4563 /// downstream behavior seems odd with missing manual thumbs.
4564 $validated = true;
4565 break;
4566 default:
4567 // Most other things appear to be empty or numeric...
4568 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4569 }
4570 }
4571
4572 if ( $validated ) {
4573 $params[$type][$paramName] = $value;
4574 }
4575 }
4576 }
4577 if ( !$validated ) {
4578 $caption = $part;
4579 }
4580 }
4581
4582 # Process alignment parameters
4583 if ( $params['horizAlign'] ) {
4584 $params['frame']['align'] = key( $params['horizAlign'] );
4585 }
4586 if ( $params['vertAlign'] ) {
4587 $params['frame']['valign'] = key( $params['vertAlign'] );
4588 }
4589
4590 # Strip bad stuff out of the alt text
4591 $alt = $this->replaceLinkHoldersText( $caption );
4592
4593 # make sure there are no placeholders in thumbnail attributes
4594 # that are later expanded to html- so expand them now and
4595 # remove the tags
4596 $alt = $this->mStripState->unstripBoth( $alt );
4597 $alt = Sanitizer::stripAllTags( $alt );
4598
4599 $params['frame']['alt'] = $alt;
4600 $params['frame']['caption'] = $caption;
4601
4602 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4603
4604 # Linker does the rest
4605 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4606
4607 # Give the handler a chance to modify the parser object
4608 if ( $handler ) {
4609 $handler->parserTransformHook( $this, $file );
4610 }
4611
4612 return $ret;
4613 }
4614
4615 /**
4616 * Set a flag in the output object indicating that the content is dynamic and
4617 * shouldn't be cached.
4618 */
4619 function disableCache() {
4620 wfDebug( "Parser output marked as uncacheable.\n" );
4621 $this->mOutput->mCacheTime = -1;
4622 }
4623
4624 /**#@+
4625 * Callback from the Sanitizer for expanding items found in HTML attribute
4626 * values, so they can be safely tested and escaped.
4627 * @param string $text
4628 * @param PPFrame $frame
4629 * @return string
4630 * @private
4631 */
4632 function attributeStripCallback( &$text, $frame = false ) {
4633 $text = $this->replaceVariables( $text, $frame );
4634 $text = $this->mStripState->unstripBoth( $text );
4635 return $text;
4636 }
4637
4638 /**#@-*/
4639
4640 /**#@+
4641 * Accessor/mutator
4642 */
4643 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4644 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4645 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4646 /**#@-*/
4647
4648 /**#@+
4649 * Accessor
4650 */
4651 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4652 /**#@-*/
4653
4654
4655 /**
4656 * Break wikitext input into sections, and either pull or replace
4657 * some particular section's text.
4658 *
4659 * External callers should use the getSection and replaceSection methods.
4660 *
4661 * @param string $text Page wikitext
4662 * @param string $section A section identifier string of the form:
4663 * <flag1> - <flag2> - ... - <section number>
4664 *
4665 * Currently the only recognised flag is "T", which means the target section number
4666 * was derived during a template inclusion parse, in other words this is a template
4667 * section edit link. If no flags are given, it was an ordinary section edit link.
4668 * This flag is required to avoid a section numbering mismatch when a section is
4669 * enclosed by <includeonly> (bug 6563).
4670 *
4671 * The section number 0 pulls the text before the first heading; other numbers will
4672 * pull the given section along with its lower-level subsections. If the section is
4673 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4674 *
4675 * @param string $mode One of "get" or "replace"
4676 * @param string $newText Replacement text for section data.
4677 * @return string for "get", the extracted section text.
4678 * for "replace", the whole page with the section replaced.
4679 */
4680 private function extractSections( $text, $section, $mode, $newText='' ) {
4681 global $wgTitle;
4682 $this->clearState();
4683 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4684 $this->mOptions = new ParserOptions;
4685 $this->setOutputType( self::OT_WIKI );
4686 $outText = '';
4687 $frame = $this->getPreprocessor()->newFrame();
4688
4689 // Process section extraction flags
4690 $flags = 0;
4691 $sectionParts = explode( '-', $section );
4692 $sectionIndex = array_pop( $sectionParts );
4693 foreach ( $sectionParts as $part ) {
4694 if ( $part == 'T' ) {
4695 $flags |= self::PTD_FOR_INCLUSION;
4696 }
4697 }
4698 // Preprocess the text
4699 $root = $this->preprocessToDom( $text, $flags );
4700
4701 // <h> nodes indicate section breaks
4702 // They can only occur at the top level, so we can find them by iterating the root's children
4703 $node = $root->getFirstChild();
4704
4705 // Find the target section
4706 if ( $sectionIndex == 0 ) {
4707 // Section zero doesn't nest, level=big
4708 $targetLevel = 1000;
4709 } else {
4710 while ( $node ) {
4711 if ( $node->getName() == 'h' ) {
4712 $bits = $node->splitHeading();
4713 if ( $bits['i'] == $sectionIndex ) {
4714 $targetLevel = $bits['level'];
4715 break;
4716 }
4717 }
4718 if ( $mode == 'replace' ) {
4719 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4720 }
4721 $node = $node->getNextSibling();
4722 }
4723 }
4724
4725 if ( !$node ) {
4726 // Not found
4727 if ( $mode == 'get' ) {
4728 return $newText;
4729 } else {
4730 return $text;
4731 }
4732 }
4733
4734 // Find the end of the section, including nested sections
4735 do {
4736 if ( $node->getName() == 'h' ) {
4737 $bits = $node->splitHeading();
4738 $curLevel = $bits['level'];
4739 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4740 break;
4741 }
4742 }
4743 if ( $mode == 'get' ) {
4744 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4745 }
4746 $node = $node->getNextSibling();
4747 } while ( $node );
4748
4749 // Write out the remainder (in replace mode only)
4750 if ( $mode == 'replace' ) {
4751 // Output the replacement text
4752 // Add two newlines on -- trailing whitespace in $newText is conventionally
4753 // stripped by the editor, so we need both newlines to restore the paragraph gap
4754 $outText .= $newText . "\n\n";
4755 while ( $node ) {
4756 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4757 $node = $node->getNextSibling();
4758 }
4759 }
4760
4761 if ( is_string( $outText ) ) {
4762 // Re-insert stripped tags
4763 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4764 }
4765
4766 return $outText;
4767 }
4768
4769 /**
4770 * This function returns the text of a section, specified by a number ($section).
4771 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4772 * the first section before any such heading (section 0).
4773 *
4774 * If a section contains subsections, these are also returned.
4775 *
4776 * @param string $text text to look in
4777 * @param string $section section identifier
4778 * @param string $deftext default to return if section is not found
4779 * @return string text of the requested section
4780 */
4781 public function getSection( $text, $section, $deftext='' ) {
4782 return $this->extractSections( $text, $section, "get", $deftext );
4783 }
4784
4785 public function replaceSection( $oldtext, $section, $text ) {
4786 return $this->extractSections( $oldtext, $section, "replace", $text );
4787 }
4788
4789 /**
4790 * Get the timestamp associated with the current revision, adjusted for
4791 * the default server-local timestamp
4792 */
4793 function getRevisionTimestamp() {
4794 if ( is_null( $this->mRevisionTimestamp ) ) {
4795 wfProfileIn( __METHOD__ );
4796 global $wgContLang;
4797 $dbr = wfGetDB( DB_SLAVE );
4798 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4799 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4800
4801 // Normalize timestamp to internal MW format for timezone processing.
4802 // This has the added side-effect of replacing a null value with
4803 // the current time, which gives us more sensible behavior for
4804 // previews.
4805 $timestamp = wfTimestamp( TS_MW, $timestamp );
4806
4807 // The cryptic '' timezone parameter tells to use the site-default
4808 // timezone offset instead of the user settings.
4809 //
4810 // Since this value will be saved into the parser cache, served
4811 // to other users, and potentially even used inside links and such,
4812 // it needs to be consistent for all visitors.
4813 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4814
4815 wfProfileOut( __METHOD__ );
4816 }
4817 return $this->mRevisionTimestamp;
4818 }
4819
4820 /**
4821 * Mutator for $mDefaultSort
4822 *
4823 * @param $sort New value
4824 */
4825 public function setDefaultSort( $sort ) {
4826 $this->mDefaultSort = $sort;
4827 }
4828
4829 /**
4830 * Accessor for $mDefaultSort
4831 * Will use the title/prefixed title if none is set
4832 *
4833 * @return string
4834 */
4835 public function getDefaultSort() {
4836 global $wgCategoryPrefixedDefaultSortkey;
4837 if( $this->mDefaultSort !== false ) {
4838 return $this->mDefaultSort;
4839 } elseif ($this->mTitle->getNamespace() == NS_CATEGORY ||
4840 !$wgCategoryPrefixedDefaultSortkey) {
4841 return $this->mTitle->getText();
4842 } else {
4843 return $this->mTitle->getPrefixedText();
4844 }
4845 }
4846
4847 /**
4848 * Try to guess the section anchor name based on a wikitext fragment
4849 * presumably extracted from a heading, for example "Header" from
4850 * "== Header ==".
4851 */
4852 public function guessSectionNameFromWikiText( $text ) {
4853 # Strip out wikitext links(they break the anchor)
4854 $text = $this->stripSectionName( $text );
4855 $headline = Sanitizer::decodeCharReferences( $text );
4856 # strip out HTML
4857 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
4858 $headline = trim( $headline );
4859 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4860 $replacearray = array(
4861 '%3A' => ':',
4862 '%' => '.'
4863 );
4864 return str_replace(
4865 array_keys( $replacearray ),
4866 array_values( $replacearray ),
4867 $sectionanchor );
4868 }
4869
4870 /**
4871 * Strips a text string of wikitext for use in a section anchor
4872 *
4873 * Accepts a text string and then removes all wikitext from the
4874 * string and leaves only the resultant text (i.e. the result of
4875 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4876 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4877 * to create valid section anchors by mimicing the output of the
4878 * parser when headings are parsed.
4879 *
4880 * @param $text string Text string to be stripped of wikitext
4881 * for use in a Section anchor
4882 * @return Filtered text string
4883 */
4884 public function stripSectionName( $text ) {
4885 # Strip internal link markup
4886 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4887 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4888
4889 # Strip external link markup (FIXME: Not Tolerant to blank link text
4890 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4891 # on how many empty links there are on the page - need to figure that out.
4892 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4893
4894 # Parse wikitext quotes (italics & bold)
4895 $text = $this->doQuotes($text);
4896
4897 # Strip HTML tags
4898 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
4899 return $text;
4900 }
4901
4902 function srvus( $text ) {
4903 return $this->testSrvus( $text, $this->mOutputType );
4904 }
4905
4906 /**
4907 * strip/replaceVariables/unstrip for preprocessor regression testing
4908 */
4909 function testSrvus( $text, $title, $options, $outputType = self::OT_HTML ) {
4910 $this->clearState();
4911 if ( ! ( $title instanceof Title ) ) {
4912 $title = Title::newFromText( $title );
4913 }
4914 $this->mTitle = $title;
4915 $this->mOptions = $options;
4916 $this->setOutputType( $outputType );
4917 $text = $this->replaceVariables( $text );
4918 $text = $this->mStripState->unstripBoth( $text );
4919 $text = Sanitizer::removeHTMLtags( $text );
4920 return $text;
4921 }
4922
4923 function testPst( $text, $title, $options ) {
4924 global $wgUser;
4925 if ( ! ( $title instanceof Title ) ) {
4926 $title = Title::newFromText( $title );
4927 }
4928 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4929 }
4930
4931 function testPreprocess( $text, $title, $options ) {
4932 if ( ! ( $title instanceof Title ) ) {
4933 $title = Title::newFromText( $title );
4934 }
4935 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
4936 }
4937
4938 function markerSkipCallback( $s, $callback ) {
4939 $i = 0;
4940 $out = '';
4941 while ( $i < strlen( $s ) ) {
4942 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
4943 if ( $markerStart === false ) {
4944 $out .= call_user_func( $callback, substr( $s, $i ) );
4945 break;
4946 } else {
4947 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4948 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
4949 if ( $markerEnd === false ) {
4950 $out .= substr( $s, $markerStart );
4951 break;
4952 } else {
4953 $markerEnd += strlen( self::MARKER_SUFFIX );
4954 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4955 $i = $markerEnd;
4956 }
4957 }
4958 }
4959 return $out;
4960 }
4961 }
4962
4963 /**
4964 * @todo document, briefly.
4965 * @ingroup Parser
4966 */
4967 class StripState {
4968 var $general, $nowiki;
4969
4970 function __construct() {
4971 $this->general = new ReplacementArray;
4972 $this->nowiki = new ReplacementArray;
4973 }
4974
4975 function unstripGeneral( $text ) {
4976 wfProfileIn( __METHOD__ );
4977 do {
4978 $oldText = $text;
4979 $text = $this->general->replace( $text );
4980 } while ( $text != $oldText );
4981 wfProfileOut( __METHOD__ );
4982 return $text;
4983 }
4984
4985 function unstripNoWiki( $text ) {
4986 wfProfileIn( __METHOD__ );
4987 do {
4988 $oldText = $text;
4989 $text = $this->nowiki->replace( $text );
4990 } while ( $text != $oldText );
4991 wfProfileOut( __METHOD__ );
4992 return $text;
4993 }
4994
4995 function unstripBoth( $text ) {
4996 wfProfileIn( __METHOD__ );
4997 do {
4998 $oldText = $text;
4999 $text = $this->general->replace( $text );
5000 $text = $this->nowiki->replace( $text );
5001 } while ( $text != $oldText );
5002 wfProfileOut( __METHOD__ );
5003 return $text;
5004 }
5005 }
5006
5007 /**
5008 * @todo document, briefly.
5009 * @ingroup Parser
5010 */
5011 class OnlyIncludeReplacer {
5012 var $output = '';
5013
5014 function replace( $matches ) {
5015 if ( substr( $matches[1], -1 ) == "\n" ) {
5016 $this->output .= substr( $matches[1], 0, -1 );
5017 } else {
5018 $this->output .= $matches[1];
5019 }
5020 }
5021 }