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