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