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