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