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