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