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