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