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