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