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