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