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