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