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