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