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