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