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