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