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