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