Fixes Bug #30149 - Handling of parentheses for Korean, Chinese and Japanese
[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 $text = SpecialPageFactory::capturePath( $title );
3254 if ( is_string( $text ) ) {
3255 $found = true;
3256 $isHTML = true;
3257 $this->disableCache();
3258 }
3259 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3260 $found = false; # access denied
3261 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
3262 } else {
3263 list( $text, $title ) = $this->getTemplateDom( $title );
3264 if ( $text !== false ) {
3265 $found = true;
3266 $isChildObj = true;
3267 }
3268 }
3269
3270 # If the title is valid but undisplayable, make a link to it
3271 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3272 $text = "[[:$titleText]]";
3273 $found = true;
3274 }
3275 } elseif ( $title->isTrans() ) {
3276 # Interwiki transclusion
3277 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3278 $text = $this->interwikiTransclude( $title, 'render' );
3279 $isHTML = true;
3280 } else {
3281 $text = $this->interwikiTransclude( $title, 'raw' );
3282 # Preprocess it like a template
3283 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3284 $isChildObj = true;
3285 }
3286 $found = true;
3287 }
3288
3289 # Do infinite loop check
3290 # This has to be done after redirect resolution to avoid infinite loops via redirects
3291 if ( !$frame->loopCheck( $title ) ) {
3292 $found = true;
3293 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3294 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
3295 }
3296 wfProfileOut( __METHOD__ . '-loadtpl' );
3297 }
3298
3299 # If we haven't found text to substitute by now, we're done
3300 # Recover the source wikitext and return it
3301 if ( !$found ) {
3302 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3303 wfProfileOut( __METHOD__."-title-$originalTitle" );
3304 wfProfileOut( __METHOD__ );
3305 return array( 'object' => $text );
3306 }
3307
3308 # Expand DOM-style return values in a child frame
3309 if ( $isChildObj ) {
3310 # Clean up argument array
3311 $newFrame = $frame->newChild( $args, $title );
3312
3313 if ( $nowiki ) {
3314 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3315 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3316 # Expansion is eligible for the empty-frame cache
3317 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3318 $text = $this->mTplExpandCache[$titleText];
3319 } else {
3320 $text = $newFrame->expand( $text );
3321 $this->mTplExpandCache[$titleText] = $text;
3322 }
3323 } else {
3324 # Uncached expansion
3325 $text = $newFrame->expand( $text );
3326 }
3327 }
3328 if ( $isLocalObj && $nowiki ) {
3329 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3330 $isLocalObj = false;
3331 }
3332
3333 # Replace raw HTML by a placeholder
3334 # Add a blank line preceding, to prevent it from mucking up
3335 # immediately preceding headings
3336 if ( $isHTML ) {
3337 $text = "\n\n" . $this->insertStripItem( $text );
3338 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3339 # Escape nowiki-style return values
3340 $text = wfEscapeWikiText( $text );
3341 } elseif ( is_string( $text )
3342 && !$piece['lineStart']
3343 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3344 {
3345 # Bug 529: if the template begins with a table or block-level
3346 # element, it should be treated as beginning a new line.
3347 # This behaviour is somewhat controversial.
3348 $text = "\n" . $text;
3349 }
3350
3351 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3352 # Error, oversize inclusion
3353 if ( $titleText !== false ) {
3354 # Make a working, properly escaped link if possible (bug 23588)
3355 $text = "[[:$titleText]]";
3356 } else {
3357 # This will probably not be a working link, but at least it may
3358 # provide some hint of where the problem is
3359 preg_replace( '/^:/', '', $originalTitle );
3360 $text = "[[:$originalTitle]]";
3361 }
3362 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3363 $this->limitationWarn( 'post-expand-template-inclusion' );
3364 }
3365
3366 if ( $isLocalObj ) {
3367 $ret = array( 'object' => $text );
3368 } else {
3369 $ret = array( 'text' => $text );
3370 }
3371
3372 wfProfileOut( __METHOD__."-title-$originalTitle" );
3373 wfProfileOut( __METHOD__ );
3374 return $ret;
3375 }
3376
3377 /**
3378 * Get the semi-parsed DOM representation of a template with a given title,
3379 * and its redirect destination title. Cached.
3380 *
3381 * @return array
3382 */
3383 function getTemplateDom( $title ) {
3384 $cacheTitle = $title;
3385 $titleText = $title->getPrefixedDBkey();
3386
3387 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3388 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3389 $title = Title::makeTitle( $ns, $dbk );
3390 $titleText = $title->getPrefixedDBkey();
3391 }
3392 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3393 return array( $this->mTplDomCache[$titleText], $title );
3394 }
3395
3396 # Cache miss, go to the database
3397 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3398
3399 if ( $text === false ) {
3400 $this->mTplDomCache[$titleText] = false;
3401 return array( false, $title );
3402 }
3403
3404 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3405 $this->mTplDomCache[ $titleText ] = $dom;
3406
3407 if ( !$title->equals( $cacheTitle ) ) {
3408 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3409 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3410 }
3411
3412 return array( $dom, $title );
3413 }
3414
3415 /**
3416 * Fetch the unparsed text of a template and register a reference to it.
3417 * @param Title $title
3418 * @return Array ( string or false, Title )
3419 */
3420 function fetchTemplateAndTitle( $title ) {
3421 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3422 $stuff = call_user_func( $templateCb, $title, $this );
3423 $text = $stuff['text'];
3424 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3425 if ( isset( $stuff['deps'] ) ) {
3426 foreach ( $stuff['deps'] as $dep ) {
3427 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3428 }
3429 }
3430 return array( $text, $finalTitle );
3431 }
3432
3433 /**
3434 * Fetch the unparsed text of a template and register a reference to it.
3435 * @param Title $title
3436 * @return mixed string or false
3437 */
3438 function fetchTemplate( $title ) {
3439 $rv = $this->fetchTemplateAndTitle( $title );
3440 return $rv[0];
3441 }
3442
3443 /**
3444 * Static function to get a template
3445 * Can be overridden via ParserOptions::setTemplateCallback().
3446 *
3447 * @return array
3448 */
3449 static function statelessFetchTemplate( $title, $parser = false ) {
3450 $text = $skip = false;
3451 $finalTitle = $title;
3452 $deps = array();
3453
3454 # Loop to fetch the article, with up to 1 redirect
3455 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3456 # Give extensions a chance to select the revision instead
3457 $id = false; # Assume current
3458 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3459 array( $parser, $title, &$skip, &$id ) );
3460
3461 if ( $skip ) {
3462 $text = false;
3463 $deps[] = array(
3464 'title' => $title,
3465 'page_id' => $title->getArticleID(),
3466 'rev_id' => null
3467 );
3468 break;
3469 }
3470 # Get the revision
3471 $rev = $id
3472 ? Revision::newFromId( $id )
3473 : Revision::newFromTitle( $title );
3474 $rev_id = $rev ? $rev->getId() : 0;
3475 # If there is no current revision, there is no page
3476 if ( $id === false && !$rev ) {
3477 $linkCache = LinkCache::singleton();
3478 $linkCache->addBadLinkObj( $title );
3479 }
3480
3481 $deps[] = array(
3482 'title' => $title,
3483 'page_id' => $title->getArticleID(),
3484 'rev_id' => $rev_id );
3485 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3486 # We fetched a rev from a different title; register it too...
3487 $deps[] = array(
3488 'title' => $rev->getTitle(),
3489 'page_id' => $rev->getPage(),
3490 'rev_id' => $rev_id );
3491 }
3492
3493 if ( $rev ) {
3494 $text = $rev->getText();
3495 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3496 global $wgContLang;
3497 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3498 if ( !$message->exists() ) {
3499 $text = false;
3500 break;
3501 }
3502 $text = $message->plain();
3503 } else {
3504 break;
3505 }
3506 if ( $text === false ) {
3507 break;
3508 }
3509 # Redirect?
3510 $finalTitle = $title;
3511 $title = Title::newFromRedirect( $text );
3512 }
3513 return array(
3514 'text' => $text,
3515 'finalTitle' => $finalTitle,
3516 'deps' => $deps );
3517 }
3518
3519 /**
3520 * Fetch a file and its title and register a reference to it.
3521 * @param Title $title
3522 * @param string $time MW timestamp
3523 * @param string $sha1 base 36 SHA-1
3524 * @return mixed File or false
3525 */
3526 function fetchFile( $title, $time = false, $sha1 = false ) {
3527 $res = $this->fetchFileAndTitle( $title, $time, $sha1 );
3528 return $res[0];
3529 }
3530
3531 /**
3532 * Fetch a file and its title and register a reference to it.
3533 * @param Title $title
3534 * @param string $time MW timestamp
3535 * @param string $sha1 base 36 SHA-1
3536 * @return Array ( File or false, Title of file )
3537 */
3538 function fetchFileAndTitle( $title, $time = false, $sha1 = false ) {
3539 if ( $time === '0' ) {
3540 $file = false; // broken thumbnail forced by hook
3541 } elseif ( $sha1 ) { // get by (sha1,timestamp)
3542 $file = RepoGroup::singleton()->findFileFromKey( $sha1, array( 'time' => $time ) );
3543 } else { // get by (name,timestamp)
3544 $file = wfFindFile( $title, array( 'time' => $time ) );
3545 }
3546 $time = $file ? $file->getTimestamp() : false;
3547 $sha1 = $file ? $file->getSha1() : false;
3548 # Register the file as a dependency...
3549 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3550 if ( $file && !$title->equals( $file->getTitle() ) ) {
3551 # Update fetched file title
3552 $title = $file->getTitle();
3553 if ( is_null( $file->getRedirectedTitle() ) ) {
3554 # This file was not a redirect, but the title does not match.
3555 # Register under the new name because otherwise the link will
3556 # get lost.
3557 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3558 }
3559 }
3560 return array( $file, $title );
3561 }
3562
3563 /**
3564 * Transclude an interwiki link.
3565 *
3566 * @param $title Title
3567 * @param $action
3568 *
3569 * @return string
3570 */
3571 function interwikiTransclude( $title, $action ) {
3572 global $wgEnableScaryTranscluding;
3573
3574 if ( !$wgEnableScaryTranscluding ) {
3575 return wfMsgForContent('scarytranscludedisabled');
3576 }
3577
3578 $url = $title->getFullUrl( "action=$action" );
3579
3580 if ( strlen( $url ) > 255 ) {
3581 return wfMsgForContent( 'scarytranscludetoolong' );
3582 }
3583 return $this->fetchScaryTemplateMaybeFromCache( $url );
3584 }
3585
3586 /**
3587 * @param $url string
3588 * @return Mixed|String
3589 */
3590 function fetchScaryTemplateMaybeFromCache( $url ) {
3591 global $wgTranscludeCacheExpiry;
3592 $dbr = wfGetDB( DB_SLAVE );
3593 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3594 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3595 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3596 if ( $obj ) {
3597 return $obj->tc_contents;
3598 }
3599
3600 $text = Http::get( $url );
3601 if ( !$text ) {
3602 return wfMsgForContent( 'scarytranscludefailed', $url );
3603 }
3604
3605 $dbw = wfGetDB( DB_MASTER );
3606 $dbw->replace( 'transcache', array('tc_url'), array(
3607 'tc_url' => $url,
3608 'tc_time' => $dbw->timestamp( time() ),
3609 'tc_contents' => $text)
3610 );
3611 return $text;
3612 }
3613
3614 /**
3615 * Triple brace replacement -- used for template arguments
3616 * @private
3617 *
3618 * @param $peice array
3619 * @param $frame PPFrame
3620 *
3621 * @return array
3622 */
3623 function argSubstitution( $piece, $frame ) {
3624 wfProfileIn( __METHOD__ );
3625
3626 $error = false;
3627 $parts = $piece['parts'];
3628 $nameWithSpaces = $frame->expand( $piece['title'] );
3629 $argName = trim( $nameWithSpaces );
3630 $object = false;
3631 $text = $frame->getArgument( $argName );
3632 if ( $text === false && $parts->getLength() > 0
3633 && (
3634 $this->ot['html']
3635 || $this->ot['pre']
3636 || ( $this->ot['wiki'] && $frame->isTemplate() )
3637 )
3638 ) {
3639 # No match in frame, use the supplied default
3640 $object = $parts->item( 0 )->getChildren();
3641 }
3642 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3643 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3644 $this->limitationWarn( 'post-expand-template-argument' );
3645 }
3646
3647 if ( $text === false && $object === false ) {
3648 # No match anywhere
3649 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3650 }
3651 if ( $error !== false ) {
3652 $text .= $error;
3653 }
3654 if ( $object !== false ) {
3655 $ret = array( 'object' => $object );
3656 } else {
3657 $ret = array( 'text' => $text );
3658 }
3659
3660 wfProfileOut( __METHOD__ );
3661 return $ret;
3662 }
3663
3664 /**
3665 * Return the text to be used for a given extension tag.
3666 * This is the ghost of strip().
3667 *
3668 * @param $params Associative array of parameters:
3669 * name PPNode for the tag name
3670 * attr PPNode for unparsed text where tag attributes are thought to be
3671 * attributes Optional associative array of parsed attributes
3672 * inner Contents of extension element
3673 * noClose Original text did not have a close tag
3674 * @param $frame PPFrame
3675 *
3676 * @return string
3677 */
3678 function extensionSubstitution( $params, $frame ) {
3679 $name = $frame->expand( $params['name'] );
3680 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3681 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3682 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3683
3684 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) &&
3685 ( $this->ot['html'] || $this->ot['pre'] );
3686 if ( $isFunctionTag ) {
3687 $markerType = 'none';
3688 } else {
3689 $markerType = 'general';
3690 }
3691 if ( $this->ot['html'] || $isFunctionTag ) {
3692 $name = strtolower( $name );
3693 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3694 if ( isset( $params['attributes'] ) ) {
3695 $attributes = $attributes + $params['attributes'];
3696 }
3697
3698 if ( isset( $this->mTagHooks[$name] ) ) {
3699 # Workaround for PHP bug 35229 and similar
3700 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3701 throw new MWException( "Tag hook for $name is not callable\n" );
3702 }
3703 $output = call_user_func_array( $this->mTagHooks[$name],
3704 array( $content, $attributes, $this, $frame ) );
3705 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3706 list( $callback, $flags ) = $this->mFunctionTagHooks[$name];
3707 if ( !is_callable( $callback ) ) {
3708 throw new MWException( "Tag hook for $name is not callable\n" );
3709 }
3710
3711 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3712 } else {
3713 $output = '<span class="error">Invalid tag extension name: ' .
3714 htmlspecialchars( $name ) . '</span>';
3715 }
3716
3717 if ( is_array( $output ) ) {
3718 # Extract flags to local scope (to override $markerType)
3719 $flags = $output;
3720 $output = $flags[0];
3721 unset( $flags[0] );
3722 extract( $flags );
3723 }
3724 } else {
3725 if ( is_null( $attrText ) ) {
3726 $attrText = '';
3727 }
3728 if ( isset( $params['attributes'] ) ) {
3729 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3730 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3731 htmlspecialchars( $attrValue ) . '"';
3732 }
3733 }
3734 if ( $content === null ) {
3735 $output = "<$name$attrText/>";
3736 } else {
3737 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3738 $output = "<$name$attrText>$content$close";
3739 }
3740 }
3741
3742 if ( $markerType === 'none' ) {
3743 return $output;
3744 } elseif ( $markerType === 'nowiki' ) {
3745 $this->mStripState->addNoWiki( $marker, $output );
3746 } elseif ( $markerType === 'general' ) {
3747 $this->mStripState->addGeneral( $marker, $output );
3748 } else {
3749 throw new MWException( __METHOD__.': invalid marker type' );
3750 }
3751 return $marker;
3752 }
3753
3754 /**
3755 * Increment an include size counter
3756 *
3757 * @param $type String: the type of expansion
3758 * @param $size Integer: the size of the text
3759 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3760 */
3761 function incrementIncludeSize( $type, $size ) {
3762 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3763 return false;
3764 } else {
3765 $this->mIncludeSizes[$type] += $size;
3766 return true;
3767 }
3768 }
3769
3770 /**
3771 * Increment the expensive function count
3772 *
3773 * @return Boolean: false if the limit has been exceeded
3774 */
3775 function incrementExpensiveFunctionCount() {
3776 global $wgExpensiveParserFunctionLimit;
3777 $this->mExpensiveFunctionCount++;
3778 if ( $this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit ) {
3779 return true;
3780 }
3781 return false;
3782 }
3783
3784 /**
3785 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3786 * Fills $this->mDoubleUnderscores, returns the modified text
3787 */
3788 function doDoubleUnderscore( $text ) {
3789 wfProfileIn( __METHOD__ );
3790
3791 # The position of __TOC__ needs to be recorded
3792 $mw = MagicWord::get( 'toc' );
3793 if ( $mw->match( $text ) ) {
3794 $this->mShowToc = true;
3795 $this->mForceTocPosition = true;
3796
3797 # Set a placeholder. At the end we'll fill it in with the TOC.
3798 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3799
3800 # Only keep the first one.
3801 $text = $mw->replace( '', $text );
3802 }
3803
3804 # Now match and remove the rest of them
3805 $mwa = MagicWord::getDoubleUnderscoreArray();
3806 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3807
3808 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3809 $this->mOutput->mNoGallery = true;
3810 }
3811 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3812 $this->mShowToc = false;
3813 }
3814 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3815 $this->addTrackingCategory( 'hidden-category-category' );
3816 }
3817 # (bug 8068) Allow control over whether robots index a page.
3818 #
3819 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3820 # is not desirable, the last one on the page should win.
3821 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
3822 $this->mOutput->setIndexPolicy( 'noindex' );
3823 $this->addTrackingCategory( 'noindex-category' );
3824 }
3825 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
3826 $this->mOutput->setIndexPolicy( 'index' );
3827 $this->addTrackingCategory( 'index-category' );
3828 }
3829
3830 # Cache all double underscores in the database
3831 foreach ( $this->mDoubleUnderscores as $key => $val ) {
3832 $this->mOutput->setProperty( $key, '' );
3833 }
3834
3835 wfProfileOut( __METHOD__ );
3836 return $text;
3837 }
3838
3839 /**
3840 * Add a tracking category, getting the title from a system message,
3841 * or print a debug message if the title is invalid.
3842 *
3843 * @param $msg String: message key
3844 * @return Boolean: whether the addition was successful
3845 */
3846 protected function addTrackingCategory( $msg ) {
3847 $cat = wfMsgForContent( $msg );
3848
3849 # Allow tracking categories to be disabled by setting them to "-"
3850 if ( $cat === '-' ) {
3851 return false;
3852 }
3853
3854 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
3855 if ( $containerCategory ) {
3856 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3857 return true;
3858 } else {
3859 wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" );
3860 return false;
3861 }
3862 }
3863
3864 /**
3865 * This function accomplishes several tasks:
3866 * 1) Auto-number headings if that option is enabled
3867 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3868 * 3) Add a Table of contents on the top for users who have enabled the option
3869 * 4) Auto-anchor headings
3870 *
3871 * It loops through all headlines, collects the necessary data, then splits up the
3872 * string and re-inserts the newly formatted headlines.
3873 *
3874 * @param $text String
3875 * @param $origText String: original, untouched wikitext
3876 * @param $isMain Boolean
3877 * @private
3878 */
3879 function formatHeadings( $text, $origText, $isMain=true ) {
3880 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3881
3882 # Inhibit editsection links if requested in the page
3883 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3884 $showEditLink = 0;
3885 } else {
3886 $showEditLink = $this->mOptions->getEditSection();
3887 }
3888 if ( $showEditLink ) {
3889 $this->mOutput->setEditSectionTokens( true );
3890 }
3891
3892 # Get all headlines for numbering them and adding funky stuff like [edit]
3893 # links - this is for later, but we need the number of headlines right now
3894 $matches = array();
3895 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3896
3897 # if there are fewer than 4 headlines in the article, do not show TOC
3898 # unless it's been explicitly enabled.
3899 $enoughToc = $this->mShowToc &&
3900 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
3901
3902 # Allow user to stipulate that a page should have a "new section"
3903 # link added via __NEWSECTIONLINK__
3904 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3905 $this->mOutput->setNewSection( true );
3906 }
3907
3908 # Allow user to remove the "new section"
3909 # link via __NONEWSECTIONLINK__
3910 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
3911 $this->mOutput->hideNewSection( true );
3912 }
3913
3914 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3915 # override above conditions and always show TOC above first header
3916 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3917 $this->mShowToc = true;
3918 $enoughToc = true;
3919 }
3920
3921 # headline counter
3922 $headlineCount = 0;
3923 $numVisible = 0;
3924
3925 # Ugh .. the TOC should have neat indentation levels which can be
3926 # passed to the skin functions. These are determined here
3927 $toc = '';
3928 $full = '';
3929 $head = array();
3930 $sublevelCount = array();
3931 $levelCount = array();
3932 $level = 0;
3933 $prevlevel = 0;
3934 $toclevel = 0;
3935 $prevtoclevel = 0;
3936 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3937 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3938 $oldType = $this->mOutputType;
3939 $this->setOutputType( self::OT_WIKI );
3940 $frame = $this->getPreprocessor()->newFrame();
3941 $root = $this->preprocessToDom( $origText );
3942 $node = $root->getFirstChild();
3943 $byteOffset = 0;
3944 $tocraw = array();
3945 $refers = array();
3946
3947 foreach ( $matches[3] as $headline ) {
3948 $isTemplate = false;
3949 $titleText = false;
3950 $sectionIndex = false;
3951 $numbering = '';
3952 $markerMatches = array();
3953 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3954 $serial = $markerMatches[1];
3955 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3956 $isTemplate = ( $titleText != $baseTitleText );
3957 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3958 }
3959
3960 if ( $toclevel ) {
3961 $prevlevel = $level;
3962 }
3963 $level = $matches[1][$headlineCount];
3964
3965 if ( $level > $prevlevel ) {
3966 # Increase TOC level
3967 $toclevel++;
3968 $sublevelCount[$toclevel] = 0;
3969 if ( $toclevel<$wgMaxTocLevel ) {
3970 $prevtoclevel = $toclevel;
3971 $toc .= Linker::tocIndent();
3972 $numVisible++;
3973 }
3974 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3975 # Decrease TOC level, find level to jump to
3976
3977 for ( $i = $toclevel; $i > 0; $i-- ) {
3978 if ( $levelCount[$i] == $level ) {
3979 # Found last matching level
3980 $toclevel = $i;
3981 break;
3982 } elseif ( $levelCount[$i] < $level ) {
3983 # Found first matching level below current level
3984 $toclevel = $i + 1;
3985 break;
3986 }
3987 }
3988 if ( $i == 0 ) {
3989 $toclevel = 1;
3990 }
3991 if ( $toclevel<$wgMaxTocLevel ) {
3992 if ( $prevtoclevel < $wgMaxTocLevel ) {
3993 # Unindent only if the previous toc level was shown :p
3994 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
3995 $prevtoclevel = $toclevel;
3996 } else {
3997 $toc .= Linker::tocLineEnd();
3998 }
3999 }
4000 } else {
4001 # No change in level, end TOC line
4002 if ( $toclevel<$wgMaxTocLevel ) {
4003 $toc .= Linker::tocLineEnd();
4004 }
4005 }
4006
4007 $levelCount[$toclevel] = $level;
4008
4009 # count number of headlines for each level
4010 @$sublevelCount[$toclevel]++;
4011 $dot = 0;
4012 for( $i = 1; $i <= $toclevel; $i++ ) {
4013 if ( !empty( $sublevelCount[$i] ) ) {
4014 if ( $dot ) {
4015 $numbering .= '.';
4016 }
4017 $numbering .= $this->getFunctionLang()->formatNum( $sublevelCount[$i] );
4018 $dot = 1;
4019 }
4020 }
4021
4022 # The safe header is a version of the header text safe to use for links
4023 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4024 $safeHeadline = $this->mStripState->unstripBoth( $headline );
4025
4026 # Remove link placeholders by the link text.
4027 # <!--LINK number-->
4028 # turns into
4029 # link text with suffix
4030 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
4031
4032 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
4033 $tocline = preg_replace(
4034 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
4035 array( '', '<$1>' ),
4036 $safeHeadline
4037 );
4038 $tocline = trim( $tocline );
4039
4040 # For the anchor, strip out HTML-y stuff period
4041 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4042 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4043
4044 # Save headline for section edit hint before it's escaped
4045 $headlineHint = $safeHeadline;
4046
4047 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4048 # For reverse compatibility, provide an id that's
4049 # HTML4-compatible, like we used to.
4050 #
4051 # It may be worth noting, academically, that it's possible for
4052 # the legacy anchor to conflict with a non-legacy headline
4053 # anchor on the page. In this case likely the "correct" thing
4054 # would be to either drop the legacy anchors or make sure
4055 # they're numbered first. However, this would require people
4056 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4057 # manually, so let's not bother worrying about it.
4058 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4059 array( 'noninitial', 'legacy' ) );
4060 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4061
4062 if ( $legacyHeadline == $safeHeadline ) {
4063 # No reason to have both (in fact, we can't)
4064 $legacyHeadline = false;
4065 }
4066 } else {
4067 $legacyHeadline = false;
4068 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4069 'noninitial' );
4070 }
4071
4072 # HTML names must be case-insensitively unique (bug 10721).
4073 # This does not apply to Unicode characters per
4074 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4075 # @todo FIXME: We may be changing them depending on the current locale.
4076 $arrayKey = strtolower( $safeHeadline );
4077 if ( $legacyHeadline === false ) {
4078 $legacyArrayKey = false;
4079 } else {
4080 $legacyArrayKey = strtolower( $legacyHeadline );
4081 }
4082
4083 # count how many in assoc. array so we can track dupes in anchors
4084 if ( isset( $refers[$arrayKey] ) ) {
4085 $refers[$arrayKey]++;
4086 } else {
4087 $refers[$arrayKey] = 1;
4088 }
4089 if ( isset( $refers[$legacyArrayKey] ) ) {
4090 $refers[$legacyArrayKey]++;
4091 } else {
4092 $refers[$legacyArrayKey] = 1;
4093 }
4094
4095 # Don't number the heading if it is the only one (looks silly)
4096 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4097 # the two are different if the line contains a link
4098 $headline = $numbering . ' ' . $headline;
4099 }
4100
4101 # Create the anchor for linking from the TOC to the section
4102 $anchor = $safeHeadline;
4103 $legacyAnchor = $legacyHeadline;
4104 if ( $refers[$arrayKey] > 1 ) {
4105 $anchor .= '_' . $refers[$arrayKey];
4106 }
4107 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4108 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4109 }
4110 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4111 $toc .= Linker::tocLine( $anchor, $tocline,
4112 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4113 }
4114
4115 # Add the section to the section tree
4116 # Find the DOM node for this header
4117 while ( $node && !$isTemplate ) {
4118 if ( $node->getName() === 'h' ) {
4119 $bits = $node->splitHeading();
4120 if ( $bits['i'] == $sectionIndex ) {
4121 break;
4122 }
4123 }
4124 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4125 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4126 $node = $node->getNextSibling();
4127 }
4128 $tocraw[] = array(
4129 'toclevel' => $toclevel,
4130 'level' => $level,
4131 'line' => $tocline,
4132 'number' => $numbering,
4133 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4134 'fromtitle' => $titleText,
4135 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
4136 'anchor' => $anchor,
4137 );
4138
4139 # give headline the correct <h#> tag
4140 if ( $showEditLink && $sectionIndex !== false ) {
4141 // Output edit section links as markers with styles that can be customized by skins
4142 if ( $isTemplate ) {
4143 # Put a T flag in the section identifier, to indicate to extractSections()
4144 # that sections inside <includeonly> should be counted.
4145 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4146 } else {
4147 $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint );
4148 }
4149 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4150 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4151 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4152 // so we don't have to worry about a user trying to input one of these markers directly.
4153 // We use a page and section attribute to stop the language converter from converting these important bits
4154 // of data, but put the headline hint inside a content block because the language converter is supposed to
4155 // be able to convert that piece of data.
4156 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4157 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4158 if ( isset($editlinkArgs[2]) ) {
4159 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4160 } else {
4161 $editlink .= '/>';
4162 }
4163 } else {
4164 $editlink = '';
4165 }
4166 $head[$headlineCount] = Linker::makeHeadline( $level,
4167 $matches['attrib'][$headlineCount], $anchor, $headline,
4168 $editlink, $legacyAnchor );
4169
4170 $headlineCount++;
4171 }
4172
4173 $this->setOutputType( $oldType );
4174
4175 # Never ever show TOC if no headers
4176 if ( $numVisible < 1 ) {
4177 $enoughToc = false;
4178 }
4179
4180 if ( $enoughToc ) {
4181 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4182 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4183 }
4184 $toc = Linker::tocList( $toc, $this->mOptions->getUserLang() );
4185 $this->mOutput->setTOCHTML( $toc );
4186 }
4187
4188 if ( $isMain ) {
4189 $this->mOutput->setSections( $tocraw );
4190 }
4191
4192 # split up and insert constructed headlines
4193 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4194 $i = 0;
4195
4196 // build an array of document sections
4197 $sections = array();
4198 foreach ( $blocks as $block ) {
4199 // $head is zero-based, sections aren't.
4200 if ( empty( $head[$i - 1] ) ) {
4201 $sections[$i] = $block;
4202 } else {
4203 $sections[$i] = $head[$i - 1] . $block;
4204 }
4205
4206 /**
4207 * Send a hook, one per section.
4208 * The idea here is to be able to make section-level DIVs, but to do so in a
4209 * lower-impact, more correct way than r50769
4210 *
4211 * $this : caller
4212 * $section : the section number
4213 * &$sectionContent : ref to the content of the section
4214 * $showEditLinks : boolean describing whether this section has an edit link
4215 */
4216 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4217
4218 $i++;
4219 }
4220
4221 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4222 // append the TOC at the beginning
4223 // Top anchor now in skin
4224 $sections[0] = $sections[0] . $toc . "\n";
4225 }
4226
4227 $full .= join( '', $sections );
4228
4229 if ( $this->mForceTocPosition ) {
4230 return str_replace( '<!--MWTOC-->', $toc, $full );
4231 } else {
4232 return $full;
4233 }
4234 }
4235
4236 /**
4237 * Transform wiki markup when saving a page by doing \r\n -> \n
4238 * conversion, substitting signatures, {{subst:}} templates, etc.
4239 *
4240 * @param $text String: the text to transform
4241 * @param $title Title: the Title object for the current article
4242 * @param $user User: the User object describing the current user
4243 * @param $options ParserOptions: parsing options
4244 * @param $clearState Boolean: whether to clear the parser state first
4245 * @return String: the altered wiki markup
4246 */
4247 public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) {
4248 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4249 $this->setUser( $user );
4250
4251 $pairs = array(
4252 "\r\n" => "\n",
4253 );
4254 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4255 if( $options->getPreSaveTransform() ) {
4256 $text = $this->pstPass2( $text, $user );
4257 }
4258 $text = $this->mStripState->unstripBoth( $text );
4259
4260 $this->setUser( null ); #Reset
4261
4262 return $text;
4263 }
4264
4265 /**
4266 * Pre-save transform helper function
4267 * @private
4268 */
4269 function pstPass2( $text, $user ) {
4270 global $wgContLang, $wgLocaltimezone;
4271
4272 # Note: This is the timestamp saved as hardcoded wikitext to
4273 # the database, we use $wgContLang here in order to give
4274 # everyone the same signature and use the default one rather
4275 # than the one selected in each user's preferences.
4276 # (see also bug 12815)
4277 $ts = $this->mOptions->getTimestamp();
4278 if ( isset( $wgLocaltimezone ) ) {
4279 $tz = $wgLocaltimezone;
4280 } else {
4281 $tz = date_default_timezone_get();
4282 }
4283
4284 $unixts = wfTimestamp( TS_UNIX, $ts );
4285 $oldtz = date_default_timezone_get();
4286 date_default_timezone_set( $tz );
4287 $ts = date( 'YmdHis', $unixts );
4288 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4289
4290 # Allow translation of timezones through wiki. date() can return
4291 # whatever crap the system uses, localised or not, so we cannot
4292 # ship premade translations.
4293 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4294 $msg = wfMessage( $key )->inContentLanguage();
4295 if ( $msg->exists() ) {
4296 $tzMsg = $msg->text();
4297 }
4298
4299 date_default_timezone_set( $oldtz );
4300
4301 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4302
4303 # Variable replacement
4304 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4305 $text = $this->replaceVariables( $text );
4306
4307 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4308 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4309
4310 # Signatures
4311 $sigText = $this->getUserSig( $user );
4312 $text = strtr( $text, array(
4313 '~~~~~' => $d,
4314 '~~~~' => "$sigText $d",
4315 '~~~' => $sigText
4316 ) );
4317
4318 # Context links: [[|name]] and [[name (context)|]]
4319 global $wgLegalTitleChars;
4320 $tc = "[$wgLegalTitleChars]";
4321 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4322
4323 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)(\s?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4324 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(\s?($tc+))\\|]]/"; # [[ns:page(context)|]]
4325 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)(\s?\\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4326 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4327
4328 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4329 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4330 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4331 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4332
4333 $t = $this->mTitle->getText();
4334 $m = array();
4335 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4336 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4337 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4338 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4339 } else {
4340 # if there's no context, don't bother duplicating the title
4341 $text = preg_replace( $p2, '[[\\1]]', $text );
4342 }
4343
4344 # Trim trailing whitespace
4345 $text = rtrim( $text );
4346
4347 return $text;
4348 }
4349
4350 /**
4351 * Fetch the user's signature text, if any, and normalize to
4352 * validated, ready-to-insert wikitext.
4353 * If you have pre-fetched the nickname or the fancySig option, you can
4354 * specify them here to save a database query.
4355 * Do not reuse this parser instance after calling getUserSig(),
4356 * as it may have changed if it's the $wgParser.
4357 *
4358 * @param $user User
4359 * @param $nickname String: nickname to use or false to use user's default nickname
4360 * @param $fancySig Boolean: whether the nicknname is the complete signature
4361 * or null to use default value
4362 * @return string
4363 */
4364 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4365 global $wgMaxSigChars;
4366
4367 $username = $user->getName();
4368
4369 # If not given, retrieve from the user object.
4370 if ( $nickname === false )
4371 $nickname = $user->getOption( 'nickname' );
4372
4373 if ( is_null( $fancySig ) ) {
4374 $fancySig = $user->getBoolOption( 'fancysig' );
4375 }
4376
4377 $nickname = $nickname == null ? $username : $nickname;
4378
4379 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4380 $nickname = $username;
4381 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4382 } elseif ( $fancySig !== false ) {
4383 # Sig. might contain markup; validate this
4384 if ( $this->validateSig( $nickname ) !== false ) {
4385 # Validated; clean up (if needed) and return it
4386 return $this->cleanSig( $nickname, true );
4387 } else {
4388 # Failed to validate; fall back to the default
4389 $nickname = $username;
4390 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
4391 }
4392 }
4393
4394 # Make sure nickname doesnt get a sig in a sig
4395 $nickname = $this->cleanSigInSig( $nickname );
4396
4397 # If we're still here, make it a link to the user page
4398 $userText = wfEscapeWikiText( $username );
4399 $nickText = wfEscapeWikiText( $nickname );
4400 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4401
4402 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4403 }
4404
4405 /**
4406 * Check that the user's signature contains no bad XML
4407 *
4408 * @param $text String
4409 * @return mixed An expanded string, or false if invalid.
4410 */
4411 function validateSig( $text ) {
4412 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
4413 }
4414
4415 /**
4416 * Clean up signature text
4417 *
4418 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4419 * 2) Substitute all transclusions
4420 *
4421 * @param $text String
4422 * @param $parsing Whether we're cleaning (preferences save) or parsing
4423 * @return String: signature text
4424 */
4425 function cleanSig( $text, $parsing = false ) {
4426 if ( !$parsing ) {
4427 global $wgTitle;
4428 $this->mOptions = new ParserOptions;
4429 $this->clearState();
4430 $this->setTitle( $wgTitle );
4431 $this->setOutputType = self::OT_PREPROCESS;
4432 }
4433
4434 # Option to disable this feature
4435 if ( !$this->mOptions->getCleanSignatures() ) {
4436 return $text;
4437 }
4438
4439 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4440 # => Move this logic to braceSubstitution()
4441 $substWord = MagicWord::get( 'subst' );
4442 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4443 $substText = '{{' . $substWord->getSynonym( 0 );
4444
4445 $text = preg_replace( $substRegex, $substText, $text );
4446 $text = $this->cleanSigInSig( $text );
4447 $dom = $this->preprocessToDom( $text );
4448 $frame = $this->getPreprocessor()->newFrame();
4449 $text = $frame->expand( $dom );
4450
4451 if ( !$parsing ) {
4452 $text = $this->mStripState->unstripBoth( $text );
4453 }
4454
4455 return $text;
4456 }
4457
4458 /**
4459 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4460 *
4461 * @param $text String
4462 * @return String: signature text with /~{3,5}/ removed
4463 */
4464 function cleanSigInSig( $text ) {
4465 $text = preg_replace( '/~{3,5}/', '', $text );
4466 return $text;
4467 }
4468
4469 /**
4470 * Set up some variables which are usually set up in parse()
4471 * so that an external function can call some class members with confidence
4472 */
4473 public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4474 $this->startParse( $title, $options, $outputType, $clearState );
4475 }
4476
4477 private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4478 $this->setTitle( $title );
4479 $this->mOptions = $options;
4480 $this->setOutputType( $outputType );
4481 if ( $clearState ) {
4482 $this->clearState();
4483 }
4484 }
4485
4486 /**
4487 * Wrapper for preprocess()
4488 *
4489 * @param $text String: the text to preprocess
4490 * @param $options ParserOptions: options
4491 * @param $title Title object or null to use $wgTitle
4492 * @return String
4493 */
4494 public function transformMsg( $text, $options, $title = null ) {
4495 static $executing = false;
4496
4497 # Guard against infinite recursion
4498 if ( $executing ) {
4499 return $text;
4500 }
4501 $executing = true;
4502
4503 wfProfileIn( __METHOD__ );
4504 if ( !$title ) {
4505 global $wgTitle;
4506 $title = $wgTitle;
4507 }
4508 if ( !$title ) {
4509 # It's not uncommon having a null $wgTitle in scripts. See r80898
4510 # Create a ghost title in such case
4511 $title = Title::newFromText( 'Dwimmerlaik' );
4512 }
4513 $text = $this->preprocess( $text, $title, $options );
4514
4515 $executing = false;
4516 wfProfileOut( __METHOD__ );
4517 return $text;
4518 }
4519
4520 /**
4521 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4522 * The callback should have the following form:
4523 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4524 *
4525 * Transform and return $text. Use $parser for any required context, e.g. use
4526 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4527 *
4528 * Hooks may return extended information by returning an array, of which the
4529 * first numbered element (index 0) must be the return string, and all other
4530 * entries are extracted into local variables within an internal function
4531 * in the Parser class.
4532 *
4533 * This interface (introduced r61913) appears to be undocumented, but
4534 * 'markerName' is used by some core tag hooks to override which strip
4535 * array their results are placed in. **Use great caution if attempting
4536 * this interface, as it is not documented and injudicious use could smash
4537 * private variables.**
4538 *
4539 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4540 * @param $callback Mixed: the callback function (and object) to use for the tag
4541 * @return The old value of the mTagHooks array associated with the hook
4542 */
4543 public function setHook( $tag, $callback ) {
4544 $tag = strtolower( $tag );
4545 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4546 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4547 $this->mTagHooks[$tag] = $callback;
4548 if ( !in_array( $tag, $this->mStripList ) ) {
4549 $this->mStripList[] = $tag;
4550 }
4551
4552 return $oldVal;
4553 }
4554
4555 /**
4556 * As setHook(), but letting the contents be parsed.
4557 *
4558 * Transparent tag hooks are like regular XML-style tag hooks, except they
4559 * operate late in the transformation sequence, on HTML instead of wikitext.
4560 *
4561 * This is probably obsoleted by things dealing with parser frames?
4562 * The only extension currently using it is geoserver.
4563 *
4564 * @since 1.10
4565 * @todo better document or deprecate this
4566 *
4567 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4568 * @param $callback Mixed: the callback function (and object) to use for the tag
4569 * @return The old value of the mTagHooks array associated with the hook
4570 */
4571 function setTransparentTagHook( $tag, $callback ) {
4572 $tag = strtolower( $tag );
4573 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4574 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4575 $this->mTransparentTagHooks[$tag] = $callback;
4576
4577 return $oldVal;
4578 }
4579
4580 /**
4581 * Remove all tag hooks
4582 */
4583 function clearTagHooks() {
4584 $this->mTagHooks = array();
4585 $this->mStripList = $this->mDefaultStripList;
4586 }
4587
4588 /**
4589 * Remove a specific tag hook. Should not be called on $wgParser.
4590 * Does not change the strip list.
4591 *
4592 * @param string $tag
4593 * @return void
4594 */
4595 function clearTagHook( $tag ) {
4596 if ( isset( $this->mTagHooks[$tag] ) ) {
4597 unset( $this->mTagHooks[$tag] );
4598 }
4599 }
4600
4601 /**
4602 * Create a function, e.g. {{sum:1|2|3}}
4603 * The callback function should have the form:
4604 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4605 *
4606 * Or with SFH_OBJECT_ARGS:
4607 * function myParserFunction( $parser, $frame, $args ) { ... }
4608 *
4609 * The callback may either return the text result of the function, or an array with the text
4610 * in element 0, and a number of flags in the other elements. The names of the flags are
4611 * specified in the keys. Valid flags are:
4612 * found The text returned is valid, stop processing the template. This
4613 * is on by default.
4614 * nowiki Wiki markup in the return value should be escaped
4615 * isHTML The returned text is HTML, armour it against wikitext transformation
4616 *
4617 * @param $id String: The magic word ID
4618 * @param $callback Mixed: the callback function (and object) to use
4619 * @param $flags Integer: a combination of the following flags:
4620 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4621 *
4622 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4623 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4624 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4625 * the arguments, and to control the way they are expanded.
4626 *
4627 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4628 * arguments, for instance:
4629 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4630 *
4631 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4632 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4633 * working if/when this is changed.
4634 *
4635 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4636 * expansion.
4637 *
4638 * Please read the documentation in includes/parser/Preprocessor.php for more information
4639 * about the methods available in PPFrame and PPNode.
4640 *
4641 * @return The old callback function for this name, if any
4642 */
4643 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4644 global $wgContLang;
4645
4646 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4647 $this->mFunctionHooks[$id] = array( $callback, $flags );
4648
4649 # Add to function cache
4650 $mw = MagicWord::get( $id );
4651 if ( !$mw )
4652 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4653
4654 $synonyms = $mw->getSynonyms();
4655 $sensitive = intval( $mw->isCaseSensitive() );
4656
4657 foreach ( $synonyms as $syn ) {
4658 # Case
4659 if ( !$sensitive ) {
4660 $syn = $wgContLang->lc( $syn );
4661 }
4662 # Add leading hash
4663 if ( !( $flags & SFH_NO_HASH ) ) {
4664 $syn = '#' . $syn;
4665 }
4666 # Remove trailing colon
4667 if ( substr( $syn, -1, 1 ) === ':' ) {
4668 $syn = substr( $syn, 0, -1 );
4669 }
4670 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4671 }
4672 return $oldVal;
4673 }
4674
4675 /**
4676 * Get all registered function hook identifiers
4677 *
4678 * @return Array
4679 */
4680 function getFunctionHooks() {
4681 return array_keys( $this->mFunctionHooks );
4682 }
4683
4684 /**
4685 * Create a tag function, e.g. <test>some stuff</test>.
4686 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4687 * Unlike parser functions, their content is not preprocessed.
4688 */
4689 function setFunctionTagHook( $tag, $callback, $flags ) {
4690 $tag = strtolower( $tag );
4691 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4692 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4693 $this->mFunctionTagHooks[$tag] : null;
4694 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4695
4696 if ( !in_array( $tag, $this->mStripList ) ) {
4697 $this->mStripList[] = $tag;
4698 }
4699
4700 return $old;
4701 }
4702
4703 /**
4704 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4705 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4706 * Placeholders created in Skin::makeLinkObj()
4707 * Returns an array of link CSS classes, indexed by PDBK.
4708 */
4709 function replaceLinkHolders( &$text, $options = 0 ) {
4710 return $this->mLinkHolders->replace( $text );
4711 }
4712
4713 /**
4714 * Replace <!--LINK--> link placeholders with plain text of links
4715 * (not HTML-formatted).
4716 *
4717 * @param $text String
4718 * @return String
4719 */
4720 function replaceLinkHoldersText( $text ) {
4721 return $this->mLinkHolders->replaceText( $text );
4722 }
4723
4724 /**
4725 * Renders an image gallery from a text with one line per image.
4726 * text labels may be given by using |-style alternative text. E.g.
4727 * Image:one.jpg|The number "1"
4728 * Image:tree.jpg|A tree
4729 * given as text will return the HTML of a gallery with two images,
4730 * labeled 'The number "1"' and
4731 * 'A tree'.
4732 *
4733 * @param string $text
4734 * @param array $param
4735 * @return string HTML
4736 */
4737 function renderImageGallery( $text, $params ) {
4738 $ig = new ImageGallery();
4739 $ig->setContextTitle( $this->mTitle );
4740 $ig->setShowBytes( false );
4741 $ig->setShowFilename( false );
4742 $ig->setParser( $this );
4743 $ig->setHideBadImages();
4744 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4745
4746 if ( isset( $params['showfilename'] ) ) {
4747 $ig->setShowFilename( true );
4748 } else {
4749 $ig->setShowFilename( false );
4750 }
4751 if ( isset( $params['caption'] ) ) {
4752 $caption = $params['caption'];
4753 $caption = htmlspecialchars( $caption );
4754 $caption = $this->replaceInternalLinks( $caption );
4755 $ig->setCaptionHtml( $caption );
4756 }
4757 if ( isset( $params['perrow'] ) ) {
4758 $ig->setPerRow( $params['perrow'] );
4759 }
4760 if ( isset( $params['widths'] ) ) {
4761 $ig->setWidths( $params['widths'] );
4762 }
4763 if ( isset( $params['heights'] ) ) {
4764 $ig->setHeights( $params['heights'] );
4765 }
4766
4767 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4768
4769 $lines = StringUtils::explode( "\n", $text );
4770 foreach ( $lines as $line ) {
4771 # match lines like these:
4772 # Image:someimage.jpg|This is some image
4773 $matches = array();
4774 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4775 # Skip empty lines
4776 if ( count( $matches ) == 0 ) {
4777 continue;
4778 }
4779
4780 if ( strpos( $matches[0], '%' ) !== false ) {
4781 $matches[1] = rawurldecode( $matches[1] );
4782 }
4783 $title = Title::newFromText( $matches[1], NS_FILE );
4784 if ( is_null( $title ) ) {
4785 # Bogus title. Ignore these so we don't bomb out later.
4786 continue;
4787 }
4788
4789 $label = '';
4790 $alt = '';
4791 if ( isset( $matches[3] ) ) {
4792 // look for an |alt= definition while trying not to break existing
4793 // captions with multiple pipes (|) in it, until a more sensible grammar
4794 // is defined for images in galleries
4795
4796 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4797 $altmatches = StringUtils::explode('|', $matches[3]);
4798 $magicWordAlt = MagicWord::get( 'img_alt' );
4799
4800 foreach ( $altmatches as $altmatch ) {
4801 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch );
4802 if ( $match ) {
4803 $alt = $this->stripAltText( $match, false );
4804 }
4805 else {
4806 // concatenate all other pipes
4807 $label .= '|' . $altmatch;
4808 }
4809 }
4810 // remove the first pipe
4811 $label = substr( $label, 1 );
4812 }
4813
4814 $ig->add( $title, $label, $alt );
4815 }
4816 return $ig->toHTML();
4817 }
4818
4819 function getImageParams( $handler ) {
4820 if ( $handler ) {
4821 $handlerClass = get_class( $handler );
4822 } else {
4823 $handlerClass = '';
4824 }
4825 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4826 # Initialise static lists
4827 static $internalParamNames = array(
4828 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4829 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4830 'bottom', 'text-bottom' ),
4831 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4832 'upright', 'border', 'link', 'alt' ),
4833 );
4834 static $internalParamMap;
4835 if ( !$internalParamMap ) {
4836 $internalParamMap = array();
4837 foreach ( $internalParamNames as $type => $names ) {
4838 foreach ( $names as $name ) {
4839 $magicName = str_replace( '-', '_', "img_$name" );
4840 $internalParamMap[$magicName] = array( $type, $name );
4841 }
4842 }
4843 }
4844
4845 # Add handler params
4846 $paramMap = $internalParamMap;
4847 if ( $handler ) {
4848 $handlerParamMap = $handler->getParamMap();
4849 foreach ( $handlerParamMap as $magic => $paramName ) {
4850 $paramMap[$magic] = array( 'handler', $paramName );
4851 }
4852 }
4853 $this->mImageParams[$handlerClass] = $paramMap;
4854 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4855 }
4856 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4857 }
4858
4859 /**
4860 * Parse image options text and use it to make an image
4861 *
4862 * @param $title Title
4863 * @param $options String
4864 * @param $holders LinkHolderArray
4865 * @return string HTML
4866 */
4867 function makeImage( $title, $options, $holders = false ) {
4868 # Check if the options text is of the form "options|alt text"
4869 # Options are:
4870 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4871 # * left no resizing, just left align. label is used for alt= only
4872 # * right same, but right aligned
4873 # * none same, but not aligned
4874 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4875 # * center center the image
4876 # * frame Keep original image size, no magnify-button.
4877 # * framed Same as "frame"
4878 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4879 # * upright reduce width for upright images, rounded to full __0 px
4880 # * border draw a 1px border around the image
4881 # * alt Text for HTML alt attribute (defaults to empty)
4882 # * link Set the target of the image link. Can be external, interwiki, or local
4883 # vertical-align values (no % or length right now):
4884 # * baseline
4885 # * sub
4886 # * super
4887 # * top
4888 # * text-top
4889 # * middle
4890 # * bottom
4891 # * text-bottom
4892
4893 $parts = StringUtils::explode( "|", $options );
4894
4895 # Give extensions a chance to select the file revision for us
4896 $time = $sha1 = $descQuery = false;
4897 wfRunHooks( 'BeforeParserFetchFileAndTitle',
4898 array( $this, $title, &$time, &$sha1, &$descQuery ) );
4899 # Fetch and register the file (file title may be different via hooks)
4900 list( $file, $title ) = $this->fetchFileAndTitle( $title, $time, $sha1 );
4901
4902 # Get parameter map
4903 $handler = $file ? $file->getHandler() : false;
4904
4905 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4906
4907 if ( !$file ) {
4908 $this->addTrackingCategory( 'broken-file-category' );
4909 }
4910
4911 # Process the input parameters
4912 $caption = '';
4913 $params = array( 'frame' => array(), 'handler' => array(),
4914 'horizAlign' => array(), 'vertAlign' => array() );
4915 foreach ( $parts as $part ) {
4916 $part = trim( $part );
4917 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4918 $validated = false;
4919 if ( isset( $paramMap[$magicName] ) ) {
4920 list( $type, $paramName ) = $paramMap[$magicName];
4921
4922 # Special case; width and height come in one variable together
4923 if ( $type === 'handler' && $paramName === 'width' ) {
4924 $m = array();
4925 # (bug 13500) In both cases (width/height and width only),
4926 # permit trailing "px" for backward compatibility.
4927 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4928 $width = intval( $m[1] );
4929 $height = intval( $m[2] );
4930 if ( $handler->validateParam( 'width', $width ) ) {
4931 $params[$type]['width'] = $width;
4932 $validated = true;
4933 }
4934 if ( $handler->validateParam( 'height', $height ) ) {
4935 $params[$type]['height'] = $height;
4936 $validated = true;
4937 }
4938 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4939 $width = intval( $value );
4940 if ( $handler->validateParam( 'width', $width ) ) {
4941 $params[$type]['width'] = $width;
4942 $validated = true;
4943 }
4944 } # else no validation -- bug 13436
4945 } else {
4946 if ( $type === 'handler' ) {
4947 # Validate handler parameter
4948 $validated = $handler->validateParam( $paramName, $value );
4949 } else {
4950 # Validate internal parameters
4951 switch( $paramName ) {
4952 case 'manualthumb':
4953 case 'alt':
4954 # @todo FIXME: Possibly check validity here for
4955 # manualthumb? downstream behavior seems odd with
4956 # missing manual thumbs.
4957 $validated = true;
4958 $value = $this->stripAltText( $value, $holders );
4959 break;
4960 case 'link':
4961 $chars = self::EXT_LINK_URL_CLASS;
4962 $prots = $this->mUrlProtocols;
4963 if ( $value === '' ) {
4964 $paramName = 'no-link';
4965 $value = true;
4966 $validated = true;
4967 } elseif ( preg_match( "/^$prots/", $value ) ) {
4968 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
4969 $paramName = 'link-url';
4970 $this->mOutput->addExternalLink( $value );
4971 if ( $this->mOptions->getExternalLinkTarget() ) {
4972 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
4973 }
4974 $validated = true;
4975 }
4976 } else {
4977 $linkTitle = Title::newFromText( $value );
4978 if ( $linkTitle ) {
4979 $paramName = 'link-title';
4980 $value = $linkTitle;
4981 $this->mOutput->addLink( $linkTitle );
4982 $validated = true;
4983 }
4984 }
4985 break;
4986 default:
4987 # Most other things appear to be empty or numeric...
4988 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4989 }
4990 }
4991
4992 if ( $validated ) {
4993 $params[$type][$paramName] = $value;
4994 }
4995 }
4996 }
4997 if ( !$validated ) {
4998 $caption = $part;
4999 }
5000 }
5001
5002 # Process alignment parameters
5003 if ( $params['horizAlign'] ) {
5004 $params['frame']['align'] = key( $params['horizAlign'] );
5005 }
5006 if ( $params['vertAlign'] ) {
5007 $params['frame']['valign'] = key( $params['vertAlign'] );
5008 }
5009
5010 $params['frame']['caption'] = $caption;
5011
5012 # Will the image be presented in a frame, with the caption below?
5013 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5014 isset( $params['frame']['framed'] ) ||
5015 isset( $params['frame']['thumbnail'] ) ||
5016 isset( $params['frame']['manualthumb'] );
5017
5018 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5019 # came to also set the caption, ordinary text after the image -- which
5020 # makes no sense, because that just repeats the text multiple times in
5021 # screen readers. It *also* came to set the title attribute.
5022 #
5023 # Now that we have an alt attribute, we should not set the alt text to
5024 # equal the caption: that's worse than useless, it just repeats the
5025 # text. This is the framed/thumbnail case. If there's no caption, we
5026 # use the unnamed parameter for alt text as well, just for the time be-
5027 # ing, if the unnamed param is set and the alt param is not.
5028 #
5029 # For the future, we need to figure out if we want to tweak this more,
5030 # e.g., introducing a title= parameter for the title; ignoring the un-
5031 # named parameter entirely for images without a caption; adding an ex-
5032 # plicit caption= parameter and preserving the old magic unnamed para-
5033 # meter for BC; ...
5034 if ( $imageIsFramed ) { # Framed image
5035 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5036 # No caption or alt text, add the filename as the alt text so
5037 # that screen readers at least get some description of the image
5038 $params['frame']['alt'] = $title->getText();
5039 }
5040 # Do not set $params['frame']['title'] because tooltips don't make sense
5041 # for framed images
5042 } else { # Inline image
5043 if ( !isset( $params['frame']['alt'] ) ) {
5044 # No alt text, use the "caption" for the alt text
5045 if ( $caption !== '') {
5046 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5047 } else {
5048 # No caption, fall back to using the filename for the
5049 # alt text
5050 $params['frame']['alt'] = $title->getText();
5051 }
5052 }
5053 # Use the "caption" for the tooltip text
5054 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5055 }
5056
5057 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
5058
5059 # Linker does the rest
5060 $ret = Linker::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5061 $time, $descQuery, $this->mOptions->getThumbSize() );
5062
5063 # Give the handler a chance to modify the parser object
5064 if ( $handler ) {
5065 $handler->parserTransformHook( $this, $file );
5066 }
5067
5068 return $ret;
5069 }
5070
5071 /**
5072 * @param $caption
5073 * @param $holders LinkHolderArray
5074 * @return mixed|String
5075 */
5076 protected function stripAltText( $caption, $holders ) {
5077 # Strip bad stuff out of the title (tooltip). We can't just use
5078 # replaceLinkHoldersText() here, because if this function is called
5079 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5080 if ( $holders ) {
5081 $tooltip = $holders->replaceText( $caption );
5082 } else {
5083 $tooltip = $this->replaceLinkHoldersText( $caption );
5084 }
5085
5086 # make sure there are no placeholders in thumbnail attributes
5087 # that are later expanded to html- so expand them now and
5088 # remove the tags
5089 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5090 $tooltip = Sanitizer::stripAllTags( $tooltip );
5091
5092 return $tooltip;
5093 }
5094
5095 /**
5096 * Set a flag in the output object indicating that the content is dynamic and
5097 * shouldn't be cached.
5098 */
5099 function disableCache() {
5100 wfDebug( "Parser output marked as uncacheable.\n" );
5101 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5102 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5103 }
5104
5105 /**
5106 * Callback from the Sanitizer for expanding items found in HTML attribute
5107 * values, so they can be safely tested and escaped.
5108 *
5109 * @param $text String
5110 * @param $frame PPFrame
5111 * @return String
5112 */
5113 function attributeStripCallback( &$text, $frame = false ) {
5114 $text = $this->replaceVariables( $text, $frame );
5115 $text = $this->mStripState->unstripBoth( $text );
5116 return $text;
5117 }
5118
5119 /**
5120 * Accessor
5121 *
5122 * @return array
5123 */
5124 function getTags() {
5125 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ) );
5126 }
5127
5128 /**
5129 * Replace transparent tags in $text with the values given by the callbacks.
5130 *
5131 * Transparent tag hooks are like regular XML-style tag hooks, except they
5132 * operate late in the transformation sequence, on HTML instead of wikitext.
5133 *
5134 * @param $text string
5135 *
5136 * @return string
5137 */
5138 function replaceTransparentTags( $text ) {
5139 $matches = array();
5140 $elements = array_keys( $this->mTransparentTagHooks );
5141 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5142 $replacements = array();
5143
5144 foreach ( $matches as $marker => $data ) {
5145 list( $element, $content, $params, $tag ) = $data;
5146 $tagName = strtolower( $element );
5147 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5148 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
5149 } else {
5150 $output = $tag;
5151 }
5152 $replacements[$marker] = $output;
5153 }
5154 return strtr( $text, $replacements );
5155 }
5156
5157 /**
5158 * Break wikitext input into sections, and either pull or replace
5159 * some particular section's text.
5160 *
5161 * External callers should use the getSection and replaceSection methods.
5162 *
5163 * @param $text String: Page wikitext
5164 * @param $section String: a section identifier string of the form:
5165 * <flag1> - <flag2> - ... - <section number>
5166 *
5167 * Currently the only recognised flag is "T", which means the target section number
5168 * was derived during a template inclusion parse, in other words this is a template
5169 * section edit link. If no flags are given, it was an ordinary section edit link.
5170 * This flag is required to avoid a section numbering mismatch when a section is
5171 * enclosed by <includeonly> (bug 6563).
5172 *
5173 * The section number 0 pulls the text before the first heading; other numbers will
5174 * pull the given section along with its lower-level subsections. If the section is
5175 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5176 *
5177 * @param $mode String: one of "get" or "replace"
5178 * @param $newText String: replacement text for section data.
5179 * @return String: for "get", the extracted section text.
5180 * for "replace", the whole page with the section replaced.
5181 * If the page is empty and section 0 is requested, $text (as '')
5182 * is returned
5183 */
5184 private function extractSections( $text, $section, $mode, $newText='' ) {
5185 global $wgTitle; # not generally used but removes an ugly failure mode
5186 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5187 $outText = '';
5188 $frame = $this->getPreprocessor()->newFrame();
5189
5190 # Process section extraction flags
5191 $flags = 0;
5192 $sectionParts = explode( '-', $section );
5193 $sectionIndex = array_pop( $sectionParts );
5194 foreach ( $sectionParts as $part ) {
5195 if ( $part === 'T' ) {
5196 $flags |= self::PTD_FOR_INCLUSION;
5197 }
5198 }
5199 # Preprocess the text
5200 $root = $this->preprocessToDom( $text, $flags );
5201
5202 # <h> nodes indicate section breaks
5203 # They can only occur at the top level, so we can find them by iterating the root's children
5204 $node = $root->getFirstChild();
5205
5206 # Find the target section
5207 if ( $sectionIndex == 0 ) {
5208 # Section zero doesn't nest, level=big
5209 $targetLevel = 1000;
5210 if ( !$node ) {
5211 # The page definitely exists - we checked that earlier - so it must be blank: see bug #14005
5212 return $text;
5213 }
5214 } else {
5215 while ( $node ) {
5216 if ( $node->getName() === 'h' ) {
5217 $bits = $node->splitHeading();
5218 if ( $bits['i'] == $sectionIndex ) {
5219 $targetLevel = $bits['level'];
5220 break;
5221 }
5222 }
5223 if ( $mode === 'replace' ) {
5224 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5225 }
5226 $node = $node->getNextSibling();
5227 }
5228 }
5229
5230 if ( !$node ) {
5231 # Not found
5232 if ( $mode === 'get' ) {
5233 return $newText;
5234 } else {
5235 return $text;
5236 }
5237 }
5238
5239 # Find the end of the section, including nested sections
5240 do {
5241 if ( $node->getName() === 'h' ) {
5242 $bits = $node->splitHeading();
5243 $curLevel = $bits['level'];
5244 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5245 break;
5246 }
5247 }
5248 if ( $mode === 'get' ) {
5249 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5250 }
5251 $node = $node->getNextSibling();
5252 } while ( $node );
5253
5254 # Write out the remainder (in replace mode only)
5255 if ( $mode === 'replace' ) {
5256 # Output the replacement text
5257 # Add two newlines on -- trailing whitespace in $newText is conventionally
5258 # stripped by the editor, so we need both newlines to restore the paragraph gap
5259 # Only add trailing whitespace if there is newText
5260 if ( $newText != "" ) {
5261 $outText .= $newText . "\n\n";
5262 }
5263
5264 while ( $node ) {
5265 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5266 $node = $node->getNextSibling();
5267 }
5268 }
5269
5270 if ( is_string( $outText ) ) {
5271 # Re-insert stripped tags
5272 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5273 }
5274
5275 return $outText;
5276 }
5277
5278 /**
5279 * This function returns the text of a section, specified by a number ($section).
5280 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5281 * the first section before any such heading (section 0).
5282 *
5283 * If a section contains subsections, these are also returned.
5284 *
5285 * @param $text String: text to look in
5286 * @param $section String: section identifier
5287 * @param $deftext String: default to return if section is not found
5288 * @return string text of the requested section
5289 */
5290 public function getSection( $text, $section, $deftext='' ) {
5291 return $this->extractSections( $text, $section, "get", $deftext );
5292 }
5293
5294 /**
5295 * This function returns $oldtext after the content of the section
5296 * specified by $section has been replaced with $text.
5297 *
5298 * @param $oldtext String: former text of the article
5299 * @param $section Numeric: section identifier
5300 * @param $text String: replacing text
5301 * @return String: modified text
5302 */
5303 public function replaceSection( $oldtext, $section, $text ) {
5304 return $this->extractSections( $oldtext, $section, "replace", $text );
5305 }
5306
5307 /**
5308 * Get the ID of the revision we are parsing
5309 *
5310 * @return Mixed: integer or null
5311 */
5312 function getRevisionId() {
5313 return $this->mRevisionId;
5314 }
5315
5316 /**
5317 * Get the revision object for $this->mRevisionId
5318 *
5319 * @return Revision|null either a Revision object or null
5320 */
5321 protected function getRevisionObject() {
5322 if ( !is_null( $this->mRevisionObject ) ) {
5323 return $this->mRevisionObject;
5324 }
5325 if ( is_null( $this->mRevisionId ) ) {
5326 return null;
5327 }
5328
5329 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
5330 return $this->mRevisionObject;
5331 }
5332
5333 /**
5334 * Get the timestamp associated with the current revision, adjusted for
5335 * the default server-local timestamp
5336 */
5337 function getRevisionTimestamp() {
5338 if ( is_null( $this->mRevisionTimestamp ) ) {
5339 wfProfileIn( __METHOD__ );
5340
5341 $revObject = $this->getRevisionObject();
5342 $timestamp = $revObject ? $revObject->getTimestamp() : false;
5343
5344 if( $timestamp !== false ) {
5345 global $wgContLang;
5346
5347 # The cryptic '' timezone parameter tells to use the site-default
5348 # timezone offset instead of the user settings.
5349 #
5350 # Since this value will be saved into the parser cache, served
5351 # to other users, and potentially even used inside links and such,
5352 # it needs to be consistent for all visitors.
5353 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5354 }
5355
5356 wfProfileOut( __METHOD__ );
5357 }
5358 return $this->mRevisionTimestamp;
5359 }
5360
5361 /**
5362 * Get the name of the user that edited the last revision
5363 *
5364 * @return String: user name
5365 */
5366 function getRevisionUser() {
5367 if( is_null( $this->mRevisionUser ) ) {
5368 $revObject = $this->getRevisionObject();
5369
5370 # if this template is subst: the revision id will be blank,
5371 # so just use the current user's name
5372 if( $revObject ) {
5373 $this->mRevisionUser = $revObject->getUserText();
5374 } elseif( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5375 $this->mRevisionUser = $this->getUser()->getName();
5376 }
5377 }
5378 return $this->mRevisionUser;
5379 }
5380
5381 /**
5382 * Mutator for $mDefaultSort
5383 *
5384 * @param $sort New value
5385 */
5386 public function setDefaultSort( $sort ) {
5387 $this->mDefaultSort = $sort;
5388 $this->mOutput->setProperty( 'defaultsort', $sort );
5389 }
5390
5391 /**
5392 * Accessor for $mDefaultSort
5393 * Will use the empty string if none is set.
5394 *
5395 * This value is treated as a prefix, so the
5396 * empty string is equivalent to sorting by
5397 * page name.
5398 *
5399 * @return string
5400 */
5401 public function getDefaultSort() {
5402 if ( $this->mDefaultSort !== false ) {
5403 return $this->mDefaultSort;
5404 } else {
5405 return '';
5406 }
5407 }
5408
5409 /**
5410 * Accessor for $mDefaultSort
5411 * Unlike getDefaultSort(), will return false if none is set
5412 *
5413 * @return string or false
5414 */
5415 public function getCustomDefaultSort() {
5416 return $this->mDefaultSort;
5417 }
5418
5419 /**
5420 * Try to guess the section anchor name based on a wikitext fragment
5421 * presumably extracted from a heading, for example "Header" from
5422 * "== Header ==".
5423 *
5424 * @param $text string
5425 *
5426 * @return string
5427 */
5428 public function guessSectionNameFromWikiText( $text ) {
5429 # Strip out wikitext links(they break the anchor)
5430 $text = $this->stripSectionName( $text );
5431 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5432 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5433 }
5434
5435 /**
5436 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5437 * instead. For use in redirects, since IE6 interprets Redirect: headers
5438 * as something other than UTF-8 (apparently?), resulting in breakage.
5439 *
5440 * @param $text String: The section name
5441 * @return string An anchor
5442 */
5443 public function guessLegacySectionNameFromWikiText( $text ) {
5444 # Strip out wikitext links(they break the anchor)
5445 $text = $this->stripSectionName( $text );
5446 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5447 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
5448 }
5449
5450 /**
5451 * Strips a text string of wikitext for use in a section anchor
5452 *
5453 * Accepts a text string and then removes all wikitext from the
5454 * string and leaves only the resultant text (i.e. the result of
5455 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5456 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5457 * to create valid section anchors by mimicing the output of the
5458 * parser when headings are parsed.
5459 *
5460 * @param $text String: text string to be stripped of wikitext
5461 * for use in a Section anchor
5462 * @return Filtered text string
5463 */
5464 public function stripSectionName( $text ) {
5465 # Strip internal link markup
5466 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5467 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5468
5469 # Strip external link markup
5470 # @todo FIXME: Not tolerant to blank link text
5471 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5472 # on how many empty links there are on the page - need to figure that out.
5473 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5474
5475 # Parse wikitext quotes (italics & bold)
5476 $text = $this->doQuotes( $text );
5477
5478 # Strip HTML tags
5479 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5480 return $text;
5481 }
5482
5483 /**
5484 * strip/replaceVariables/unstrip for preprocessor regression testing
5485 *
5486 * @return string
5487 */
5488 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
5489 $this->startParse( $title, $options, $outputType, true );
5490
5491 $text = $this->replaceVariables( $text );
5492 $text = $this->mStripState->unstripBoth( $text );
5493 $text = Sanitizer::removeHTMLtags( $text );
5494 return $text;
5495 }
5496
5497 function testPst( $text, Title $title, ParserOptions $options ) {
5498 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5499 }
5500
5501 function testPreprocess( $text, Title $title, ParserOptions $options ) {
5502 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5503 }
5504
5505 /**
5506 * Call a callback function on all regions of the given text that are not
5507 * inside strip markers, and replace those regions with the return value
5508 * of the callback. For example, with input:
5509 *
5510 * aaa<MARKER>bbb
5511 *
5512 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5513 * two strings will be replaced with the value returned by the callback in
5514 * each case.
5515 *
5516 * @return string
5517 */
5518 function markerSkipCallback( $s, $callback ) {
5519 $i = 0;
5520 $out = '';
5521 while ( $i < strlen( $s ) ) {
5522 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5523 if ( $markerStart === false ) {
5524 $out .= call_user_func( $callback, substr( $s, $i ) );
5525 break;
5526 } else {
5527 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5528 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5529 if ( $markerEnd === false ) {
5530 $out .= substr( $s, $markerStart );
5531 break;
5532 } else {
5533 $markerEnd += strlen( self::MARKER_SUFFIX );
5534 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5535 $i = $markerEnd;
5536 }
5537 }
5538 }
5539 return $out;
5540 }
5541
5542 /**
5543 * Save the parser state required to convert the given half-parsed text to
5544 * HTML. "Half-parsed" in this context means the output of
5545 * recursiveTagParse() or internalParse(). This output has strip markers
5546 * from replaceVariables (extensionSubstitution() etc.), and link
5547 * placeholders from replaceLinkHolders().
5548 *
5549 * Returns an array which can be serialized and stored persistently. This
5550 * array can later be loaded into another parser instance with
5551 * unserializeHalfParsedText(). The text can then be safely incorporated into
5552 * the return value of a parser hook.
5553 *
5554 * @return array
5555 */
5556 function serializeHalfParsedText( $text ) {
5557 wfProfileIn( __METHOD__ );
5558 $data = array(
5559 'text' => $text,
5560 'version' => self::HALF_PARSED_VERSION,
5561 'stripState' => $this->mStripState->getSubState( $text ),
5562 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
5563 );
5564 wfProfileOut( __METHOD__ );
5565 return $data;
5566 }
5567
5568 /**
5569 * Load the parser state given in the $data array, which is assumed to
5570 * have been generated by serializeHalfParsedText(). The text contents is
5571 * extracted from the array, and its markers are transformed into markers
5572 * appropriate for the current Parser instance. This transformed text is
5573 * returned, and can be safely included in the return value of a parser
5574 * hook.
5575 *
5576 * If the $data array has been stored persistently, the caller should first
5577 * check whether it is still valid, by calling isValidHalfParsedText().
5578 *
5579 * @param $data Serialized data
5580 * @return String
5581 */
5582 function unserializeHalfParsedText( $data ) {
5583 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
5584 throw new MWException( __METHOD__.': invalid version' );
5585 }
5586
5587 # First, extract the strip state.
5588 $texts = array( $data['text'] );
5589 $texts = $this->mStripState->merge( $data['stripState'], $texts );
5590
5591 # Now renumber links
5592 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
5593
5594 # Should be good to go.
5595 return $texts[0];
5596 }
5597
5598 /**
5599 * Returns true if the given array, presumed to be generated by
5600 * serializeHalfParsedText(), is compatible with the current version of the
5601 * parser.
5602 *
5603 * @param $data Array
5604 *
5605 * @return bool
5606 */
5607 function isValidHalfParsedText( $data ) {
5608 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
5609 }
5610 }