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