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