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