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