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