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