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