(bug 32450) MediaWiki: .js|.css pages parsed [[Category:#]] links
[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 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1647 return $s;
1648 }
1649
1650 /**
1651 * Process [[ ]] wikilinks (RIL)
1652 * @return LinkHolderArray
1653 *
1654 * @private
1655 */
1656 function replaceInternalLinks2( &$s ) {
1657 wfProfileIn( __METHOD__ );
1658
1659 wfProfileIn( __METHOD__.'-setup' );
1660 static $tc = FALSE, $e1, $e1_img;
1661 # the % is needed to support urlencoded titles as well
1662 if ( !$tc ) {
1663 $tc = Title::legalChars() . '#%';
1664 # Match a link having the form [[namespace:link|alternate]]trail
1665 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1666 # Match cases where there is no "]]", which might still be images
1667 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1668 }
1669
1670 $holders = new LinkHolderArray( $this );
1671
1672 # split the entire text string on occurences of [[
1673 $a = StringUtils::explode( '[[', ' ' . $s );
1674 # get the first element (all text up to first [[), and remove the space we added
1675 $s = $a->current();
1676 $a->next();
1677 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1678 $s = substr( $s, 1 );
1679
1680 $useLinkPrefixExtension = $this->getFunctionLang()->linkPrefixExtension();
1681 $e2 = null;
1682 if ( $useLinkPrefixExtension ) {
1683 # Match the end of a line for a word that's not followed by whitespace,
1684 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1685 $e2 = wfMsgForContent( 'linkprefix' );
1686 }
1687
1688 if ( is_null( $this->mTitle ) ) {
1689 wfProfileOut( __METHOD__.'-setup' );
1690 wfProfileOut( __METHOD__ );
1691 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1692 }
1693 $nottalk = !$this->mTitle->isTalkPage();
1694
1695 if ( $useLinkPrefixExtension ) {
1696 $m = array();
1697 if ( preg_match( $e2, $s, $m ) ) {
1698 $first_prefix = $m[2];
1699 } else {
1700 $first_prefix = false;
1701 }
1702 } else {
1703 $prefix = '';
1704 }
1705
1706 if ( $this->getFunctionLang()->hasVariants() ) {
1707 $selflink = $this->getFunctionLang()->autoConvertToAllVariants( $this->mTitle->getPrefixedText() );
1708 } else {
1709 $selflink = array( $this->mTitle->getPrefixedText() );
1710 }
1711 $useSubpages = $this->areSubpagesAllowed();
1712 wfProfileOut( __METHOD__.'-setup' );
1713
1714 # Loop for each link
1715 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1716 # Check for excessive memory usage
1717 if ( $holders->isBig() ) {
1718 # Too big
1719 # Do the existence check, replace the link holders and clear the array
1720 $holders->replace( $s );
1721 $holders->clear();
1722 }
1723
1724 if ( $useLinkPrefixExtension ) {
1725 wfProfileIn( __METHOD__.'-prefixhandling' );
1726 if ( preg_match( $e2, $s, $m ) ) {
1727 $prefix = $m[2];
1728 $s = $m[1];
1729 } else {
1730 $prefix='';
1731 }
1732 # first link
1733 if ( $first_prefix ) {
1734 $prefix = $first_prefix;
1735 $first_prefix = false;
1736 }
1737 wfProfileOut( __METHOD__.'-prefixhandling' );
1738 }
1739
1740 $might_be_img = false;
1741
1742 wfProfileIn( __METHOD__."-e1" );
1743 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1744 $text = $m[2];
1745 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1746 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1747 # the real problem is with the $e1 regex
1748 # See bug 1300.
1749 #
1750 # Still some problems for cases where the ] is meant to be outside punctuation,
1751 # and no image is in sight. See bug 2095.
1752 #
1753 if ( $text !== '' &&
1754 substr( $m[3], 0, 1 ) === ']' &&
1755 strpos( $text, '[' ) !== false
1756 )
1757 {
1758 $text .= ']'; # so that replaceExternalLinks($text) works later
1759 $m[3] = substr( $m[3], 1 );
1760 }
1761 # fix up urlencoded title texts
1762 if ( strpos( $m[1], '%' ) !== false ) {
1763 # Should anchors '#' also be rejected?
1764 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), rawurldecode( $m[1] ) );
1765 }
1766 $trail = $m[3];
1767 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1768 $might_be_img = true;
1769 $text = $m[2];
1770 if ( strpos( $m[1], '%' ) !== false ) {
1771 $m[1] = rawurldecode( $m[1] );
1772 }
1773 $trail = "";
1774 } else { # Invalid form; output directly
1775 $s .= $prefix . '[[' . $line ;
1776 wfProfileOut( __METHOD__."-e1" );
1777 continue;
1778 }
1779 wfProfileOut( __METHOD__."-e1" );
1780 wfProfileIn( __METHOD__."-misc" );
1781
1782 # Don't allow internal links to pages containing
1783 # PROTO: where PROTO is a valid URL protocol; these
1784 # should be external links.
1785 if ( preg_match( '/^(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1786 $s .= $prefix . '[[' . $line ;
1787 wfProfileOut( __METHOD__."-misc" );
1788 continue;
1789 }
1790
1791 # Make subpage if necessary
1792 if ( $useSubpages ) {
1793 $link = $this->maybeDoSubpageLink( $m[1], $text );
1794 } else {
1795 $link = $m[1];
1796 }
1797
1798 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1799 if ( !$noforce ) {
1800 # Strip off leading ':'
1801 $link = substr( $link, 1 );
1802 }
1803
1804 wfProfileOut( __METHOD__."-misc" );
1805 wfProfileIn( __METHOD__."-title" );
1806 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
1807 if ( $nt === null ) {
1808 $s .= $prefix . '[[' . $line;
1809 wfProfileOut( __METHOD__."-title" );
1810 continue;
1811 }
1812
1813 $ns = $nt->getNamespace();
1814 $iw = $nt->getInterWiki();
1815 wfProfileOut( __METHOD__."-title" );
1816
1817 if ( $might_be_img ) { # if this is actually an invalid link
1818 wfProfileIn( __METHOD__."-might_be_img" );
1819 if ( $ns == NS_FILE && $noforce ) { # but might be an image
1820 $found = false;
1821 while ( true ) {
1822 # look at the next 'line' to see if we can close it there
1823 $a->next();
1824 $next_line = $a->current();
1825 if ( $next_line === false || $next_line === null ) {
1826 break;
1827 }
1828 $m = explode( ']]', $next_line, 3 );
1829 if ( count( $m ) == 3 ) {
1830 # the first ]] closes the inner link, the second the image
1831 $found = true;
1832 $text .= "[[{$m[0]}]]{$m[1]}";
1833 $trail = $m[2];
1834 break;
1835 } elseif ( count( $m ) == 2 ) {
1836 # if there's exactly one ]] that's fine, we'll keep looking
1837 $text .= "[[{$m[0]}]]{$m[1]}";
1838 } else {
1839 # if $next_line is invalid too, we need look no further
1840 $text .= '[[' . $next_line;
1841 break;
1842 }
1843 }
1844 if ( !$found ) {
1845 # we couldn't find the end of this imageLink, so output it raw
1846 # but don't ignore what might be perfectly normal links in the text we've examined
1847 $holders->merge( $this->replaceInternalLinks2( $text ) );
1848 $s .= "{$prefix}[[$link|$text";
1849 # note: no $trail, because without an end, there *is* no trail
1850 wfProfileOut( __METHOD__."-might_be_img" );
1851 continue;
1852 }
1853 } else { # it's not an image, so output it raw
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 wfProfileOut( __METHOD__."-might_be_img" );
1860 }
1861
1862 $wasblank = ( $text == '' );
1863 if ( $wasblank ) {
1864 $text = $link;
1865 } else {
1866 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1867 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1868 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1869 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1870 $text = $this->doQuotes( $text );
1871 }
1872
1873 # Link not escaped by : , create the various objects
1874 if ( $noforce ) {
1875 global $wgContLang;
1876
1877 # Interwikis
1878 wfProfileIn( __METHOD__."-interwiki" );
1879 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1880 $this->mOutput->addLanguageLink( $nt->getFullText() );
1881 $s = rtrim( $s . $prefix );
1882 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
1883 wfProfileOut( __METHOD__."-interwiki" );
1884 continue;
1885 }
1886 wfProfileOut( __METHOD__."-interwiki" );
1887
1888 if ( $ns == NS_FILE ) {
1889 wfProfileIn( __METHOD__."-image" );
1890 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1891 if ( $wasblank ) {
1892 # if no parameters were passed, $text
1893 # becomes something like "File:Foo.png",
1894 # which we don't want to pass on to the
1895 # image generator
1896 $text = '';
1897 } else {
1898 # recursively parse links inside the image caption
1899 # actually, this will parse them in any other parameters, too,
1900 # but it might be hard to fix that, and it doesn't matter ATM
1901 $text = $this->replaceExternalLinks( $text );
1902 $holders->merge( $this->replaceInternalLinks2( $text ) );
1903 }
1904 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1905 $s .= $prefix . $this->armorLinks(
1906 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1907 } else {
1908 $s .= $prefix . $trail;
1909 }
1910 wfProfileOut( __METHOD__."-image" );
1911 continue;
1912 }
1913
1914 if ( $ns == NS_CATEGORY ) {
1915 wfProfileIn( __METHOD__."-category" );
1916 if( $this->getTitle()->isCssOrJsPage() ) {
1917 # bug 32450 : js and script pages in MediaWiki: namespace do not want
1918 # to get their code or comments altered. Think about js string:
1919 # var foobar = "[[Category:" + $catname + "]];
1920 $s .= "[[$text]]$trail";
1921 wfProfileOut( __METHOD__."-category" );
1922 continue;
1923 }
1924 $s = rtrim( $s . "\n" ); # bug 87
1925
1926 if ( $wasblank ) {
1927 $sortkey = $this->getDefaultSort();
1928 } else {
1929 $sortkey = $text;
1930 }
1931 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1932 $sortkey = str_replace( "\n", '', $sortkey );
1933 $sortkey = $this->getFunctionLang()->convertCategoryKey( $sortkey );
1934 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1935
1936 /**
1937 * Strip the whitespace Category links produce, see bug 87
1938 * @todo We might want to use trim($tmp, "\n") here.
1939 */
1940 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
1941
1942 wfProfileOut( __METHOD__."-category" );
1943 continue;
1944 }
1945 }
1946
1947 # Self-link checking
1948 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL ) {
1949 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1950 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
1951 continue;
1952 }
1953 }
1954
1955 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1956 # @todo FIXME: Should do batch file existence checks, see comment below
1957 if ( $ns == NS_MEDIA ) {
1958 wfProfileIn( __METHOD__."-media" );
1959 # Give extensions a chance to select the file revision for us
1960 $options = array();
1961 $descQuery = false;
1962 wfRunHooks( 'BeforeParserFetchFileAndTitle',
1963 array( $this, $nt, &$options, &$descQuery ) );
1964 # Fetch and register the file (file title may be different via hooks)
1965 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
1966 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1967 $s .= $prefix . $this->armorLinks(
1968 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
1969 wfProfileOut( __METHOD__."-media" );
1970 continue;
1971 }
1972
1973 wfProfileIn( __METHOD__."-always_known" );
1974 # Some titles, such as valid special pages or files in foreign repos, should
1975 # be shown as bluelinks even though they're not included in the page table
1976 #
1977 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1978 # batch file existence checks for NS_FILE and NS_MEDIA
1979 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1980 $this->mOutput->addLink( $nt );
1981 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
1982 } else {
1983 # Links will be added to the output link list after checking
1984 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
1985 }
1986 wfProfileOut( __METHOD__."-always_known" );
1987 }
1988 wfProfileOut( __METHOD__ );
1989 return $holders;
1990 }
1991
1992 /**
1993 * Render a forced-blue link inline; protect against double expansion of
1994 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1995 * Since this little disaster has to split off the trail text to avoid
1996 * breaking URLs in the following text without breaking trails on the
1997 * wiki links, it's been made into a horrible function.
1998 *
1999 * @param $nt Title
2000 * @param $text String
2001 * @param $query Array or String
2002 * @param $trail String
2003 * @param $prefix String
2004 * @return String: HTML-wikitext mix oh yuck
2005 */
2006 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2007 list( $inside, $trail ) = Linker::splitTrail( $trail );
2008
2009 if ( is_string( $query ) ) {
2010 $query = wfCgiToArray( $query );
2011 }
2012 if ( $text == '' ) {
2013 $text = htmlspecialchars( $nt->getPrefixedText() );
2014 }
2015
2016 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2017
2018 return $this->armorLinks( $link ) . $trail;
2019 }
2020
2021 /**
2022 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2023 * going to go through further parsing steps before inline URL expansion.
2024 *
2025 * Not needed quite as much as it used to be since free links are a bit
2026 * more sensible these days. But bracketed links are still an issue.
2027 *
2028 * @param $text String: more-or-less HTML
2029 * @return String: less-or-more HTML with NOPARSE bits
2030 */
2031 function armorLinks( $text ) {
2032 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2033 "{$this->mUniqPrefix}NOPARSE$1", $text );
2034 }
2035
2036 /**
2037 * Return true if subpage links should be expanded on this page.
2038 * @return Boolean
2039 */
2040 function areSubpagesAllowed() {
2041 # Some namespaces don't allow subpages
2042 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2043 }
2044
2045 /**
2046 * Handle link to subpage if necessary
2047 *
2048 * @param $target String: the source of the link
2049 * @param &$text String: the link text, modified as necessary
2050 * @return string the full name of the link
2051 * @private
2052 */
2053 function maybeDoSubpageLink( $target, &$text ) {
2054 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2055 }
2056
2057 /**#@+
2058 * Used by doBlockLevels()
2059 * @private
2060 *
2061 * @return string
2062 */
2063 function closeParagraph() {
2064 $result = '';
2065 if ( $this->mLastSection != '' ) {
2066 $result = '</' . $this->mLastSection . ">\n";
2067 }
2068 $this->mInPre = false;
2069 $this->mLastSection = '';
2070 return $result;
2071 }
2072
2073 /**
2074 * getCommon() returns the length of the longest common substring
2075 * of both arguments, starting at the beginning of both.
2076 * @private
2077 *
2078 * @param $st1 string
2079 * @param $st2 string
2080 *
2081 * @return int
2082 */
2083 function getCommon( $st1, $st2 ) {
2084 $fl = strlen( $st1 );
2085 $shorter = strlen( $st2 );
2086 if ( $fl < $shorter ) {
2087 $shorter = $fl;
2088 }
2089
2090 for ( $i = 0; $i < $shorter; ++$i ) {
2091 if ( $st1[$i] != $st2[$i] ) {
2092 break;
2093 }
2094 }
2095 return $i;
2096 }
2097
2098 /**
2099 * These next three functions open, continue, and close the list
2100 * element appropriate to the prefix character passed into them.
2101 * @private
2102 *
2103 * @param $char char
2104 *
2105 * @return string
2106 */
2107 function openList( $char ) {
2108 $result = $this->closeParagraph();
2109
2110 if ( '*' === $char ) {
2111 $result .= '<ul><li>';
2112 } elseif ( '#' === $char ) {
2113 $result .= '<ol><li>';
2114 } elseif ( ':' === $char ) {
2115 $result .= '<dl><dd>';
2116 } elseif ( ';' === $char ) {
2117 $result .= '<dl><dt>';
2118 $this->mDTopen = true;
2119 } else {
2120 $result = '<!-- ERR 1 -->';
2121 }
2122
2123 return $result;
2124 }
2125
2126 /**
2127 * TODO: document
2128 * @param $char String
2129 * @private
2130 *
2131 * @return string
2132 */
2133 function nextItem( $char ) {
2134 if ( '*' === $char || '#' === $char ) {
2135 return '</li><li>';
2136 } elseif ( ':' === $char || ';' === $char ) {
2137 $close = '</dd>';
2138 if ( $this->mDTopen ) {
2139 $close = '</dt>';
2140 }
2141 if ( ';' === $char ) {
2142 $this->mDTopen = true;
2143 return $close . '<dt>';
2144 } else {
2145 $this->mDTopen = false;
2146 return $close . '<dd>';
2147 }
2148 }
2149 return '<!-- ERR 2 -->';
2150 }
2151
2152 /**
2153 * TODO: document
2154 * @param $char String
2155 * @private
2156 *
2157 * @return string
2158 */
2159 function closeList( $char ) {
2160 if ( '*' === $char ) {
2161 $text = '</li></ul>';
2162 } elseif ( '#' === $char ) {
2163 $text = '</li></ol>';
2164 } elseif ( ':' === $char ) {
2165 if ( $this->mDTopen ) {
2166 $this->mDTopen = false;
2167 $text = '</dt></dl>';
2168 } else {
2169 $text = '</dd></dl>';
2170 }
2171 } else {
2172 return '<!-- ERR 3 -->';
2173 }
2174 return $text."\n";
2175 }
2176 /**#@-*/
2177
2178 /**
2179 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2180 *
2181 * @param $text String
2182 * @param $linestart Boolean: whether or not this is at the start of a line.
2183 * @private
2184 * @return string the lists rendered as HTML
2185 */
2186 function doBlockLevels( $text, $linestart ) {
2187 wfProfileIn( __METHOD__ );
2188
2189 # Parsing through the text line by line. The main thing
2190 # happening here is handling of block-level elements p, pre,
2191 # and making lists from lines starting with * # : etc.
2192 #
2193 $textLines = StringUtils::explode( "\n", $text );
2194
2195 $lastPrefix = $output = '';
2196 $this->mDTopen = $inBlockElem = false;
2197 $prefixLength = 0;
2198 $paragraphStack = false;
2199
2200 foreach ( $textLines as $oLine ) {
2201 # Fix up $linestart
2202 if ( !$linestart ) {
2203 $output .= $oLine;
2204 $linestart = true;
2205 continue;
2206 }
2207 # * = ul
2208 # # = ol
2209 # ; = dt
2210 # : = dd
2211
2212 $lastPrefixLength = strlen( $lastPrefix );
2213 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2214 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2215 # If not in a <pre> element, scan for and figure out what prefixes are there.
2216 if ( !$this->mInPre ) {
2217 # Multiple prefixes may abut each other for nested lists.
2218 $prefixLength = strspn( $oLine, '*#:;' );
2219 $prefix = substr( $oLine, 0, $prefixLength );
2220
2221 # eh?
2222 # ; and : are both from definition-lists, so they're equivalent
2223 # for the purposes of determining whether or not we need to open/close
2224 # elements.
2225 $prefix2 = str_replace( ';', ':', $prefix );
2226 $t = substr( $oLine, $prefixLength );
2227 $this->mInPre = (bool)$preOpenMatch;
2228 } else {
2229 # Don't interpret any other prefixes in preformatted text
2230 $prefixLength = 0;
2231 $prefix = $prefix2 = '';
2232 $t = $oLine;
2233 }
2234
2235 # List generation
2236 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2237 # Same as the last item, so no need to deal with nesting or opening stuff
2238 $output .= $this->nextItem( substr( $prefix, -1 ) );
2239 $paragraphStack = false;
2240
2241 if ( substr( $prefix, -1 ) === ';') {
2242 # The one nasty exception: definition lists work like this:
2243 # ; title : definition text
2244 # So we check for : in the remainder text to split up the
2245 # title and definition, without b0rking links.
2246 $term = $t2 = '';
2247 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2248 $t = $t2;
2249 $output .= $term . $this->nextItem( ':' );
2250 }
2251 }
2252 } elseif ( $prefixLength || $lastPrefixLength ) {
2253 # We need to open or close prefixes, or both.
2254
2255 # Either open or close a level...
2256 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2257 $paragraphStack = false;
2258
2259 # Close all the prefixes which aren't shared.
2260 while ( $commonPrefixLength < $lastPrefixLength ) {
2261 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2262 --$lastPrefixLength;
2263 }
2264
2265 # Continue the current prefix if appropriate.
2266 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2267 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2268 }
2269
2270 # Open prefixes where appropriate.
2271 while ( $prefixLength > $commonPrefixLength ) {
2272 $char = substr( $prefix, $commonPrefixLength, 1 );
2273 $output .= $this->openList( $char );
2274
2275 if ( ';' === $char ) {
2276 # @todo FIXME: This is dupe of code above
2277 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2278 $t = $t2;
2279 $output .= $term . $this->nextItem( ':' );
2280 }
2281 }
2282 ++$commonPrefixLength;
2283 }
2284 $lastPrefix = $prefix2;
2285 }
2286
2287 # If we have no prefixes, go to paragraph mode.
2288 if ( 0 == $prefixLength ) {
2289 wfProfileIn( __METHOD__."-paragraph" );
2290 # No prefix (not in list)--go to paragraph mode
2291 # XXX: use a stack for nestable elements like span, table and div
2292 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2293 $closematch = preg_match(
2294 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2295 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2296 if ( $openmatch or $closematch ) {
2297 $paragraphStack = false;
2298 # TODO bug 5718: paragraph closed
2299 $output .= $this->closeParagraph();
2300 if ( $preOpenMatch and !$preCloseMatch ) {
2301 $this->mInPre = true;
2302 }
2303 $inBlockElem = !$closematch;
2304 } elseif ( !$inBlockElem && !$this->mInPre ) {
2305 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) ) {
2306 # pre
2307 if ( $this->mLastSection !== 'pre' ) {
2308 $paragraphStack = false;
2309 $output .= $this->closeParagraph().'<pre>';
2310 $this->mLastSection = 'pre';
2311 }
2312 $t = substr( $t, 1 );
2313 } else {
2314 # paragraph
2315 if ( trim( $t ) === '' ) {
2316 if ( $paragraphStack ) {
2317 $output .= $paragraphStack.'<br />';
2318 $paragraphStack = false;
2319 $this->mLastSection = 'p';
2320 } else {
2321 if ( $this->mLastSection !== 'p' ) {
2322 $output .= $this->closeParagraph();
2323 $this->mLastSection = '';
2324 $paragraphStack = '<p>';
2325 } else {
2326 $paragraphStack = '</p><p>';
2327 }
2328 }
2329 } else {
2330 if ( $paragraphStack ) {
2331 $output .= $paragraphStack;
2332 $paragraphStack = false;
2333 $this->mLastSection = 'p';
2334 } elseif ( $this->mLastSection !== 'p' ) {
2335 $output .= $this->closeParagraph().'<p>';
2336 $this->mLastSection = 'p';
2337 }
2338 }
2339 }
2340 }
2341 wfProfileOut( __METHOD__."-paragraph" );
2342 }
2343 # somewhere above we forget to get out of pre block (bug 785)
2344 if ( $preCloseMatch && $this->mInPre ) {
2345 $this->mInPre = false;
2346 }
2347 if ( $paragraphStack === false ) {
2348 $output .= $t."\n";
2349 }
2350 }
2351 while ( $prefixLength ) {
2352 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2353 --$prefixLength;
2354 }
2355 if ( $this->mLastSection != '' ) {
2356 $output .= '</' . $this->mLastSection . '>';
2357 $this->mLastSection = '';
2358 }
2359
2360 wfProfileOut( __METHOD__ );
2361 return $output;
2362 }
2363
2364 /**
2365 * Split up a string on ':', ignoring any occurences inside tags
2366 * to prevent illegal overlapping.
2367 *
2368 * @param $str String the string to split
2369 * @param &$before String set to everything before the ':'
2370 * @param &$after String set to everything after the ':'
2371 * @return String the position of the ':', or false if none found
2372 */
2373 function findColonNoLinks( $str, &$before, &$after ) {
2374 wfProfileIn( __METHOD__ );
2375
2376 $pos = strpos( $str, ':' );
2377 if ( $pos === false ) {
2378 # Nothing to find!
2379 wfProfileOut( __METHOD__ );
2380 return false;
2381 }
2382
2383 $lt = strpos( $str, '<' );
2384 if ( $lt === false || $lt > $pos ) {
2385 # Easy; no tag nesting to worry about
2386 $before = substr( $str, 0, $pos );
2387 $after = substr( $str, $pos+1 );
2388 wfProfileOut( __METHOD__ );
2389 return $pos;
2390 }
2391
2392 # Ugly state machine to walk through avoiding tags.
2393 $state = self::COLON_STATE_TEXT;
2394 $stack = 0;
2395 $len = strlen( $str );
2396 for( $i = 0; $i < $len; $i++ ) {
2397 $c = $str[$i];
2398
2399 switch( $state ) {
2400 # (Using the number is a performance hack for common cases)
2401 case 0: # self::COLON_STATE_TEXT:
2402 switch( $c ) {
2403 case "<":
2404 # Could be either a <start> tag or an </end> tag
2405 $state = self::COLON_STATE_TAGSTART;
2406 break;
2407 case ":":
2408 if ( $stack == 0 ) {
2409 # We found it!
2410 $before = substr( $str, 0, $i );
2411 $after = substr( $str, $i + 1 );
2412 wfProfileOut( __METHOD__ );
2413 return $i;
2414 }
2415 # Embedded in a tag; don't break it.
2416 break;
2417 default:
2418 # Skip ahead looking for something interesting
2419 $colon = strpos( $str, ':', $i );
2420 if ( $colon === false ) {
2421 # Nothing else interesting
2422 wfProfileOut( __METHOD__ );
2423 return false;
2424 }
2425 $lt = strpos( $str, '<', $i );
2426 if ( $stack === 0 ) {
2427 if ( $lt === false || $colon < $lt ) {
2428 # We found it!
2429 $before = substr( $str, 0, $colon );
2430 $after = substr( $str, $colon + 1 );
2431 wfProfileOut( __METHOD__ );
2432 return $i;
2433 }
2434 }
2435 if ( $lt === false ) {
2436 # Nothing else interesting to find; abort!
2437 # We're nested, but there's no close tags left. Abort!
2438 break 2;
2439 }
2440 # Skip ahead to next tag start
2441 $i = $lt;
2442 $state = self::COLON_STATE_TAGSTART;
2443 }
2444 break;
2445 case 1: # self::COLON_STATE_TAG:
2446 # In a <tag>
2447 switch( $c ) {
2448 case ">":
2449 $stack++;
2450 $state = self::COLON_STATE_TEXT;
2451 break;
2452 case "/":
2453 # Slash may be followed by >?
2454 $state = self::COLON_STATE_TAGSLASH;
2455 break;
2456 default:
2457 # ignore
2458 }
2459 break;
2460 case 2: # self::COLON_STATE_TAGSTART:
2461 switch( $c ) {
2462 case "/":
2463 $state = self::COLON_STATE_CLOSETAG;
2464 break;
2465 case "!":
2466 $state = self::COLON_STATE_COMMENT;
2467 break;
2468 case ">":
2469 # Illegal early close? This shouldn't happen D:
2470 $state = self::COLON_STATE_TEXT;
2471 break;
2472 default:
2473 $state = self::COLON_STATE_TAG;
2474 }
2475 break;
2476 case 3: # self::COLON_STATE_CLOSETAG:
2477 # In a </tag>
2478 if ( $c === ">" ) {
2479 $stack--;
2480 if ( $stack < 0 ) {
2481 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
2482 wfProfileOut( __METHOD__ );
2483 return false;
2484 }
2485 $state = self::COLON_STATE_TEXT;
2486 }
2487 break;
2488 case self::COLON_STATE_TAGSLASH:
2489 if ( $c === ">" ) {
2490 # Yes, a self-closed tag <blah/>
2491 $state = self::COLON_STATE_TEXT;
2492 } else {
2493 # Probably we're jumping the gun, and this is an attribute
2494 $state = self::COLON_STATE_TAG;
2495 }
2496 break;
2497 case 5: # self::COLON_STATE_COMMENT:
2498 if ( $c === "-" ) {
2499 $state = self::COLON_STATE_COMMENTDASH;
2500 }
2501 break;
2502 case self::COLON_STATE_COMMENTDASH:
2503 if ( $c === "-" ) {
2504 $state = self::COLON_STATE_COMMENTDASHDASH;
2505 } else {
2506 $state = self::COLON_STATE_COMMENT;
2507 }
2508 break;
2509 case self::COLON_STATE_COMMENTDASHDASH:
2510 if ( $c === ">" ) {
2511 $state = self::COLON_STATE_TEXT;
2512 } else {
2513 $state = self::COLON_STATE_COMMENT;
2514 }
2515 break;
2516 default:
2517 throw new MWException( "State machine error in " . __METHOD__ );
2518 }
2519 }
2520 if ( $stack > 0 ) {
2521 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2522 wfProfileOut( __METHOD__ );
2523 return false;
2524 }
2525 wfProfileOut( __METHOD__ );
2526 return false;
2527 }
2528
2529 /**
2530 * Return value of a magic variable (like PAGENAME)
2531 *
2532 * @private
2533 *
2534 * @param $index integer
2535 * @param $frame PPFrame
2536 *
2537 * @return string
2538 */
2539 function getVariableValue( $index, $frame = false ) {
2540 global $wgContLang, $wgSitename, $wgServer;
2541 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2542
2543 if ( is_null( $this->mTitle ) ) {
2544 // If no title set, bad things are going to happen
2545 // later. Title should always be set since this
2546 // should only be called in the middle of a parse
2547 // operation (but the unit-tests do funky stuff)
2548 throw new MWException( __METHOD__ . ' Should only be '
2549 . ' called while parsing (no title set)' );
2550 }
2551
2552 /**
2553 * Some of these require message or data lookups and can be
2554 * expensive to check many times.
2555 */
2556 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2557 if ( isset( $this->mVarCache[$index] ) ) {
2558 return $this->mVarCache[$index];
2559 }
2560 }
2561
2562 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2563 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2564
2565 # Use the time zone
2566 global $wgLocaltimezone;
2567 if ( isset( $wgLocaltimezone ) ) {
2568 $oldtz = date_default_timezone_get();
2569 date_default_timezone_set( $wgLocaltimezone );
2570 }
2571
2572 $localTimestamp = date( 'YmdHis', $ts );
2573 $localMonth = date( 'm', $ts );
2574 $localMonth1 = date( 'n', $ts );
2575 $localMonthName = date( 'n', $ts );
2576 $localDay = date( 'j', $ts );
2577 $localDay2 = date( 'd', $ts );
2578 $localDayOfWeek = date( 'w', $ts );
2579 $localWeek = date( 'W', $ts );
2580 $localYear = date( 'Y', $ts );
2581 $localHour = date( 'H', $ts );
2582 if ( isset( $wgLocaltimezone ) ) {
2583 date_default_timezone_set( $oldtz );
2584 }
2585
2586 $pageLang = $this->getFunctionLang();
2587
2588 switch ( $index ) {
2589 case 'currentmonth':
2590 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2591 break;
2592 case 'currentmonth1':
2593 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2594 break;
2595 case 'currentmonthname':
2596 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2597 break;
2598 case 'currentmonthnamegen':
2599 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2600 break;
2601 case 'currentmonthabbrev':
2602 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2603 break;
2604 case 'currentday':
2605 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2606 break;
2607 case 'currentday2':
2608 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2609 break;
2610 case 'localmonth':
2611 $value = $pageLang->formatNum( $localMonth );
2612 break;
2613 case 'localmonth1':
2614 $value = $pageLang->formatNum( $localMonth1 );
2615 break;
2616 case 'localmonthname':
2617 $value = $pageLang->getMonthName( $localMonthName );
2618 break;
2619 case 'localmonthnamegen':
2620 $value = $pageLang->getMonthNameGen( $localMonthName );
2621 break;
2622 case 'localmonthabbrev':
2623 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2624 break;
2625 case 'localday':
2626 $value = $pageLang->formatNum( $localDay );
2627 break;
2628 case 'localday2':
2629 $value = $pageLang->formatNum( $localDay2 );
2630 break;
2631 case 'pagename':
2632 $value = wfEscapeWikiText( $this->mTitle->getText() );
2633 break;
2634 case 'pagenamee':
2635 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2636 break;
2637 case 'fullpagename':
2638 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2639 break;
2640 case 'fullpagenamee':
2641 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2642 break;
2643 case 'subpagename':
2644 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2645 break;
2646 case 'subpagenamee':
2647 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2648 break;
2649 case 'basepagename':
2650 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2651 break;
2652 case 'basepagenamee':
2653 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ) );
2654 break;
2655 case 'talkpagename':
2656 if ( $this->mTitle->canTalk() ) {
2657 $talkPage = $this->mTitle->getTalkPage();
2658 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2659 } else {
2660 $value = '';
2661 }
2662 break;
2663 case 'talkpagenamee':
2664 if ( $this->mTitle->canTalk() ) {
2665 $talkPage = $this->mTitle->getTalkPage();
2666 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2667 } else {
2668 $value = '';
2669 }
2670 break;
2671 case 'subjectpagename':
2672 $subjPage = $this->mTitle->getSubjectPage();
2673 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2674 break;
2675 case 'subjectpagenamee':
2676 $subjPage = $this->mTitle->getSubjectPage();
2677 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2678 break;
2679 case 'revisionid':
2680 # Let the edit saving system know we should parse the page
2681 # *after* a revision ID has been assigned.
2682 $this->mOutput->setFlag( 'vary-revision' );
2683 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2684 $value = $this->mRevisionId;
2685 break;
2686 case 'revisionday':
2687 # Let the edit saving system know we should parse the page
2688 # *after* a revision ID has been assigned. This is for null edits.
2689 $this->mOutput->setFlag( 'vary-revision' );
2690 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2691 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2692 break;
2693 case 'revisionday2':
2694 # Let the edit saving system know we should parse the page
2695 # *after* a revision ID has been assigned. This is for null edits.
2696 $this->mOutput->setFlag( 'vary-revision' );
2697 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2698 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2699 break;
2700 case 'revisionmonth':
2701 # Let the edit saving system know we should parse the page
2702 # *after* a revision ID has been assigned. This is for null edits.
2703 $this->mOutput->setFlag( 'vary-revision' );
2704 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2705 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2706 break;
2707 case 'revisionmonth1':
2708 # Let the edit saving system know we should parse the page
2709 # *after* a revision ID has been assigned. This is for null edits.
2710 $this->mOutput->setFlag( 'vary-revision' );
2711 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2712 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2713 break;
2714 case 'revisionyear':
2715 # Let the edit saving system know we should parse the page
2716 # *after* a revision ID has been assigned. This is for null edits.
2717 $this->mOutput->setFlag( 'vary-revision' );
2718 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2719 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2720 break;
2721 case 'revisiontimestamp':
2722 # Let the edit saving system know we should parse the page
2723 # *after* a revision ID has been assigned. This is for null edits.
2724 $this->mOutput->setFlag( 'vary-revision' );
2725 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2726 $value = $this->getRevisionTimestamp();
2727 break;
2728 case 'revisionuser':
2729 # Let the edit saving system know we should parse the page
2730 # *after* a revision ID has been assigned. This is for null edits.
2731 $this->mOutput->setFlag( 'vary-revision' );
2732 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2733 $value = $this->getRevisionUser();
2734 break;
2735 case 'namespace':
2736 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2737 break;
2738 case 'namespacee':
2739 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2740 break;
2741 case 'talkspace':
2742 $value = $this->mTitle->canTalk() ? str_replace( '_',' ',$this->mTitle->getTalkNsText() ) : '';
2743 break;
2744 case 'talkspacee':
2745 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2746 break;
2747 case 'subjectspace':
2748 $value = $this->mTitle->getSubjectNsText();
2749 break;
2750 case 'subjectspacee':
2751 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2752 break;
2753 case 'currentdayname':
2754 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2755 break;
2756 case 'currentyear':
2757 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2758 break;
2759 case 'currenttime':
2760 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2761 break;
2762 case 'currenthour':
2763 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2764 break;
2765 case 'currentweek':
2766 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2767 # int to remove the padding
2768 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2769 break;
2770 case 'currentdow':
2771 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2772 break;
2773 case 'localdayname':
2774 $value = $pageLang->getWeekdayName( $localDayOfWeek + 1 );
2775 break;
2776 case 'localyear':
2777 $value = $pageLang->formatNum( $localYear, true );
2778 break;
2779 case 'localtime':
2780 $value = $pageLang->time( $localTimestamp, false, false );
2781 break;
2782 case 'localhour':
2783 $value = $pageLang->formatNum( $localHour, true );
2784 break;
2785 case 'localweek':
2786 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2787 # int to remove the padding
2788 $value = $pageLang->formatNum( (int)$localWeek );
2789 break;
2790 case 'localdow':
2791 $value = $pageLang->formatNum( $localDayOfWeek );
2792 break;
2793 case 'numberofarticles':
2794 $value = $pageLang->formatNum( SiteStats::articles() );
2795 break;
2796 case 'numberoffiles':
2797 $value = $pageLang->formatNum( SiteStats::images() );
2798 break;
2799 case 'numberofusers':
2800 $value = $pageLang->formatNum( SiteStats::users() );
2801 break;
2802 case 'numberofactiveusers':
2803 $value = $pageLang->formatNum( SiteStats::activeUsers() );
2804 break;
2805 case 'numberofpages':
2806 $value = $pageLang->formatNum( SiteStats::pages() );
2807 break;
2808 case 'numberofadmins':
2809 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2810 break;
2811 case 'numberofedits':
2812 $value = $pageLang->formatNum( SiteStats::edits() );
2813 break;
2814 case 'numberofviews':
2815 $value = $pageLang->formatNum( SiteStats::views() );
2816 break;
2817 case 'currenttimestamp':
2818 $value = wfTimestamp( TS_MW, $ts );
2819 break;
2820 case 'localtimestamp':
2821 $value = $localTimestamp;
2822 break;
2823 case 'currentversion':
2824 $value = SpecialVersion::getVersion();
2825 break;
2826 case 'articlepath':
2827 return $wgArticlePath;
2828 case 'sitename':
2829 return $wgSitename;
2830 case 'server':
2831 return $wgServer;
2832 case 'servername':
2833 $serverParts = wfParseUrl( $wgServer );
2834 return $serverParts && isset( $serverParts['host'] ) ? $serverParts['host'] : $wgServer;
2835 case 'scriptpath':
2836 return $wgScriptPath;
2837 case 'stylepath':
2838 return $wgStylePath;
2839 case 'directionmark':
2840 return $pageLang->getDirMark();
2841 case 'contentlanguage':
2842 global $wgLanguageCode;
2843 return $wgLanguageCode;
2844 default:
2845 $ret = null;
2846 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) ) {
2847 return $ret;
2848 } else {
2849 return null;
2850 }
2851 }
2852
2853 if ( $index ) {
2854 $this->mVarCache[$index] = $value;
2855 }
2856
2857 return $value;
2858 }
2859
2860 /**
2861 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2862 *
2863 * @private
2864 */
2865 function initialiseVariables() {
2866 wfProfileIn( __METHOD__ );
2867 $variableIDs = MagicWord::getVariableIDs();
2868 $substIDs = MagicWord::getSubstIDs();
2869
2870 $this->mVariables = new MagicWordArray( $variableIDs );
2871 $this->mSubstWords = new MagicWordArray( $substIDs );
2872 wfProfileOut( __METHOD__ );
2873 }
2874
2875 /**
2876 * Preprocess some wikitext and return the document tree.
2877 * This is the ghost of replace_variables().
2878 *
2879 * @param $text String: The text to parse
2880 * @param $flags Integer: bitwise combination of:
2881 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2882 * included. Default is to assume a direct page view.
2883 *
2884 * The generated DOM tree must depend only on the input text and the flags.
2885 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2886 *
2887 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2888 * change in the DOM tree for a given text, must be passed through the section identifier
2889 * in the section edit link and thus back to extractSections().
2890 *
2891 * The output of this function is currently only cached in process memory, but a persistent
2892 * cache may be implemented at a later date which takes further advantage of these strict
2893 * dependency requirements.
2894 *
2895 * @private
2896 *
2897 * @return PPNode
2898 */
2899 function preprocessToDom( $text, $flags = 0 ) {
2900 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2901 return $dom;
2902 }
2903
2904 /**
2905 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2906 *
2907 * @param $s string
2908 *
2909 * @return array
2910 */
2911 public static function splitWhitespace( $s ) {
2912 $ltrimmed = ltrim( $s );
2913 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2914 $trimmed = rtrim( $ltrimmed );
2915 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2916 if ( $diff > 0 ) {
2917 $w2 = substr( $ltrimmed, -$diff );
2918 } else {
2919 $w2 = '';
2920 }
2921 return array( $w1, $trimmed, $w2 );
2922 }
2923
2924 /**
2925 * Replace magic variables, templates, and template arguments
2926 * with the appropriate text. Templates are substituted recursively,
2927 * taking care to avoid infinite loops.
2928 *
2929 * Note that the substitution depends on value of $mOutputType:
2930 * self::OT_WIKI: only {{subst:}} templates
2931 * self::OT_PREPROCESS: templates but not extension tags
2932 * self::OT_HTML: all templates and extension tags
2933 *
2934 * @param $text String the text to transform
2935 * @param $frame PPFrame Object describing the arguments passed to the template.
2936 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2937 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2938 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
2939 * @private
2940 *
2941 * @return string
2942 */
2943 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2944 # Is there any text? Also, Prevent too big inclusions!
2945 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2946 return $text;
2947 }
2948 wfProfileIn( __METHOD__ );
2949
2950 if ( $frame === false ) {
2951 $frame = $this->getPreprocessor()->newFrame();
2952 } elseif ( !( $frame instanceof PPFrame ) ) {
2953 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2954 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2955 }
2956
2957 $dom = $this->preprocessToDom( $text );
2958 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2959 $text = $frame->expand( $dom, $flags );
2960
2961 wfProfileOut( __METHOD__ );
2962 return $text;
2963 }
2964
2965 /**
2966 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2967 *
2968 * @param $args array
2969 *
2970 * @return array
2971 */
2972 static function createAssocArgs( $args ) {
2973 $assocArgs = array();
2974 $index = 1;
2975 foreach ( $args as $arg ) {
2976 $eqpos = strpos( $arg, '=' );
2977 if ( $eqpos === false ) {
2978 $assocArgs[$index++] = $arg;
2979 } else {
2980 $name = trim( substr( $arg, 0, $eqpos ) );
2981 $value = trim( substr( $arg, $eqpos+1 ) );
2982 if ( $value === false ) {
2983 $value = '';
2984 }
2985 if ( $name !== false ) {
2986 $assocArgs[$name] = $value;
2987 }
2988 }
2989 }
2990
2991 return $assocArgs;
2992 }
2993
2994 /**
2995 * Warn the user when a parser limitation is reached
2996 * Will warn at most once the user per limitation type
2997 *
2998 * @param $limitationType String: should be one of:
2999 * 'expensive-parserfunction' (corresponding messages:
3000 * 'expensive-parserfunction-warning',
3001 * 'expensive-parserfunction-category')
3002 * 'post-expand-template-argument' (corresponding messages:
3003 * 'post-expand-template-argument-warning',
3004 * 'post-expand-template-argument-category')
3005 * 'post-expand-template-inclusion' (corresponding messages:
3006 * 'post-expand-template-inclusion-warning',
3007 * 'post-expand-template-inclusion-category')
3008 * @param $current Current value
3009 * @param $max Maximum allowed, when an explicit limit has been
3010 * exceeded, provide the values (optional)
3011 */
3012 function limitationWarn( $limitationType, $current=null, $max=null) {
3013 # does no harm if $current and $max are present but are unnecessary for the message
3014 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3015 $this->mOutput->addWarning( $warning );
3016 $this->addTrackingCategory( "$limitationType-category" );
3017 }
3018
3019 /**
3020 * Return the text of a template, after recursively
3021 * replacing any variables or templates within the template.
3022 *
3023 * @param $piece Array: the parts of the template
3024 * $piece['title']: the title, i.e. the part before the |
3025 * $piece['parts']: the parameter array
3026 * $piece['lineStart']: whether the brace was at the start of a line
3027 * @param $frame PPFrame The current frame, contains template arguments
3028 * @return String: the text of the template
3029 * @private
3030 */
3031 function braceSubstitution( $piece, $frame ) {
3032 global $wgNonincludableNamespaces;
3033 wfProfileIn( __METHOD__ );
3034 wfProfileIn( __METHOD__.'-setup' );
3035
3036 # Flags
3037 $found = false; # $text has been filled
3038 $nowiki = false; # wiki markup in $text should be escaped
3039 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3040 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3041 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3042 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3043
3044 # Title object, where $text came from
3045 $title = false;
3046
3047 # $part1 is the bit before the first |, and must contain only title characters.
3048 # Various prefixes will be stripped from it later.
3049 $titleWithSpaces = $frame->expand( $piece['title'] );
3050 $part1 = trim( $titleWithSpaces );
3051 $titleText = false;
3052
3053 # Original title text preserved for various purposes
3054 $originalTitle = $part1;
3055
3056 # $args is a list of argument nodes, starting from index 0, not including $part1
3057 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3058 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
3059 wfProfileOut( __METHOD__.'-setup' );
3060
3061 $titleProfileIn = null; // profile templates
3062
3063 # SUBST
3064 wfProfileIn( __METHOD__.'-modifiers' );
3065 if ( !$found ) {
3066
3067 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3068
3069 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3070 # Decide whether to expand template or keep wikitext as-is.
3071 if ( $this->ot['wiki'] ) {
3072 if ( $substMatch === false ) {
3073 $literal = true; # literal when in PST with no prefix
3074 } else {
3075 $literal = false; # expand when in PST with subst: or safesubst:
3076 }
3077 } else {
3078 if ( $substMatch == 'subst' ) {
3079 $literal = true; # literal when not in PST with plain subst:
3080 } else {
3081 $literal = false; # expand when not in PST with safesubst: or no prefix
3082 }
3083 }
3084 if ( $literal ) {
3085 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3086 $isLocalObj = true;
3087 $found = true;
3088 }
3089 }
3090
3091 # Variables
3092 if ( !$found && $args->getLength() == 0 ) {
3093 $id = $this->mVariables->matchStartToEnd( $part1 );
3094 if ( $id !== false ) {
3095 $text = $this->getVariableValue( $id, $frame );
3096 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3097 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3098 }
3099 $found = true;
3100 }
3101 }
3102
3103 # MSG, MSGNW and RAW
3104 if ( !$found ) {
3105 # Check for MSGNW:
3106 $mwMsgnw = MagicWord::get( 'msgnw' );
3107 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3108 $nowiki = true;
3109 } else {
3110 # Remove obsolete MSG:
3111 $mwMsg = MagicWord::get( 'msg' );
3112 $mwMsg->matchStartAndRemove( $part1 );
3113 }
3114
3115 # Check for RAW:
3116 $mwRaw = MagicWord::get( 'raw' );
3117 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3118 $forceRawInterwiki = true;
3119 }
3120 }
3121 wfProfileOut( __METHOD__.'-modifiers' );
3122
3123 # Parser functions
3124 if ( !$found ) {
3125 wfProfileIn( __METHOD__ . '-pfunc' );
3126
3127 $colonPos = strpos( $part1, ':' );
3128 if ( $colonPos !== false ) {
3129 # Case sensitive functions
3130 $function = substr( $part1, 0, $colonPos );
3131 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3132 $function = $this->mFunctionSynonyms[1][$function];
3133 } else {
3134 # Case insensitive functions
3135 $function = $this->getFunctionLang()->lc( $function );
3136 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3137 $function = $this->mFunctionSynonyms[0][$function];
3138 } else {
3139 $function = false;
3140 }
3141 }
3142 if ( $function ) {
3143 wfProfileIn( __METHOD__ . '-pfunc-' . $function );
3144 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3145 $initialArgs = array( &$this );
3146 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3147 if ( $flags & SFH_OBJECT_ARGS ) {
3148 # Add a frame parameter, and pass the arguments as an array
3149 $allArgs = $initialArgs;
3150 $allArgs[] = $frame;
3151 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3152 $funcArgs[] = $args->item( $i );
3153 }
3154 $allArgs[] = $funcArgs;
3155 } else {
3156 # Convert arguments to plain text
3157 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3158 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3159 }
3160 $allArgs = array_merge( $initialArgs, $funcArgs );
3161 }
3162
3163 # Workaround for PHP bug 35229 and similar
3164 if ( !is_callable( $callback ) ) {
3165 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3166 wfProfileOut( __METHOD__ . '-pfunc' );
3167 wfProfileOut( __METHOD__ );
3168 throw new MWException( "Tag hook for $function is not callable\n" );
3169 }
3170 $result = call_user_func_array( $callback, $allArgs );
3171 $found = true;
3172 $noparse = true;
3173 $preprocessFlags = 0;
3174
3175 if ( is_array( $result ) ) {
3176 if ( isset( $result[0] ) ) {
3177 $text = $result[0];
3178 unset( $result[0] );
3179 }
3180
3181 # Extract flags into the local scope
3182 # This allows callers to set flags such as nowiki, found, etc.
3183 extract( $result );
3184 } else {
3185 $text = $result;
3186 }
3187 if ( !$noparse ) {
3188 $text = $this->preprocessToDom( $text, $preprocessFlags );
3189 $isChildObj = true;
3190 }
3191 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3192 }
3193 }
3194 wfProfileOut( __METHOD__ . '-pfunc' );
3195 }
3196
3197 # Finish mangling title and then check for loops.
3198 # Set $title to a Title object and $titleText to the PDBK
3199 if ( !$found ) {
3200 $ns = NS_TEMPLATE;
3201 # Split the title into page and subpage
3202 $subpage = '';
3203 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3204 if ( $subpage !== '' ) {
3205 $ns = $this->mTitle->getNamespace();
3206 }
3207 $title = Title::newFromText( $part1, $ns );
3208 if ( $title ) {
3209 $titleText = $title->getPrefixedText();
3210 # Check for language variants if the template is not found
3211 if ( $this->getFunctionLang()->hasVariants() && $title->getArticleID() == 0 ) {
3212 $this->getFunctionLang()->findVariantLink( $part1, $title, true );
3213 }
3214 # Do recursion depth check
3215 $limit = $this->mOptions->getMaxTemplateDepth();
3216 if ( $frame->depth >= $limit ) {
3217 $found = true;
3218 $text = '<span class="error">'
3219 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3220 . '</span>';
3221 }
3222 }
3223 }
3224
3225 # Load from database
3226 if ( !$found && $title ) {
3227 $titleProfileIn = __METHOD__ . "-title-" . $title->getDBKey();
3228 wfProfileIn( $titleProfileIn ); // template in
3229 wfProfileIn( __METHOD__ . '-loadtpl' );
3230 if ( !$title->isExternal() ) {
3231 if ( $title->isSpecialPage()
3232 && $this->mOptions->getAllowSpecialInclusion()
3233 && $this->ot['html'] )
3234 {
3235 // Pass the template arguments as URL parameters.
3236 // "uselang" will have no effect since the Language object
3237 // is forced to the one defined in ParserOptions.
3238 $pageArgs = array();
3239 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3240 $bits = $args->item( $i )->splitArg();
3241 if ( strval( $bits['index'] ) === '' ) {
3242 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3243 $value = trim( $frame->expand( $bits['value'] ) );
3244 $pageArgs[$name] = $value;
3245 }
3246 }
3247
3248 // Create a new context to execute the special page
3249 $context = new RequestContext;
3250 $context->setTitle( $title );
3251 $context->setRequest( new FauxRequest( $pageArgs ) );
3252 $context->setUser( $this->getUser() );
3253 $context->setLang( $this->mOptions->getUserLangObj() );
3254 $ret = SpecialPageFactory::capturePath( $title, $context );
3255 if ( $ret ) {
3256 $text = $context->getOutput()->getHTML();
3257 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3258 $found = true;
3259 $isHTML = true;
3260 $this->disableCache();
3261 }
3262 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3263 $found = false; # access denied
3264 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
3265 } else {
3266 list( $text, $title ) = $this->getTemplateDom( $title );
3267 if ( $text !== false ) {
3268 $found = true;
3269 $isChildObj = true;
3270 }
3271 }
3272
3273 # If the title is valid but undisplayable, make a link to it
3274 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3275 $text = "[[:$titleText]]";
3276 $found = true;
3277 }
3278 } elseif ( $title->isTrans() ) {
3279 # Interwiki transclusion
3280 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3281 $text = $this->interwikiTransclude( $title, 'render' );
3282 $isHTML = true;
3283 } else {
3284 $text = $this->interwikiTransclude( $title, 'raw' );
3285 # Preprocess it like a template
3286 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3287 $isChildObj = true;
3288 }
3289 $found = true;
3290 }
3291
3292 # Do infinite loop check
3293 # This has to be done after redirect resolution to avoid infinite loops via redirects
3294 if ( !$frame->loopCheck( $title ) ) {
3295 $found = true;
3296 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3297 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
3298 }
3299 wfProfileOut( __METHOD__ . '-loadtpl' );
3300 }
3301
3302 # If we haven't found text to substitute by now, we're done
3303 # Recover the source wikitext and return it
3304 if ( !$found ) {
3305 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3306 if ( $titleProfileIn ) {
3307 wfProfileOut( $titleProfileIn ); // template out
3308 }
3309 wfProfileOut( __METHOD__ );
3310 return array( 'object' => $text );
3311 }
3312
3313 # Expand DOM-style return values in a child frame
3314 if ( $isChildObj ) {
3315 # Clean up argument array
3316 $newFrame = $frame->newChild( $args, $title );
3317
3318 if ( $nowiki ) {
3319 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3320 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3321 # Expansion is eligible for the empty-frame cache
3322 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3323 $text = $this->mTplExpandCache[$titleText];
3324 } else {
3325 $text = $newFrame->expand( $text );
3326 $this->mTplExpandCache[$titleText] = $text;
3327 }
3328 } else {
3329 # Uncached expansion
3330 $text = $newFrame->expand( $text );
3331 }
3332 }
3333 if ( $isLocalObj && $nowiki ) {
3334 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3335 $isLocalObj = false;
3336 }
3337
3338 if ( $titleProfileIn ) {
3339 wfProfileOut( $titleProfileIn ); // template out
3340 }
3341
3342 # Replace raw HTML by a placeholder
3343 # Add a blank line preceding, to prevent it from mucking up
3344 # immediately preceding headings
3345 if ( $isHTML ) {
3346 $text = "\n\n" . $this->insertStripItem( $text );
3347 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3348 # Escape nowiki-style return values
3349 $text = wfEscapeWikiText( $text );
3350 } elseif ( is_string( $text )
3351 && !$piece['lineStart']
3352 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3353 {
3354 # Bug 529: if the template begins with a table or block-level
3355 # element, it should be treated as beginning a new line.
3356 # This behaviour is somewhat controversial.
3357 $text = "\n" . $text;
3358 }
3359
3360 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3361 # Error, oversize inclusion
3362 if ( $titleText !== false ) {
3363 # Make a working, properly escaped link if possible (bug 23588)
3364 $text = "[[:$titleText]]";
3365 } else {
3366 # This will probably not be a working link, but at least it may
3367 # provide some hint of where the problem is
3368 preg_replace( '/^:/', '', $originalTitle );
3369 $text = "[[:$originalTitle]]";
3370 }
3371 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3372 $this->limitationWarn( 'post-expand-template-inclusion' );
3373 }
3374
3375 if ( $isLocalObj ) {
3376 $ret = array( 'object' => $text );
3377 } else {
3378 $ret = array( 'text' => $text );
3379 }
3380
3381 wfProfileOut( __METHOD__ );
3382 return $ret;
3383 }
3384
3385 /**
3386 * Get the semi-parsed DOM representation of a template with a given title,
3387 * and its redirect destination title. Cached.
3388 *
3389 * @param $title Title
3390 *
3391 * @return array
3392 */
3393 function getTemplateDom( $title ) {
3394 $cacheTitle = $title;
3395 $titleText = $title->getPrefixedDBkey();
3396
3397 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3398 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3399 $title = Title::makeTitle( $ns, $dbk );
3400 $titleText = $title->getPrefixedDBkey();
3401 }
3402 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3403 return array( $this->mTplDomCache[$titleText], $title );
3404 }
3405
3406 # Cache miss, go to the database
3407 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3408
3409 if ( $text === false ) {
3410 $this->mTplDomCache[$titleText] = false;
3411 return array( false, $title );
3412 }
3413
3414 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3415 $this->mTplDomCache[ $titleText ] = $dom;
3416
3417 if ( !$title->equals( $cacheTitle ) ) {
3418 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3419 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3420 }
3421
3422 return array( $dom, $title );
3423 }
3424
3425 /**
3426 * Fetch the unparsed text of a template and register a reference to it.
3427 * @param Title $title
3428 * @return Array ( string or false, Title )
3429 */
3430 function fetchTemplateAndTitle( $title ) {
3431 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3432 $stuff = call_user_func( $templateCb, $title, $this );
3433 $text = $stuff['text'];
3434 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3435 if ( isset( $stuff['deps'] ) ) {
3436 foreach ( $stuff['deps'] as $dep ) {
3437 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3438 }
3439 }
3440 return array( $text, $finalTitle );
3441 }
3442
3443 /**
3444 * Fetch the unparsed text of a template and register a reference to it.
3445 * @param Title $title
3446 * @return mixed string or false
3447 */
3448 function fetchTemplate( $title ) {
3449 $rv = $this->fetchTemplateAndTitle( $title );
3450 return $rv[0];
3451 }
3452
3453 /**
3454 * Static function to get a template
3455 * Can be overridden via ParserOptions::setTemplateCallback().
3456 *
3457 * @parma $title Title
3458 * @param $parser Parser
3459 *
3460 * @return array
3461 */
3462 static function statelessFetchTemplate( $title, $parser = false ) {
3463 $text = $skip = false;
3464 $finalTitle = $title;
3465 $deps = array();
3466
3467 # Loop to fetch the article, with up to 1 redirect
3468 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3469 # Give extensions a chance to select the revision instead
3470 $id = false; # Assume current
3471 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3472 array( $parser, $title, &$skip, &$id ) );
3473
3474 if ( $skip ) {
3475 $text = false;
3476 $deps[] = array(
3477 'title' => $title,
3478 'page_id' => $title->getArticleID(),
3479 'rev_id' => null
3480 );
3481 break;
3482 }
3483 # Get the revision
3484 $rev = $id
3485 ? Revision::newFromId( $id )
3486 : Revision::newFromTitle( $title );
3487 $rev_id = $rev ? $rev->getId() : 0;
3488 # If there is no current revision, there is no page
3489 if ( $id === false && !$rev ) {
3490 $linkCache = LinkCache::singleton();
3491 $linkCache->addBadLinkObj( $title );
3492 }
3493
3494 $deps[] = array(
3495 'title' => $title,
3496 'page_id' => $title->getArticleID(),
3497 'rev_id' => $rev_id );
3498 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3499 # We fetched a rev from a different title; register it too...
3500 $deps[] = array(
3501 'title' => $rev->getTitle(),
3502 'page_id' => $rev->getPage(),
3503 'rev_id' => $rev_id );
3504 }
3505
3506 if ( $rev ) {
3507 $text = $rev->getText();
3508 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3509 global $wgContLang;
3510 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3511 if ( !$message->exists() ) {
3512 $text = false;
3513 break;
3514 }
3515 $text = $message->plain();
3516 } else {
3517 break;
3518 }
3519 if ( $text === false ) {
3520 break;
3521 }
3522 # Redirect?
3523 $finalTitle = $title;
3524 $title = Title::newFromRedirect( $text );
3525 }
3526 return array(
3527 'text' => $text,
3528 'finalTitle' => $finalTitle,
3529 'deps' => $deps );
3530 }
3531
3532 /**
3533 * Fetch a file and its title and register a reference to it.
3534 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3535 * @param Title $title
3536 * @param Array $options Array of options to RepoGroup::findFile
3537 * @return File|false
3538 */
3539 function fetchFile( $title, $options = array() ) {
3540 $res = $this->fetchFileAndTitle( $title, $options );
3541 return $res[0];
3542 }
3543
3544 /**
3545 * Fetch a file and its title and register a reference to it.
3546 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3547 * @param Title $title
3548 * @param Array $options Array of options to RepoGroup::findFile
3549 * @return Array ( File or false, Title of file )
3550 */
3551 function fetchFileAndTitle( $title, $options = array() ) {
3552 if ( isset( $options['broken'] ) ) {
3553 $file = false; // broken thumbnail forced by hook
3554 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3555 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3556 } else { // get by (name,timestamp)
3557 $file = wfFindFile( $title, $options );
3558 }
3559 $time = $file ? $file->getTimestamp() : false;
3560 $sha1 = $file ? $file->getSha1() : false;
3561 # Register the file as a dependency...
3562 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3563 if ( $file && !$title->equals( $file->getTitle() ) ) {
3564 # Update fetched file title
3565 $title = $file->getTitle();
3566 if ( is_null( $file->getRedirectedTitle() ) ) {
3567 # This file was not a redirect, but the title does not match.
3568 # Register under the new name because otherwise the link will
3569 # get lost.
3570 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3571 }
3572 }
3573 return array( $file, $title );
3574 }
3575
3576 /**
3577 * Transclude an interwiki link.
3578 *
3579 * @param $title Title
3580 * @param $action
3581 *
3582 * @return string
3583 */
3584 function interwikiTransclude( $title, $action ) {
3585 global $wgEnableScaryTranscluding;
3586
3587 if ( !$wgEnableScaryTranscluding ) {
3588 return wfMsgForContent('scarytranscludedisabled');
3589 }
3590
3591 $url = $title->getFullUrl( "action=$action" );
3592
3593 if ( strlen( $url ) > 255 ) {
3594 return wfMsgForContent( 'scarytranscludetoolong' );
3595 }
3596 return $this->fetchScaryTemplateMaybeFromCache( $url );
3597 }
3598
3599 /**
3600 * @param $url string
3601 * @return Mixed|String
3602 */
3603 function fetchScaryTemplateMaybeFromCache( $url ) {
3604 global $wgTranscludeCacheExpiry;
3605 $dbr = wfGetDB( DB_SLAVE );
3606 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3607 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3608 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3609 if ( $obj ) {
3610 return $obj->tc_contents;
3611 }
3612
3613 $text = Http::get( $url );
3614 if ( !$text ) {
3615 return wfMsgForContent( 'scarytranscludefailed', $url );
3616 }
3617
3618 $dbw = wfGetDB( DB_MASTER );
3619 $dbw->replace( 'transcache', array('tc_url'), array(
3620 'tc_url' => $url,
3621 'tc_time' => $dbw->timestamp( time() ),
3622 'tc_contents' => $text)
3623 );
3624 return $text;
3625 }
3626
3627 /**
3628 * Triple brace replacement -- used for template arguments
3629 * @private
3630 *
3631 * @param $peice array
3632 * @param $frame PPFrame
3633 *
3634 * @return array
3635 */
3636 function argSubstitution( $piece, $frame ) {
3637 wfProfileIn( __METHOD__ );
3638
3639 $error = false;
3640 $parts = $piece['parts'];
3641 $nameWithSpaces = $frame->expand( $piece['title'] );
3642 $argName = trim( $nameWithSpaces );
3643 $object = false;
3644 $text = $frame->getArgument( $argName );
3645 if ( $text === false && $parts->getLength() > 0
3646 && (
3647 $this->ot['html']
3648 || $this->ot['pre']
3649 || ( $this->ot['wiki'] && $frame->isTemplate() )
3650 )
3651 ) {
3652 # No match in frame, use the supplied default
3653 $object = $parts->item( 0 )->getChildren();
3654 }
3655 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3656 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3657 $this->limitationWarn( 'post-expand-template-argument' );
3658 }
3659
3660 if ( $text === false && $object === false ) {
3661 # No match anywhere
3662 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3663 }
3664 if ( $error !== false ) {
3665 $text .= $error;
3666 }
3667 if ( $object !== false ) {
3668 $ret = array( 'object' => $object );
3669 } else {
3670 $ret = array( 'text' => $text );
3671 }
3672
3673 wfProfileOut( __METHOD__ );
3674 return $ret;
3675 }
3676
3677 /**
3678 * Return the text to be used for a given extension tag.
3679 * This is the ghost of strip().
3680 *
3681 * @param $params Associative array of parameters:
3682 * name PPNode for the tag name
3683 * attr PPNode for unparsed text where tag attributes are thought to be
3684 * attributes Optional associative array of parsed attributes
3685 * inner Contents of extension element
3686 * noClose Original text did not have a close tag
3687 * @param $frame PPFrame
3688 *
3689 * @return string
3690 */
3691 function extensionSubstitution( $params, $frame ) {
3692 $name = $frame->expand( $params['name'] );
3693 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3694 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3695 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3696
3697 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) &&
3698 ( $this->ot['html'] || $this->ot['pre'] );
3699 if ( $isFunctionTag ) {
3700 $markerType = 'none';
3701 } else {
3702 $markerType = 'general';
3703 }
3704 if ( $this->ot['html'] || $isFunctionTag ) {
3705 $name = strtolower( $name );
3706 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3707 if ( isset( $params['attributes'] ) ) {
3708 $attributes = $attributes + $params['attributes'];
3709 }
3710
3711 if ( isset( $this->mTagHooks[$name] ) ) {
3712 # Workaround for PHP bug 35229 and similar
3713 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3714 throw new MWException( "Tag hook for $name is not callable\n" );
3715 }
3716 $output = call_user_func_array( $this->mTagHooks[$name],
3717 array( $content, $attributes, $this, $frame ) );
3718 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3719 list( $callback, $flags ) = $this->mFunctionTagHooks[$name];
3720 if ( !is_callable( $callback ) ) {
3721 throw new MWException( "Tag hook for $name is not callable\n" );
3722 }
3723
3724 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3725 } else {
3726 $output = '<span class="error">Invalid tag extension name: ' .
3727 htmlspecialchars( $name ) . '</span>';
3728 }
3729
3730 if ( is_array( $output ) ) {
3731 # Extract flags to local scope (to override $markerType)
3732 $flags = $output;
3733 $output = $flags[0];
3734 unset( $flags[0] );
3735 extract( $flags );
3736 }
3737 } else {
3738 if ( is_null( $attrText ) ) {
3739 $attrText = '';
3740 }
3741 if ( isset( $params['attributes'] ) ) {
3742 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3743 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3744 htmlspecialchars( $attrValue ) . '"';
3745 }
3746 }
3747 if ( $content === null ) {
3748 $output = "<$name$attrText/>";
3749 } else {
3750 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3751 $output = "<$name$attrText>$content$close";
3752 }
3753 }
3754
3755 if ( $markerType === 'none' ) {
3756 return $output;
3757 } elseif ( $markerType === 'nowiki' ) {
3758 $this->mStripState->addNoWiki( $marker, $output );
3759 } elseif ( $markerType === 'general' ) {
3760 $this->mStripState->addGeneral( $marker, $output );
3761 } else {
3762 throw new MWException( __METHOD__.': invalid marker type' );
3763 }
3764 return $marker;
3765 }
3766
3767 /**
3768 * Increment an include size counter
3769 *
3770 * @param $type String: the type of expansion
3771 * @param $size Integer: the size of the text
3772 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3773 */
3774 function incrementIncludeSize( $type, $size ) {
3775 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3776 return false;
3777 } else {
3778 $this->mIncludeSizes[$type] += $size;
3779 return true;
3780 }
3781 }
3782
3783 /**
3784 * Increment the expensive function count
3785 *
3786 * @return Boolean: false if the limit has been exceeded
3787 */
3788 function incrementExpensiveFunctionCount() {
3789 global $wgExpensiveParserFunctionLimit;
3790 $this->mExpensiveFunctionCount++;
3791 if ( $this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit ) {
3792 return true;
3793 }
3794 return false;
3795 }
3796
3797 /**
3798 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3799 * Fills $this->mDoubleUnderscores, returns the modified text
3800 *
3801 * @param $text string
3802 *
3803 * @return string
3804 */
3805 function doDoubleUnderscore( $text ) {
3806 wfProfileIn( __METHOD__ );
3807
3808 # The position of __TOC__ needs to be recorded
3809 $mw = MagicWord::get( 'toc' );
3810 if ( $mw->match( $text ) ) {
3811 $this->mShowToc = true;
3812 $this->mForceTocPosition = true;
3813
3814 # Set a placeholder. At the end we'll fill it in with the TOC.
3815 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3816
3817 # Only keep the first one.
3818 $text = $mw->replace( '', $text );
3819 }
3820
3821 # Now match and remove the rest of them
3822 $mwa = MagicWord::getDoubleUnderscoreArray();
3823 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3824
3825 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3826 $this->mOutput->mNoGallery = true;
3827 }
3828 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3829 $this->mShowToc = false;
3830 }
3831 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3832 $this->addTrackingCategory( 'hidden-category-category' );
3833 }
3834 # (bug 8068) Allow control over whether robots index a page.
3835 #
3836 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3837 # is not desirable, the last one on the page should win.
3838 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
3839 $this->mOutput->setIndexPolicy( 'noindex' );
3840 $this->addTrackingCategory( 'noindex-category' );
3841 }
3842 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
3843 $this->mOutput->setIndexPolicy( 'index' );
3844 $this->addTrackingCategory( 'index-category' );
3845 }
3846
3847 # Cache all double underscores in the database
3848 foreach ( $this->mDoubleUnderscores as $key => $val ) {
3849 $this->mOutput->setProperty( $key, '' );
3850 }
3851
3852 wfProfileOut( __METHOD__ );
3853 return $text;
3854 }
3855
3856 /**
3857 * Add a tracking category, getting the title from a system message,
3858 * or print a debug message if the title is invalid.
3859 *
3860 * @param $msg String: message key
3861 * @return Boolean: whether the addition was successful
3862 */
3863 protected function addTrackingCategory( $msg ) {
3864 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) {
3865 wfDebug( __METHOD__.": Not adding tracking category $msg to special page!\n" );
3866 return false;
3867 }
3868 $cat = wfMsgForContent( $msg );
3869
3870 # Allow tracking categories to be disabled by setting them to "-"
3871 if ( $cat === '-' ) {
3872 return false;
3873 }
3874
3875 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
3876 if ( $containerCategory ) {
3877 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3878 return true;
3879 } else {
3880 wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" );
3881 return false;
3882 }
3883 }
3884
3885 /**
3886 * This function accomplishes several tasks:
3887 * 1) Auto-number headings if that option is enabled
3888 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3889 * 3) Add a Table of contents on the top for users who have enabled the option
3890 * 4) Auto-anchor headings
3891 *
3892 * It loops through all headlines, collects the necessary data, then splits up the
3893 * string and re-inserts the newly formatted headlines.
3894 *
3895 * @param $text String
3896 * @param $origText String: original, untouched wikitext
3897 * @param $isMain Boolean
3898 * @private
3899 */
3900 function formatHeadings( $text, $origText, $isMain=true ) {
3901 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3902
3903 # Inhibit editsection links if requested in the page
3904 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3905 $maybeShowEditLink = $showEditLink = false;
3906 } else {
3907 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3908 $showEditLink = $this->mOptions->getEditSection();
3909 }
3910 if ( $showEditLink ) {
3911 $this->mOutput->setEditSectionTokens( true );
3912 }
3913
3914 # Get all headlines for numbering them and adding funky stuff like [edit]
3915 # links - this is for later, but we need the number of headlines right now
3916 $matches = array();
3917 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3918
3919 # if there are fewer than 4 headlines in the article, do not show TOC
3920 # unless it's been explicitly enabled.
3921 $enoughToc = $this->mShowToc &&
3922 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
3923
3924 # Allow user to stipulate that a page should have a "new section"
3925 # link added via __NEWSECTIONLINK__
3926 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3927 $this->mOutput->setNewSection( true );
3928 }
3929
3930 # Allow user to remove the "new section"
3931 # link via __NONEWSECTIONLINK__
3932 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
3933 $this->mOutput->hideNewSection( true );
3934 }
3935
3936 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3937 # override above conditions and always show TOC above first header
3938 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3939 $this->mShowToc = true;
3940 $enoughToc = true;
3941 }
3942
3943 # headline counter
3944 $headlineCount = 0;
3945 $numVisible = 0;
3946
3947 # Ugh .. the TOC should have neat indentation levels which can be
3948 # passed to the skin functions. These are determined here
3949 $toc = '';
3950 $full = '';
3951 $head = array();
3952 $sublevelCount = array();
3953 $levelCount = array();
3954 $level = 0;
3955 $prevlevel = 0;
3956 $toclevel = 0;
3957 $prevtoclevel = 0;
3958 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3959 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3960 $oldType = $this->mOutputType;
3961 $this->setOutputType( self::OT_WIKI );
3962 $frame = $this->getPreprocessor()->newFrame();
3963 $root = $this->preprocessToDom( $origText );
3964 $node = $root->getFirstChild();
3965 $byteOffset = 0;
3966 $tocraw = array();
3967 $refers = array();
3968
3969 foreach ( $matches[3] as $headline ) {
3970 $isTemplate = false;
3971 $titleText = false;
3972 $sectionIndex = false;
3973 $numbering = '';
3974 $markerMatches = array();
3975 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3976 $serial = $markerMatches[1];
3977 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3978 $isTemplate = ( $titleText != $baseTitleText );
3979 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3980 }
3981
3982 if ( $toclevel ) {
3983 $prevlevel = $level;
3984 }
3985 $level = $matches[1][$headlineCount];
3986
3987 if ( $level > $prevlevel ) {
3988 # Increase TOC level
3989 $toclevel++;
3990 $sublevelCount[$toclevel] = 0;
3991 if ( $toclevel<$wgMaxTocLevel ) {
3992 $prevtoclevel = $toclevel;
3993 $toc .= Linker::tocIndent();
3994 $numVisible++;
3995 }
3996 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3997 # Decrease TOC level, find level to jump to
3998
3999 for ( $i = $toclevel; $i > 0; $i-- ) {
4000 if ( $levelCount[$i] == $level ) {
4001 # Found last matching level
4002 $toclevel = $i;
4003 break;
4004 } elseif ( $levelCount[$i] < $level ) {
4005 # Found first matching level below current level
4006 $toclevel = $i + 1;
4007 break;
4008 }
4009 }
4010 if ( $i == 0 ) {
4011 $toclevel = 1;
4012 }
4013 if ( $toclevel<$wgMaxTocLevel ) {
4014 if ( $prevtoclevel < $wgMaxTocLevel ) {
4015 # Unindent only if the previous toc level was shown :p
4016 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4017 $prevtoclevel = $toclevel;
4018 } else {
4019 $toc .= Linker::tocLineEnd();
4020 }
4021 }
4022 } else {
4023 # No change in level, end TOC line
4024 if ( $toclevel<$wgMaxTocLevel ) {
4025 $toc .= Linker::tocLineEnd();
4026 }
4027 }
4028
4029 $levelCount[$toclevel] = $level;
4030
4031 # count number of headlines for each level
4032 @$sublevelCount[$toclevel]++;
4033 $dot = 0;
4034 for( $i = 1; $i <= $toclevel; $i++ ) {
4035 if ( !empty( $sublevelCount[$i] ) ) {
4036 if ( $dot ) {
4037 $numbering .= '.';
4038 }
4039 $numbering .= $this->getFunctionLang()->formatNum( $sublevelCount[$i] );
4040 $dot = 1;
4041 }
4042 }
4043
4044 # The safe header is a version of the header text safe to use for links
4045 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4046 $safeHeadline = $this->mStripState->unstripBoth( $headline );
4047
4048 # Remove link placeholders by the link text.
4049 # <!--LINK number-->
4050 # turns into
4051 # link text with suffix
4052 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
4053
4054 # Strip out HTML (other than plain <sup> and <sub>: bug 8393, or <i>: bug 26375)
4055 $tocline = preg_replace(
4056 array( '#<(?!/?(sup|sub|i)).*?'.'>#', '#<(/?(sup|sub|i)).*?'.'>#' ),
4057 array( '', '<$1>' ),
4058 $safeHeadline
4059 );
4060 $tocline = trim( $tocline );
4061
4062 # For the anchor, strip out HTML-y stuff period
4063 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4064 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4065
4066 # Save headline for section edit hint before it's escaped
4067 $headlineHint = $safeHeadline;
4068
4069 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4070 # For reverse compatibility, provide an id that's
4071 # HTML4-compatible, like we used to.
4072 #
4073 # It may be worth noting, academically, that it's possible for
4074 # the legacy anchor to conflict with a non-legacy headline
4075 # anchor on the page. In this case likely the "correct" thing
4076 # would be to either drop the legacy anchors or make sure
4077 # they're numbered first. However, this would require people
4078 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4079 # manually, so let's not bother worrying about it.
4080 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4081 array( 'noninitial', 'legacy' ) );
4082 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4083
4084 if ( $legacyHeadline == $safeHeadline ) {
4085 # No reason to have both (in fact, we can't)
4086 $legacyHeadline = false;
4087 }
4088 } else {
4089 $legacyHeadline = false;
4090 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4091 'noninitial' );
4092 }
4093
4094 # HTML names must be case-insensitively unique (bug 10721).
4095 # This does not apply to Unicode characters per
4096 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4097 # @todo FIXME: We may be changing them depending on the current locale.
4098 $arrayKey = strtolower( $safeHeadline );
4099 if ( $legacyHeadline === false ) {
4100 $legacyArrayKey = false;
4101 } else {
4102 $legacyArrayKey = strtolower( $legacyHeadline );
4103 }
4104
4105 # count how many in assoc. array so we can track dupes in anchors
4106 if ( isset( $refers[$arrayKey] ) ) {
4107 $refers[$arrayKey]++;
4108 } else {
4109 $refers[$arrayKey] = 1;
4110 }
4111 if ( isset( $refers[$legacyArrayKey] ) ) {
4112 $refers[$legacyArrayKey]++;
4113 } else {
4114 $refers[$legacyArrayKey] = 1;
4115 }
4116
4117 # Don't number the heading if it is the only one (looks silly)
4118 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4119 # the two are different if the line contains a link
4120 $headline = $numbering . ' ' . $headline;
4121 }
4122
4123 # Create the anchor for linking from the TOC to the section
4124 $anchor = $safeHeadline;
4125 $legacyAnchor = $legacyHeadline;
4126 if ( $refers[$arrayKey] > 1 ) {
4127 $anchor .= '_' . $refers[$arrayKey];
4128 }
4129 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4130 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4131 }
4132 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4133 $toc .= Linker::tocLine( $anchor, $tocline,
4134 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4135 }
4136
4137 # Add the section to the section tree
4138 # Find the DOM node for this header
4139 while ( $node && !$isTemplate ) {
4140 if ( $node->getName() === 'h' ) {
4141 $bits = $node->splitHeading();
4142 if ( $bits['i'] == $sectionIndex ) {
4143 break;
4144 }
4145 }
4146 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4147 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4148 $node = $node->getNextSibling();
4149 }
4150 $tocraw[] = array(
4151 'toclevel' => $toclevel,
4152 'level' => $level,
4153 'line' => $tocline,
4154 'number' => $numbering,
4155 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4156 'fromtitle' => $titleText,
4157 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
4158 'anchor' => $anchor,
4159 );
4160
4161 # give headline the correct <h#> tag
4162 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4163 // Output edit section links as markers with styles that can be customized by skins
4164 if ( $isTemplate ) {
4165 # Put a T flag in the section identifier, to indicate to extractSections()
4166 # that sections inside <includeonly> should be counted.
4167 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4168 } else {
4169 $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint );
4170 }
4171 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4172 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4173 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4174 // so we don't have to worry about a user trying to input one of these markers directly.
4175 // We use a page and section attribute to stop the language converter from converting these important bits
4176 // of data, but put the headline hint inside a content block because the language converter is supposed to
4177 // be able to convert that piece of data.
4178 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4179 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4180 if ( isset($editlinkArgs[2]) ) {
4181 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4182 } else {
4183 $editlink .= '/>';
4184 }
4185 } else {
4186 $editlink = '';
4187 }
4188 $head[$headlineCount] = Linker::makeHeadline( $level,
4189 $matches['attrib'][$headlineCount], $anchor, $headline,
4190 $editlink, $legacyAnchor );
4191
4192 $headlineCount++;
4193 }
4194
4195 $this->setOutputType( $oldType );
4196
4197 # Never ever show TOC if no headers
4198 if ( $numVisible < 1 ) {
4199 $enoughToc = false;
4200 }
4201
4202 if ( $enoughToc ) {
4203 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4204 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4205 }
4206 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4207 $this->mOutput->setTOCHTML( $toc );
4208 }
4209
4210 if ( $isMain ) {
4211 $this->mOutput->setSections( $tocraw );
4212 }
4213
4214 # split up and insert constructed headlines
4215 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4216 $i = 0;
4217
4218 // build an array of document sections
4219 $sections = array();
4220 foreach ( $blocks as $block ) {
4221 // $head is zero-based, sections aren't.
4222 if ( empty( $head[$i - 1] ) ) {
4223 $sections[$i] = $block;
4224 } else {
4225 $sections[$i] = $head[$i - 1] . $block;
4226 }
4227
4228 /**
4229 * Send a hook, one per section.
4230 * The idea here is to be able to make section-level DIVs, but to do so in a
4231 * lower-impact, more correct way than r50769
4232 *
4233 * $this : caller
4234 * $section : the section number
4235 * &$sectionContent : ref to the content of the section
4236 * $showEditLinks : boolean describing whether this section has an edit link
4237 */
4238 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4239
4240 $i++;
4241 }
4242
4243 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4244 // append the TOC at the beginning
4245 // Top anchor now in skin
4246 $sections[0] = $sections[0] . $toc . "\n";
4247 }
4248
4249 $full .= join( '', $sections );
4250
4251 if ( $this->mForceTocPosition ) {
4252 return str_replace( '<!--MWTOC-->', $toc, $full );
4253 } else {
4254 return $full;
4255 }
4256 }
4257
4258 /**
4259 * Transform wiki markup when saving a page by doing \r\n -> \n
4260 * conversion, substitting signatures, {{subst:}} templates, etc.
4261 *
4262 * @param $text String: the text to transform
4263 * @param $title Title: the Title object for the current article
4264 * @param $user User: the User object describing the current user
4265 * @param $options ParserOptions: parsing options
4266 * @param $clearState Boolean: whether to clear the parser state first
4267 * @return String: the altered wiki markup
4268 */
4269 public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) {
4270 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4271 $this->setUser( $user );
4272
4273 $pairs = array(
4274 "\r\n" => "\n",
4275 );
4276 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4277 if( $options->getPreSaveTransform() ) {
4278 $text = $this->pstPass2( $text, $user );
4279 }
4280 $text = $this->mStripState->unstripBoth( $text );
4281
4282 $this->setUser( null ); #Reset
4283
4284 return $text;
4285 }
4286
4287 /**
4288 * Pre-save transform helper function
4289 * @private
4290 *
4291 * @param $text string
4292 * @param $user User
4293 *
4294 * @return string
4295 */
4296 function pstPass2( $text, $user ) {
4297 global $wgContLang, $wgLocaltimezone;
4298
4299 # Note: This is the timestamp saved as hardcoded wikitext to
4300 # the database, we use $wgContLang here in order to give
4301 # everyone the same signature and use the default one rather
4302 # than the one selected in each user's preferences.
4303 # (see also bug 12815)
4304 $ts = $this->mOptions->getTimestamp();
4305 if ( isset( $wgLocaltimezone ) ) {
4306 $tz = $wgLocaltimezone;
4307 } else {
4308 $tz = date_default_timezone_get();
4309 }
4310
4311 $unixts = wfTimestamp( TS_UNIX, $ts );
4312 $oldtz = date_default_timezone_get();
4313 date_default_timezone_set( $tz );
4314 $ts = date( 'YmdHis', $unixts );
4315 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4316
4317 # Allow translation of timezones through wiki. date() can return
4318 # whatever crap the system uses, localised or not, so we cannot
4319 # ship premade translations.
4320 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4321 $msg = wfMessage( $key )->inContentLanguage();
4322 if ( $msg->exists() ) {
4323 $tzMsg = $msg->text();
4324 }
4325
4326 date_default_timezone_set( $oldtz );
4327
4328 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4329
4330 # Variable replacement
4331 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4332 $text = $this->replaceVariables( $text );
4333
4334 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4335 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4336
4337 # Signatures
4338 $sigText = $this->getUserSig( $user );
4339 $text = strtr( $text, array(
4340 '~~~~~' => $d,
4341 '~~~~' => "$sigText $d",
4342 '~~~' => $sigText
4343 ) );
4344
4345 # Context links: [[|name]] and [[name (context)|]]
4346 global $wgLegalTitleChars;
4347 $tc = "[$wgLegalTitleChars]";
4348 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4349
4350 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4351 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4352 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4353 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4354
4355 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4356 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4357 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4358 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4359
4360 $t = $this->mTitle->getText();
4361 $m = array();
4362 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4363 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4364 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4365 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4366 } else {
4367 # if there's no context, don't bother duplicating the title
4368 $text = preg_replace( $p2, '[[\\1]]', $text );
4369 }
4370
4371 # Trim trailing whitespace
4372 $text = rtrim( $text );
4373
4374 return $text;
4375 }
4376
4377 /**
4378 * Fetch the user's signature text, if any, and normalize to
4379 * validated, ready-to-insert wikitext.
4380 * If you have pre-fetched the nickname or the fancySig option, you can
4381 * specify them here to save a database query.
4382 * Do not reuse this parser instance after calling getUserSig(),
4383 * as it may have changed if it's the $wgParser.
4384 *
4385 * @param $user User
4386 * @param $nickname String|bool nickname to use or false to use user's default nickname
4387 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4388 * or null to use default value
4389 * @return string
4390 */
4391 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4392 global $wgMaxSigChars;
4393
4394 $username = $user->getName();
4395
4396 # If not given, retrieve from the user object.
4397 if ( $nickname === false )
4398 $nickname = $user->getOption( 'nickname' );
4399
4400 if ( is_null( $fancySig ) ) {
4401 $fancySig = $user->getBoolOption( 'fancysig' );
4402 }
4403
4404 $nickname = $nickname == null ? $username : $nickname;
4405
4406 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4407 $nickname = $username;
4408 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4409 } elseif ( $fancySig !== false ) {
4410 # Sig. might contain markup; validate this
4411 if ( $this->validateSig( $nickname ) !== false ) {
4412 # Validated; clean up (if needed) and return it
4413 return $this->cleanSig( $nickname, true );
4414 } else {
4415 # Failed to validate; fall back to the default
4416 $nickname = $username;
4417 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
4418 }
4419 }
4420
4421 # Make sure nickname doesnt get a sig in a sig
4422 $nickname = $this->cleanSigInSig( $nickname );
4423
4424 # If we're still here, make it a link to the user page
4425 $userText = wfEscapeWikiText( $username );
4426 $nickText = wfEscapeWikiText( $nickname );
4427 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4428
4429 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4430 }
4431
4432 /**
4433 * Check that the user's signature contains no bad XML
4434 *
4435 * @param $text String
4436 * @return mixed An expanded string, or false if invalid.
4437 */
4438 function validateSig( $text ) {
4439 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
4440 }
4441
4442 /**
4443 * Clean up signature text
4444 *
4445 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4446 * 2) Substitute all transclusions
4447 *
4448 * @param $text String
4449 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4450 * @return String: signature text
4451 */
4452 function cleanSig( $text, $parsing = false ) {
4453 if ( !$parsing ) {
4454 global $wgTitle;
4455 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4456 }
4457
4458 # Option to disable this feature
4459 if ( !$this->mOptions->getCleanSignatures() ) {
4460 return $text;
4461 }
4462
4463 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4464 # => Move this logic to braceSubstitution()
4465 $substWord = MagicWord::get( 'subst' );
4466 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4467 $substText = '{{' . $substWord->getSynonym( 0 );
4468
4469 $text = preg_replace( $substRegex, $substText, $text );
4470 $text = $this->cleanSigInSig( $text );
4471 $dom = $this->preprocessToDom( $text );
4472 $frame = $this->getPreprocessor()->newFrame();
4473 $text = $frame->expand( $dom );
4474
4475 if ( !$parsing ) {
4476 $text = $this->mStripState->unstripBoth( $text );
4477 }
4478
4479 return $text;
4480 }
4481
4482 /**
4483 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4484 *
4485 * @param $text String
4486 * @return String: signature text with /~{3,5}/ removed
4487 */
4488 function cleanSigInSig( $text ) {
4489 $text = preg_replace( '/~{3,5}/', '', $text );
4490 return $text;
4491 }
4492
4493 /**
4494 * Set up some variables which are usually set up in parse()
4495 * so that an external function can call some class members with confidence
4496 *
4497 * @param $title Title|null
4498 * @param $options ParserOptions
4499 * @param $outputType
4500 * @param $clearState bool
4501 */
4502 public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4503 $this->startParse( $title, $options, $outputType, $clearState );
4504 }
4505
4506 /**
4507 * @param $title Title|null
4508 * @param $options ParserOptions
4509 * @param $outputType
4510 * @param $clearState bool
4511 */
4512 private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4513 $this->setTitle( $title );
4514 $this->mOptions = $options;
4515 $this->setOutputType( $outputType );
4516 if ( $clearState ) {
4517 $this->clearState();
4518 }
4519 }
4520
4521 /**
4522 * Wrapper for preprocess()
4523 *
4524 * @param $text String: the text to preprocess
4525 * @param $options ParserOptions: options
4526 * @param $title Title object or null to use $wgTitle
4527 * @return String
4528 */
4529 public function transformMsg( $text, $options, $title = null ) {
4530 static $executing = false;
4531
4532 # Guard against infinite recursion
4533 if ( $executing ) {
4534 return $text;
4535 }
4536 $executing = true;
4537
4538 wfProfileIn( __METHOD__ );
4539 if ( !$title ) {
4540 global $wgTitle;
4541 $title = $wgTitle;
4542 }
4543 if ( !$title ) {
4544 # It's not uncommon having a null $wgTitle in scripts. See r80898
4545 # Create a ghost title in such case
4546 $title = Title::newFromText( 'Dwimmerlaik' );
4547 }
4548 $text = $this->preprocess( $text, $title, $options );
4549
4550 $executing = false;
4551 wfProfileOut( __METHOD__ );
4552 return $text;
4553 }
4554
4555 /**
4556 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4557 * The callback should have the following form:
4558 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4559 *
4560 * Transform and return $text. Use $parser for any required context, e.g. use
4561 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4562 *
4563 * Hooks may return extended information by returning an array, of which the
4564 * first numbered element (index 0) must be the return string, and all other
4565 * entries are extracted into local variables within an internal function
4566 * in the Parser class.
4567 *
4568 * This interface (introduced r61913) appears to be undocumented, but
4569 * 'markerName' is used by some core tag hooks to override which strip
4570 * array their results are placed in. **Use great caution if attempting
4571 * this interface, as it is not documented and injudicious use could smash
4572 * private variables.**
4573 *
4574 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4575 * @param $callback Mixed: the callback function (and object) to use for the tag
4576 * @return The old value of the mTagHooks array associated with the hook
4577 */
4578 public function setHook( $tag, $callback ) {
4579 $tag = strtolower( $tag );
4580 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4581 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4582 $this->mTagHooks[$tag] = $callback;
4583 if ( !in_array( $tag, $this->mStripList ) ) {
4584 $this->mStripList[] = $tag;
4585 }
4586
4587 return $oldVal;
4588 }
4589
4590 /**
4591 * As setHook(), but letting the contents be parsed.
4592 *
4593 * Transparent tag hooks are like regular XML-style tag hooks, except they
4594 * operate late in the transformation sequence, on HTML instead of wikitext.
4595 *
4596 * This is probably obsoleted by things dealing with parser frames?
4597 * The only extension currently using it is geoserver.
4598 *
4599 * @since 1.10
4600 * @todo better document or deprecate this
4601 *
4602 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4603 * @param $callback Mixed: the callback function (and object) to use for the tag
4604 * @return The old value of the mTagHooks array associated with the hook
4605 */
4606 function setTransparentTagHook( $tag, $callback ) {
4607 $tag = strtolower( $tag );
4608 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4609 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4610 $this->mTransparentTagHooks[$tag] = $callback;
4611
4612 return $oldVal;
4613 }
4614
4615 /**
4616 * Remove all tag hooks
4617 */
4618 function clearTagHooks() {
4619 $this->mTagHooks = array();
4620 $this->mStripList = $this->mDefaultStripList;
4621 }
4622
4623 /**
4624 * Create a function, e.g. {{sum:1|2|3}}
4625 * The callback function should have the form:
4626 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4627 *
4628 * Or with SFH_OBJECT_ARGS:
4629 * function myParserFunction( $parser, $frame, $args ) { ... }
4630 *
4631 * The callback may either return the text result of the function, or an array with the text
4632 * in element 0, and a number of flags in the other elements. The names of the flags are
4633 * specified in the keys. Valid flags are:
4634 * found The text returned is valid, stop processing the template. This
4635 * is on by default.
4636 * nowiki Wiki markup in the return value should be escaped
4637 * isHTML The returned text is HTML, armour it against wikitext transformation
4638 *
4639 * @param $id String: The magic word ID
4640 * @param $callback Mixed: the callback function (and object) to use
4641 * @param $flags Integer: a combination of the following flags:
4642 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4643 *
4644 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4645 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4646 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4647 * the arguments, and to control the way they are expanded.
4648 *
4649 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4650 * arguments, for instance:
4651 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4652 *
4653 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4654 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4655 * working if/when this is changed.
4656 *
4657 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4658 * expansion.
4659 *
4660 * Please read the documentation in includes/parser/Preprocessor.php for more information
4661 * about the methods available in PPFrame and PPNode.
4662 *
4663 * @return The old callback function for this name, if any
4664 */
4665 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4666 global $wgContLang;
4667
4668 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4669 $this->mFunctionHooks[$id] = array( $callback, $flags );
4670
4671 # Add to function cache
4672 $mw = MagicWord::get( $id );
4673 if ( !$mw )
4674 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4675
4676 $synonyms = $mw->getSynonyms();
4677 $sensitive = intval( $mw->isCaseSensitive() );
4678
4679 foreach ( $synonyms as $syn ) {
4680 # Case
4681 if ( !$sensitive ) {
4682 $syn = $wgContLang->lc( $syn );
4683 }
4684 # Add leading hash
4685 if ( !( $flags & SFH_NO_HASH ) ) {
4686 $syn = '#' . $syn;
4687 }
4688 # Remove trailing colon
4689 if ( substr( $syn, -1, 1 ) === ':' ) {
4690 $syn = substr( $syn, 0, -1 );
4691 }
4692 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4693 }
4694 return $oldVal;
4695 }
4696
4697 /**
4698 * Get all registered function hook identifiers
4699 *
4700 * @return Array
4701 */
4702 function getFunctionHooks() {
4703 return array_keys( $this->mFunctionHooks );
4704 }
4705
4706 /**
4707 * Create a tag function, e.g. <test>some stuff</test>.
4708 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4709 * Unlike parser functions, their content is not preprocessed.
4710 */
4711 function setFunctionTagHook( $tag, $callback, $flags ) {
4712 $tag = strtolower( $tag );
4713 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4714 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4715 $this->mFunctionTagHooks[$tag] : null;
4716 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4717
4718 if ( !in_array( $tag, $this->mStripList ) ) {
4719 $this->mStripList[] = $tag;
4720 }
4721
4722 return $old;
4723 }
4724
4725 /**
4726 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4727 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4728 * Placeholders created in Skin::makeLinkObj()
4729 *
4730 * @param $text string
4731 * @param $options int
4732 *
4733 * @return array of link CSS classes, indexed by PDBK.
4734 */
4735 function replaceLinkHolders( &$text, $options = 0 ) {
4736 return $this->mLinkHolders->replace( $text );
4737 }
4738
4739 /**
4740 * Replace <!--LINK--> link placeholders with plain text of links
4741 * (not HTML-formatted).
4742 *
4743 * @param $text String
4744 * @return String
4745 */
4746 function replaceLinkHoldersText( $text ) {
4747 return $this->mLinkHolders->replaceText( $text );
4748 }
4749
4750 /**
4751 * Renders an image gallery from a text with one line per image.
4752 * text labels may be given by using |-style alternative text. E.g.
4753 * Image:one.jpg|The number "1"
4754 * Image:tree.jpg|A tree
4755 * given as text will return the HTML of a gallery with two images,
4756 * labeled 'The number "1"' and
4757 * 'A tree'.
4758 *
4759 * @param string $text
4760 * @param array $params
4761 * @return string HTML
4762 */
4763 function renderImageGallery( $text, $params ) {
4764 $ig = new ImageGallery();
4765 $ig->setContextTitle( $this->mTitle );
4766 $ig->setShowBytes( false );
4767 $ig->setShowFilename( false );
4768 $ig->setParser( $this );
4769 $ig->setHideBadImages();
4770 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4771
4772 if ( isset( $params['showfilename'] ) ) {
4773 $ig->setShowFilename( true );
4774 } else {
4775 $ig->setShowFilename( false );
4776 }
4777 if ( isset( $params['caption'] ) ) {
4778 $caption = $params['caption'];
4779 $caption = htmlspecialchars( $caption );
4780 $caption = $this->replaceInternalLinks( $caption );
4781 $ig->setCaptionHtml( $caption );
4782 }
4783 if ( isset( $params['perrow'] ) ) {
4784 $ig->setPerRow( $params['perrow'] );
4785 }
4786 if ( isset( $params['widths'] ) ) {
4787 $ig->setWidths( $params['widths'] );
4788 }
4789 if ( isset( $params['heights'] ) ) {
4790 $ig->setHeights( $params['heights'] );
4791 }
4792
4793 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4794
4795 $lines = StringUtils::explode( "\n", $text );
4796 foreach ( $lines as $line ) {
4797 # match lines like these:
4798 # Image:someimage.jpg|This is some image
4799 $matches = array();
4800 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4801 # Skip empty lines
4802 if ( count( $matches ) == 0 ) {
4803 continue;
4804 }
4805
4806 if ( strpos( $matches[0], '%' ) !== false ) {
4807 $matches[1] = rawurldecode( $matches[1] );
4808 }
4809 $title = Title::newFromText( $matches[1], NS_FILE );
4810 if ( is_null( $title ) ) {
4811 # Bogus title. Ignore these so we don't bomb out later.
4812 continue;
4813 }
4814
4815 $label = '';
4816 $alt = '';
4817 if ( isset( $matches[3] ) ) {
4818 // look for an |alt= definition while trying not to break existing
4819 // captions with multiple pipes (|) in it, until a more sensible grammar
4820 // is defined for images in galleries
4821
4822 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4823 $altmatches = StringUtils::explode('|', $matches[3]);
4824 $magicWordAlt = MagicWord::get( 'img_alt' );
4825
4826 foreach ( $altmatches as $altmatch ) {
4827 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch );
4828 if ( $match ) {
4829 $alt = $this->stripAltText( $match, false );
4830 }
4831 else {
4832 // concatenate all other pipes
4833 $label .= '|' . $altmatch;
4834 }
4835 }
4836 // remove the first pipe
4837 $label = substr( $label, 1 );
4838 }
4839
4840 $ig->add( $title, $label, $alt );
4841 }
4842 return $ig->toHTML();
4843 }
4844
4845 /**
4846 * @param $handler
4847 * @return array
4848 */
4849 function getImageParams( $handler ) {
4850 if ( $handler ) {
4851 $handlerClass = get_class( $handler );
4852 } else {
4853 $handlerClass = '';
4854 }
4855 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4856 # Initialise static lists
4857 static $internalParamNames = array(
4858 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4859 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4860 'bottom', 'text-bottom' ),
4861 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4862 'upright', 'border', 'link', 'alt' ),
4863 );
4864 static $internalParamMap;
4865 if ( !$internalParamMap ) {
4866 $internalParamMap = array();
4867 foreach ( $internalParamNames as $type => $names ) {
4868 foreach ( $names as $name ) {
4869 $magicName = str_replace( '-', '_', "img_$name" );
4870 $internalParamMap[$magicName] = array( $type, $name );
4871 }
4872 }
4873 }
4874
4875 # Add handler params
4876 $paramMap = $internalParamMap;
4877 if ( $handler ) {
4878 $handlerParamMap = $handler->getParamMap();
4879 foreach ( $handlerParamMap as $magic => $paramName ) {
4880 $paramMap[$magic] = array( 'handler', $paramName );
4881 }
4882 }
4883 $this->mImageParams[$handlerClass] = $paramMap;
4884 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4885 }
4886 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4887 }
4888
4889 /**
4890 * Parse image options text and use it to make an image
4891 *
4892 * @param $title Title
4893 * @param $options String
4894 * @param $holders LinkHolderArray|false
4895 * @return string HTML
4896 */
4897 function makeImage( $title, $options, $holders = false ) {
4898 # Check if the options text is of the form "options|alt text"
4899 # Options are:
4900 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4901 # * left no resizing, just left align. label is used for alt= only
4902 # * right same, but right aligned
4903 # * none same, but not aligned
4904 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4905 # * center center the image
4906 # * frame Keep original image size, no magnify-button.
4907 # * framed Same as "frame"
4908 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4909 # * upright reduce width for upright images, rounded to full __0 px
4910 # * border draw a 1px border around the image
4911 # * alt Text for HTML alt attribute (defaults to empty)
4912 # * link Set the target of the image link. Can be external, interwiki, or local
4913 # vertical-align values (no % or length right now):
4914 # * baseline
4915 # * sub
4916 # * super
4917 # * top
4918 # * text-top
4919 # * middle
4920 # * bottom
4921 # * text-bottom
4922
4923 $parts = StringUtils::explode( "|", $options );
4924
4925 # Give extensions a chance to select the file revision for us
4926 $options = array();
4927 $descQuery = false;
4928 wfRunHooks( 'BeforeParserFetchFileAndTitle',
4929 array( $this, $title, &$options, &$descQuery ) );
4930 # Fetch and register the file (file title may be different via hooks)
4931 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
4932
4933 # Get parameter map
4934 $handler = $file ? $file->getHandler() : false;
4935
4936 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4937
4938 if ( !$file ) {
4939 $this->addTrackingCategory( 'broken-file-category' );
4940 }
4941
4942 # Process the input parameters
4943 $caption = '';
4944 $params = array( 'frame' => array(), 'handler' => array(),
4945 'horizAlign' => array(), 'vertAlign' => array() );
4946 foreach ( $parts as $part ) {
4947 $part = trim( $part );
4948 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4949 $validated = false;
4950 if ( isset( $paramMap[$magicName] ) ) {
4951 list( $type, $paramName ) = $paramMap[$magicName];
4952
4953 # Special case; width and height come in one variable together
4954 if ( $type === 'handler' && $paramName === 'width' ) {
4955 $m = array();
4956 # (bug 13500) In both cases (width/height and width only),
4957 # permit trailing "px" for backward compatibility.
4958 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4959 $width = intval( $m[1] );
4960 $height = intval( $m[2] );
4961 if ( $handler->validateParam( 'width', $width ) ) {
4962 $params[$type]['width'] = $width;
4963 $validated = true;
4964 }
4965 if ( $handler->validateParam( 'height', $height ) ) {
4966 $params[$type]['height'] = $height;
4967 $validated = true;
4968 }
4969 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4970 $width = intval( $value );
4971 if ( $handler->validateParam( 'width', $width ) ) {
4972 $params[$type]['width'] = $width;
4973 $validated = true;
4974 }
4975 } # else no validation -- bug 13436
4976 } else {
4977 if ( $type === 'handler' ) {
4978 # Validate handler parameter
4979 $validated = $handler->validateParam( $paramName, $value );
4980 } else {
4981 # Validate internal parameters
4982 switch( $paramName ) {
4983 case 'manualthumb':
4984 case 'alt':
4985 # @todo FIXME: Possibly check validity here for
4986 # manualthumb? downstream behavior seems odd with
4987 # missing manual thumbs.
4988 $validated = true;
4989 $value = $this->stripAltText( $value, $holders );
4990 break;
4991 case 'link':
4992 $chars = self::EXT_LINK_URL_CLASS;
4993 $prots = $this->mUrlProtocols;
4994 if ( $value === '' ) {
4995 $paramName = 'no-link';
4996 $value = true;
4997 $validated = true;
4998 } elseif ( preg_match( "/^$prots/", $value ) ) {
4999 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
5000 $paramName = 'link-url';
5001 $this->mOutput->addExternalLink( $value );
5002 if ( $this->mOptions->getExternalLinkTarget() ) {
5003 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5004 }
5005 $validated = true;
5006 }
5007 } else {
5008 $linkTitle = Title::newFromText( $value );
5009 if ( $linkTitle ) {
5010 $paramName = 'link-title';
5011 $value = $linkTitle;
5012 $this->mOutput->addLink( $linkTitle );
5013 $validated = true;
5014 }
5015 }
5016 break;
5017 default:
5018 # Most other things appear to be empty or numeric...
5019 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5020 }
5021 }
5022
5023 if ( $validated ) {
5024 $params[$type][$paramName] = $value;
5025 }
5026 }
5027 }
5028 if ( !$validated ) {
5029 $caption = $part;
5030 }
5031 }
5032
5033 # Process alignment parameters
5034 if ( $params['horizAlign'] ) {
5035 $params['frame']['align'] = key( $params['horizAlign'] );
5036 }
5037 if ( $params['vertAlign'] ) {
5038 $params['frame']['valign'] = key( $params['vertAlign'] );
5039 }
5040
5041 $params['frame']['caption'] = $caption;
5042
5043 # Will the image be presented in a frame, with the caption below?
5044 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5045 isset( $params['frame']['framed'] ) ||
5046 isset( $params['frame']['thumbnail'] ) ||
5047 isset( $params['frame']['manualthumb'] );
5048
5049 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5050 # came to also set the caption, ordinary text after the image -- which
5051 # makes no sense, because that just repeats the text multiple times in
5052 # screen readers. It *also* came to set the title attribute.
5053 #
5054 # Now that we have an alt attribute, we should not set the alt text to
5055 # equal the caption: that's worse than useless, it just repeats the
5056 # text. This is the framed/thumbnail case. If there's no caption, we
5057 # use the unnamed parameter for alt text as well, just for the time be-
5058 # ing, if the unnamed param is set and the alt param is not.
5059 #
5060 # For the future, we need to figure out if we want to tweak this more,
5061 # e.g., introducing a title= parameter for the title; ignoring the un-
5062 # named parameter entirely for images without a caption; adding an ex-
5063 # plicit caption= parameter and preserving the old magic unnamed para-
5064 # meter for BC; ...
5065 if ( $imageIsFramed ) { # Framed image
5066 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5067 # No caption or alt text, add the filename as the alt text so
5068 # that screen readers at least get some description of the image
5069 $params['frame']['alt'] = $title->getText();
5070 }
5071 # Do not set $params['frame']['title'] because tooltips don't make sense
5072 # for framed images
5073 } else { # Inline image
5074 if ( !isset( $params['frame']['alt'] ) ) {
5075 # No alt text, use the "caption" for the alt text
5076 if ( $caption !== '') {
5077 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5078 } else {
5079 # No caption, fall back to using the filename for the
5080 # alt text
5081 $params['frame']['alt'] = $title->getText();
5082 }
5083 }
5084 # Use the "caption" for the tooltip text
5085 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5086 }
5087
5088 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
5089
5090 # Linker does the rest
5091 $time = isset( $options['time'] ) ? $options['time'] : false;
5092 $ret = Linker::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5093 $time, $descQuery, $this->mOptions->getThumbSize() );
5094
5095 # Give the handler a chance to modify the parser object
5096 if ( $handler ) {
5097 $handler->parserTransformHook( $this, $file );
5098 }
5099
5100 return $ret;
5101 }
5102
5103 /**
5104 * @param $caption
5105 * @param $holders LinkHolderArray
5106 * @return mixed|String
5107 */
5108 protected function stripAltText( $caption, $holders ) {
5109 # Strip bad stuff out of the title (tooltip). We can't just use
5110 # replaceLinkHoldersText() here, because if this function is called
5111 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5112 if ( $holders ) {
5113 $tooltip = $holders->replaceText( $caption );
5114 } else {
5115 $tooltip = $this->replaceLinkHoldersText( $caption );
5116 }
5117
5118 # make sure there are no placeholders in thumbnail attributes
5119 # that are later expanded to html- so expand them now and
5120 # remove the tags
5121 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5122 $tooltip = Sanitizer::stripAllTags( $tooltip );
5123
5124 return $tooltip;
5125 }
5126
5127 /**
5128 * Set a flag in the output object indicating that the content is dynamic and
5129 * shouldn't be cached.
5130 */
5131 function disableCache() {
5132 wfDebug( "Parser output marked as uncacheable.\n" );
5133 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5134 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5135 }
5136
5137 /**
5138 * Callback from the Sanitizer for expanding items found in HTML attribute
5139 * values, so they can be safely tested and escaped.
5140 *
5141 * @param $text String
5142 * @param $frame PPFrame
5143 * @return String
5144 */
5145 function attributeStripCallback( &$text, $frame = false ) {
5146 $text = $this->replaceVariables( $text, $frame );
5147 $text = $this->mStripState->unstripBoth( $text );
5148 return $text;
5149 }
5150
5151 /**
5152 * Accessor
5153 *
5154 * @return array
5155 */
5156 function getTags() {
5157 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ) );
5158 }
5159
5160 /**
5161 * Replace transparent tags in $text with the values given by the callbacks.
5162 *
5163 * Transparent tag hooks are like regular XML-style tag hooks, except they
5164 * operate late in the transformation sequence, on HTML instead of wikitext.
5165 *
5166 * @param $text string
5167 *
5168 * @return string
5169 */
5170 function replaceTransparentTags( $text ) {
5171 $matches = array();
5172 $elements = array_keys( $this->mTransparentTagHooks );
5173 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5174 $replacements = array();
5175
5176 foreach ( $matches as $marker => $data ) {
5177 list( $element, $content, $params, $tag ) = $data;
5178 $tagName = strtolower( $element );
5179 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5180 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
5181 } else {
5182 $output = $tag;
5183 }
5184 $replacements[$marker] = $output;
5185 }
5186 return strtr( $text, $replacements );
5187 }
5188
5189 /**
5190 * Break wikitext input into sections, and either pull or replace
5191 * some particular section's text.
5192 *
5193 * External callers should use the getSection and replaceSection methods.
5194 *
5195 * @param $text String: Page wikitext
5196 * @param $section String: a section identifier string of the form:
5197 * <flag1> - <flag2> - ... - <section number>
5198 *
5199 * Currently the only recognised flag is "T", which means the target section number
5200 * was derived during a template inclusion parse, in other words this is a template
5201 * section edit link. If no flags are given, it was an ordinary section edit link.
5202 * This flag is required to avoid a section numbering mismatch when a section is
5203 * enclosed by <includeonly> (bug 6563).
5204 *
5205 * The section number 0 pulls the text before the first heading; other numbers will
5206 * pull the given section along with its lower-level subsections. If the section is
5207 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5208 *
5209 * Section 0 is always considered to exist, even if it only contains the empty
5210 * string. If $text is the empty string and section 0 is replaced, $newText is
5211 * returned.
5212 *
5213 * @param $mode String: one of "get" or "replace"
5214 * @param $newText String: replacement text for section data.
5215 * @return String: for "get", the extracted section text.
5216 * for "replace", the whole page with the section replaced.
5217 */
5218 private function extractSections( $text, $section, $mode, $newText='' ) {
5219 global $wgTitle; # not generally used but removes an ugly failure mode
5220 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5221 $outText = '';
5222 $frame = $this->getPreprocessor()->newFrame();
5223
5224 # Process section extraction flags
5225 $flags = 0;
5226 $sectionParts = explode( '-', $section );
5227 $sectionIndex = array_pop( $sectionParts );
5228 foreach ( $sectionParts as $part ) {
5229 if ( $part === 'T' ) {
5230 $flags |= self::PTD_FOR_INCLUSION;
5231 }
5232 }
5233
5234 # Check for empty input
5235 if ( strval( $text ) === '' ) {
5236 # Only sections 0 and T-0 exist in an empty document
5237 if ( $sectionIndex == 0 ) {
5238 if ( $mode === 'get' ) {
5239 return '';
5240 } else {
5241 return $newText;
5242 }
5243 } else {
5244 if ( $mode === 'get' ) {
5245 return $newText;
5246 } else {
5247 return $text;
5248 }
5249 }
5250 }
5251
5252 # Preprocess the text
5253 $root = $this->preprocessToDom( $text, $flags );
5254
5255 # <h> nodes indicate section breaks
5256 # They can only occur at the top level, so we can find them by iterating the root's children
5257 $node = $root->getFirstChild();
5258
5259 # Find the target section
5260 if ( $sectionIndex == 0 ) {
5261 # Section zero doesn't nest, level=big
5262 $targetLevel = 1000;
5263 } else {
5264 while ( $node ) {
5265 if ( $node->getName() === 'h' ) {
5266 $bits = $node->splitHeading();
5267 if ( $bits['i'] == $sectionIndex ) {
5268 $targetLevel = $bits['level'];
5269 break;
5270 }
5271 }
5272 if ( $mode === 'replace' ) {
5273 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5274 }
5275 $node = $node->getNextSibling();
5276 }
5277 }
5278
5279 if ( !$node ) {
5280 # Not found
5281 if ( $mode === 'get' ) {
5282 return $newText;
5283 } else {
5284 return $text;
5285 }
5286 }
5287
5288 # Find the end of the section, including nested sections
5289 do {
5290 if ( $node->getName() === 'h' ) {
5291 $bits = $node->splitHeading();
5292 $curLevel = $bits['level'];
5293 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5294 break;
5295 }
5296 }
5297 if ( $mode === 'get' ) {
5298 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5299 }
5300 $node = $node->getNextSibling();
5301 } while ( $node );
5302
5303 # Write out the remainder (in replace mode only)
5304 if ( $mode === 'replace' ) {
5305 # Output the replacement text
5306 # Add two newlines on -- trailing whitespace in $newText is conventionally
5307 # stripped by the editor, so we need both newlines to restore the paragraph gap
5308 # Only add trailing whitespace if there is newText
5309 if ( $newText != "" ) {
5310 $outText .= $newText . "\n\n";
5311 }
5312
5313 while ( $node ) {
5314 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5315 $node = $node->getNextSibling();
5316 }
5317 }
5318
5319 if ( is_string( $outText ) ) {
5320 # Re-insert stripped tags
5321 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5322 }
5323
5324 return $outText;
5325 }
5326
5327 /**
5328 * This function returns the text of a section, specified by a number ($section).
5329 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5330 * the first section before any such heading (section 0).
5331 *
5332 * If a section contains subsections, these are also returned.
5333 *
5334 * @param $text String: text to look in
5335 * @param $section String: section identifier
5336 * @param $deftext String: default to return if section is not found
5337 * @return string text of the requested section
5338 */
5339 public function getSection( $text, $section, $deftext='' ) {
5340 return $this->extractSections( $text, $section, "get", $deftext );
5341 }
5342
5343 /**
5344 * This function returns $oldtext after the content of the section
5345 * specified by $section has been replaced with $text. If the target
5346 * section does not exist, $oldtext is returned unchanged.
5347 *
5348 * @param $oldtext String: former text of the article
5349 * @param $section Numeric: section identifier
5350 * @param $text String: replacing text
5351 * @return String: modified text
5352 */
5353 public function replaceSection( $oldtext, $section, $text ) {
5354 return $this->extractSections( $oldtext, $section, "replace", $text );
5355 }
5356
5357 /**
5358 * Get the ID of the revision we are parsing
5359 *
5360 * @return Mixed: integer or null
5361 */
5362 function getRevisionId() {
5363 return $this->mRevisionId;
5364 }
5365
5366 /**
5367 * Get the revision object for $this->mRevisionId
5368 *
5369 * @return Revision|null either a Revision object or null
5370 */
5371 protected function getRevisionObject() {
5372 if ( !is_null( $this->mRevisionObject ) ) {
5373 return $this->mRevisionObject;
5374 }
5375 if ( is_null( $this->mRevisionId ) ) {
5376 return null;
5377 }
5378
5379 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
5380 return $this->mRevisionObject;
5381 }
5382
5383 /**
5384 * Get the timestamp associated with the current revision, adjusted for
5385 * the default server-local timestamp
5386 */
5387 function getRevisionTimestamp() {
5388 if ( is_null( $this->mRevisionTimestamp ) ) {
5389 wfProfileIn( __METHOD__ );
5390
5391 global $wgContLang;
5392
5393 $revObject = $this->getRevisionObject();
5394 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5395
5396 # The cryptic '' timezone parameter tells to use the site-default
5397 # timezone offset instead of the user settings.
5398 #
5399 # Since this value will be saved into the parser cache, served
5400 # to other users, and potentially even used inside links and such,
5401 # it needs to be consistent for all visitors.
5402 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5403
5404 wfProfileOut( __METHOD__ );
5405 }
5406 return $this->mRevisionTimestamp;
5407 }
5408
5409 /**
5410 * Get the name of the user that edited the last revision
5411 *
5412 * @return String: user name
5413 */
5414 function getRevisionUser() {
5415 if( is_null( $this->mRevisionUser ) ) {
5416 $revObject = $this->getRevisionObject();
5417
5418 # if this template is subst: the revision id will be blank,
5419 # so just use the current user's name
5420 if( $revObject ) {
5421 $this->mRevisionUser = $revObject->getUserText();
5422 } elseif( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5423 $this->mRevisionUser = $this->getUser()->getName();
5424 }
5425 }
5426 return $this->mRevisionUser;
5427 }
5428
5429 /**
5430 * Mutator for $mDefaultSort
5431 *
5432 * @param $sort New value
5433 */
5434 public function setDefaultSort( $sort ) {
5435 $this->mDefaultSort = $sort;
5436 $this->mOutput->setProperty( 'defaultsort', $sort );
5437 }
5438
5439 /**
5440 * Accessor for $mDefaultSort
5441 * Will use the empty string if none is set.
5442 *
5443 * This value is treated as a prefix, so the
5444 * empty string is equivalent to sorting by
5445 * page name.
5446 *
5447 * @return string
5448 */
5449 public function getDefaultSort() {
5450 if ( $this->mDefaultSort !== false ) {
5451 return $this->mDefaultSort;
5452 } else {
5453 return '';
5454 }
5455 }
5456
5457 /**
5458 * Accessor for $mDefaultSort
5459 * Unlike getDefaultSort(), will return false if none is set
5460 *
5461 * @return string or false
5462 */
5463 public function getCustomDefaultSort() {
5464 return $this->mDefaultSort;
5465 }
5466
5467 /**
5468 * Try to guess the section anchor name based on a wikitext fragment
5469 * presumably extracted from a heading, for example "Header" from
5470 * "== Header ==".
5471 *
5472 * @param $text string
5473 *
5474 * @return string
5475 */
5476 public function guessSectionNameFromWikiText( $text ) {
5477 # Strip out wikitext links(they break the anchor)
5478 $text = $this->stripSectionName( $text );
5479 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5480 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5481 }
5482
5483 /**
5484 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5485 * instead. For use in redirects, since IE6 interprets Redirect: headers
5486 * as something other than UTF-8 (apparently?), resulting in breakage.
5487 *
5488 * @param $text String: The section name
5489 * @return string An anchor
5490 */
5491 public function guessLegacySectionNameFromWikiText( $text ) {
5492 # Strip out wikitext links(they break the anchor)
5493 $text = $this->stripSectionName( $text );
5494 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5495 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
5496 }
5497
5498 /**
5499 * Strips a text string of wikitext for use in a section anchor
5500 *
5501 * Accepts a text string and then removes all wikitext from the
5502 * string and leaves only the resultant text (i.e. the result of
5503 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5504 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5505 * to create valid section anchors by mimicing the output of the
5506 * parser when headings are parsed.
5507 *
5508 * @param $text String: text string to be stripped of wikitext
5509 * for use in a Section anchor
5510 * @return Filtered text string
5511 */
5512 public function stripSectionName( $text ) {
5513 # Strip internal link markup
5514 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5515 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5516
5517 # Strip external link markup
5518 # @todo FIXME: Not tolerant to blank link text
5519 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5520 # on how many empty links there are on the page - need to figure that out.
5521 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5522
5523 # Parse wikitext quotes (italics & bold)
5524 $text = $this->doQuotes( $text );
5525
5526 # Strip HTML tags
5527 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5528 return $text;
5529 }
5530
5531 /**
5532 * strip/replaceVariables/unstrip for preprocessor regression testing
5533 *
5534 * @param $text string
5535 * @param $title Title
5536 * @param $options ParserOptions
5537 * @param $outputType int
5538 *
5539 * @return string
5540 */
5541 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
5542 $this->startParse( $title, $options, $outputType, true );
5543
5544 $text = $this->replaceVariables( $text );
5545 $text = $this->mStripState->unstripBoth( $text );
5546 $text = Sanitizer::removeHTMLtags( $text );
5547 return $text;
5548 }
5549
5550 /**
5551 * @param $text string
5552 * @param $title Title
5553 * @param $options ParserOptions
5554 * @return string
5555 */
5556 function testPst( $text, Title $title, ParserOptions $options ) {
5557 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5558 }
5559
5560 /**
5561 * @param $text
5562 * @param $title Title
5563 * @param $options ParserOptions
5564 * @return string
5565 */
5566 function testPreprocess( $text, Title $title, ParserOptions $options ) {
5567 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5568 }
5569
5570 /**
5571 * Call a callback function on all regions of the given text that are not
5572 * inside strip markers, and replace those regions with the return value
5573 * of the callback. For example, with input:
5574 *
5575 * aaa<MARKER>bbb
5576 *
5577 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5578 * two strings will be replaced with the value returned by the callback in
5579 * each case.
5580 *
5581 * @param $s string
5582 * @param $callback
5583 *
5584 * @return string
5585 */
5586 function markerSkipCallback( $s, $callback ) {
5587 $i = 0;
5588 $out = '';
5589 while ( $i < strlen( $s ) ) {
5590 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5591 if ( $markerStart === false ) {
5592 $out .= call_user_func( $callback, substr( $s, $i ) );
5593 break;
5594 } else {
5595 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5596 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5597 if ( $markerEnd === false ) {
5598 $out .= substr( $s, $markerStart );
5599 break;
5600 } else {
5601 $markerEnd += strlen( self::MARKER_SUFFIX );
5602 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5603 $i = $markerEnd;
5604 }
5605 }
5606 }
5607 return $out;
5608 }
5609
5610 /**
5611 * Save the parser state required to convert the given half-parsed text to
5612 * HTML. "Half-parsed" in this context means the output of
5613 * recursiveTagParse() or internalParse(). This output has strip markers
5614 * from replaceVariables (extensionSubstitution() etc.), and link
5615 * placeholders from replaceLinkHolders().
5616 *
5617 * Returns an array which can be serialized and stored persistently. This
5618 * array can later be loaded into another parser instance with
5619 * unserializeHalfParsedText(). The text can then be safely incorporated into
5620 * the return value of a parser hook.
5621 *
5622 * @param $text string
5623 *
5624 * @return array
5625 */
5626 function serializeHalfParsedText( $text ) {
5627 wfProfileIn( __METHOD__ );
5628 $data = array(
5629 'text' => $text,
5630 'version' => self::HALF_PARSED_VERSION,
5631 'stripState' => $this->mStripState->getSubState( $text ),
5632 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
5633 );
5634 wfProfileOut( __METHOD__ );
5635 return $data;
5636 }
5637
5638 /**
5639 * Load the parser state given in the $data array, which is assumed to
5640 * have been generated by serializeHalfParsedText(). The text contents is
5641 * extracted from the array, and its markers are transformed into markers
5642 * appropriate for the current Parser instance. This transformed text is
5643 * returned, and can be safely included in the return value of a parser
5644 * hook.
5645 *
5646 * If the $data array has been stored persistently, the caller should first
5647 * check whether it is still valid, by calling isValidHalfParsedText().
5648 *
5649 * @param $data Serialized data
5650 * @return String
5651 */
5652 function unserializeHalfParsedText( $data ) {
5653 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
5654 throw new MWException( __METHOD__.': invalid version' );
5655 }
5656
5657 # First, extract the strip state.
5658 $texts = array( $data['text'] );
5659 $texts = $this->mStripState->merge( $data['stripState'], $texts );
5660
5661 # Now renumber links
5662 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
5663
5664 # Should be good to go.
5665 return $texts[0];
5666 }
5667
5668 /**
5669 * Returns true if the given array, presumed to be generated by
5670 * serializeHalfParsedText(), is compatible with the current version of the
5671 * parser.
5672 *
5673 * @param $data Array
5674 *
5675 * @return bool
5676 */
5677 function isValidHalfParsedText( $data ) {
5678 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
5679 }
5680 }