Moved constant values from constructor to class definition
[lhc/web/wiklou.git] / includes / parser / Parser.php
1 <?php
2 /**
3 * @defgroup Parser Parser
4 *
5 * @file
6 * @ingroup Parser
7 * File for Parser and related classes
8 */
9
10
11 /**
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
16 *
17 * <pre>
18 * There are five main entry points into the Parser class:
19 * parse()
20 * produces HTML output
21 * preSaveTransform().
22 * produces altered wiki markup.
23 * preprocess()
24 * removes HTML comments and expands templates
25 * cleanSig()
26 * Cleans a signature before saving it to preferences
27 * extractSections()
28 * Extracts sections from an article for section editing
29 * getPreloadText()
30 * Removes <noinclude> sections, and <includeonly> tags.
31 *
32 * Globals used:
33 * objects: $wgLang, $wgContLang
34 *
35 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 *
37 * settings:
38 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
39 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
40 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * $wgMaxArticleSize*
42 *
43 * * only within ParserOptions
44 * </pre>
45 *
46 * @ingroup Parser
47 */
48 class Parser {
49 /**
50 * Update this version number when the ParserOutput format
51 * changes in an incompatible way, so the parser cache
52 * can automatically discard old data.
53 */
54 const VERSION = '1.6.4';
55
56 # Flags for Parser::setFunctionHook
57 # Also available as global constants from Defines.php
58 const SFH_NO_HASH = 1;
59 const SFH_OBJECT_ARGS = 2;
60
61 # Constants needed for external link processing
62 # Everything except bracket, space, or control characters
63 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F]';
64 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
65 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66
67 # State constants for the definition list colon extraction
68 const COLON_STATE_TEXT = 0;
69 const COLON_STATE_TAG = 1;
70 const COLON_STATE_TAGSTART = 2;
71 const COLON_STATE_CLOSETAG = 3;
72 const COLON_STATE_TAGSLASH = 4;
73 const COLON_STATE_COMMENT = 5;
74 const COLON_STATE_COMMENTDASH = 6;
75 const COLON_STATE_COMMENTDASHDASH = 7;
76
77 # Flags for preprocessToDom
78 const PTD_FOR_INCLUSION = 1;
79
80 # Allowed values for $this->mOutputType
81 # Parameter to startExternalParse().
82 const OT_HTML = 1; # like parse()
83 const OT_WIKI = 2; # like preSaveTransform()
84 const OT_PREPROCESS = 3; # like preprocess()
85 const OT_MSG = 3;
86 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
87
88 # Marker Suffix needs to be accessible staticly.
89 const MARKER_SUFFIX = "-QINU\x7f";
90
91 # Persistent:
92 var $mTagHooks = array();
93 var $mTransparentTagHooks = array();
94 var $mFunctionHooks = array();
95 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
96 var $mFunctionTagHooks = array();
97 var $mStripList = array();
98 var $mDefaultStripList = array();
99 var $mVarCache = array();
100 var $mImageParams = array();
101 var $mImageParamsMagicArray = array();
102 var $mMarkerIndex = 0;
103 var $mFirstCall = true;
104 var $mVariables, $mSubstWords; # Initialised by initialiseVariables()
105 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
106
107
108 # Cleared with clearState():
109 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
110 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
111 var $mLinkHolders, $mLinkID;
112 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
113 var $mTplExpandCache; # empty-frame expansion cache
114 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
115 var $mExpensiveFunctionCount; # number of expensive parser function calls
116 var $mUser; # User object; only used when doing pre-save transform
117
118 # Temporary
119 # These are variables reset at least once per parse regardless of $clearState
120 var $mOptions; # ParserOptions object
121 var $mTitle; # Title context, used for self-link rendering and similar things
122 var $mOutputType; # Output type, one of the OT_xxx constants
123 var $ot; # Shortcut alias, see setOutputType()
124 var $mRevisionObject; # The revision object of the specified revision ID
125 var $mRevisionId; # ID to display in {{REVISIONID}} tags
126 var $mRevisionTimestamp; # The timestamp of the specified revision ID
127 var $mRevisionUser; # Userto display in {{REVISIONUSER}} tag
128 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
129
130 /**
131 * Constructor
132 *
133 * @public
134 */
135 function __construct( $conf = array() ) {
136 $this->mConf = $conf;
137 $this->mUrlProtocols = wfUrlProtocols();
138 $this->mExtLinkBracketedRegex = '/\[(\b(' . wfUrlProtocols() . ')'.
139 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
140 if ( isset( $conf['preprocessorClass'] ) ) {
141 $this->mPreprocessorClass = $conf['preprocessorClass'];
142 } elseif ( extension_loaded( 'domxml' ) ) {
143 # PECL extension that conflicts with the core DOM extension (bug 13770)
144 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
145 $this->mPreprocessorClass = 'Preprocessor_Hash';
146 } elseif ( extension_loaded( 'dom' ) ) {
147 $this->mPreprocessorClass = 'Preprocessor_DOM';
148 } else {
149 $this->mPreprocessorClass = 'Preprocessor_Hash';
150 }
151 }
152
153 /**
154 * Reduce memory usage to reduce the impact of circular references
155 */
156 function __destruct() {
157 if ( isset( $this->mLinkHolders ) ) {
158 $this->mLinkHolders->__destruct();
159 }
160 foreach ( $this as $name => $value ) {
161 unset( $this->$name );
162 }
163 }
164
165 /**
166 * Do various kinds of initialisation on the first call of the parser
167 */
168 function firstCallInit() {
169 if ( !$this->mFirstCall ) {
170 return;
171 }
172 $this->mFirstCall = false;
173
174 wfProfileIn( __METHOD__ );
175
176 CoreParserFunctions::register( $this );
177 CoreTagHooks::register( $this );
178 $this->initialiseVariables();
179
180 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
181 wfProfileOut( __METHOD__ );
182 }
183
184 /**
185 * Clear Parser state
186 *
187 * @private
188 */
189 function clearState() {
190 wfProfileIn( __METHOD__ );
191 if ( $this->mFirstCall ) {
192 $this->firstCallInit();
193 }
194 $this->mOutput = new ParserOutput;
195 $this->mAutonumber = 0;
196 $this->mLastSection = '';
197 $this->mDTopen = false;
198 $this->mIncludeCount = array();
199 $this->mStripState = new StripState;
200 $this->mArgStack = false;
201 $this->mInPre = false;
202 $this->mLinkHolders = new LinkHolderArray( $this );
203 $this->mLinkID = 0;
204 $this->mRevisionObject = $this->mRevisionTimestamp =
205 $this->mRevisionId = $this->mRevisionUser = null;
206 $this->mVarCache = array();
207 $this->mUser = null;
208
209 /**
210 * Prefix for temporary replacement strings for the multipass parser.
211 * \x07 should never appear in input as it's disallowed in XML.
212 * Using it at the front also gives us a little extra robustness
213 * since it shouldn't match when butted up against identifier-like
214 * string constructs.
215 *
216 * Must not consist of all title characters, or else it will change
217 * the behaviour of <nowiki> in a link.
218 */
219 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
220 # Changed to \x7f to allow XML double-parsing -- TS
221 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
222
223
224 # Clear these on every parse, bug 4549
225 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
226
227 $this->mShowToc = true;
228 $this->mForceTocPosition = false;
229 $this->mIncludeSizes = array(
230 'post-expand' => 0,
231 'arg' => 0,
232 );
233 $this->mPPNodeCount = 0;
234 $this->mDefaultSort = false;
235 $this->mHeadings = array();
236 $this->mDoubleUnderscores = array();
237 $this->mExpensiveFunctionCount = 0;
238
239 # Fix cloning
240 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
241 $this->mPreprocessor = null;
242 }
243
244 wfRunHooks( 'ParserClearState', array( &$this ) );
245 wfProfileOut( __METHOD__ );
246 }
247
248 /**
249 * Convert wikitext to HTML
250 * Do not call this function recursively.
251 *
252 * @param $text String: text we want to parse
253 * @param $title A title object
254 * @param $options ParserOptions
255 * @param $linestart boolean
256 * @param $clearState boolean
257 * @param $revid Int: number to pass in {{REVISIONID}}
258 * @return ParserOutput a ParserOutput
259 */
260 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
261 /**
262 * First pass--just handle <nowiki> sections, pass the rest off
263 * to internalParse() which does all the real work.
264 */
265
266 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
267 $fname = __METHOD__.'-' . wfGetCaller();
268 wfProfileIn( __METHOD__ );
269 wfProfileIn( $fname );
270
271 if ( $clearState ) {
272 $this->clearState();
273 }
274
275 $options->resetUsage();
276 $this->mOptions = $options;
277 $this->setTitle( $title ); # Page title has to be set for the pre-processor
278
279 $oldRevisionId = $this->mRevisionId;
280 $oldRevisionObject = $this->mRevisionObject;
281 $oldRevisionTimestamp = $this->mRevisionTimestamp;
282 $oldRevisionUser = $this->mRevisionUser;
283 if ( $revid !== null ) {
284 $this->mRevisionId = $revid;
285 $this->mRevisionObject = null;
286 $this->mRevisionTimestamp = null;
287 $this->mRevisionUser = null;
288 }
289 $this->setOutputType( self::OT_HTML );
290 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
291 # No more strip!
292 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
293 $text = $this->internalParse( $text );
294
295 $text = $this->mStripState->unstripGeneral( $text );
296
297 # Clean up special characters, only run once, next-to-last before doBlockLevels
298 $fixtags = array(
299 # french spaces, last one Guillemet-left
300 # only if there is something before the space
301 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&#160;\\2',
302 # french spaces, Guillemet-right
303 '/(\\302\\253) /' => '\\1&#160;',
304 '/&#160;(!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
305 );
306 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
307
308 $text = $this->doBlockLevels( $text, $linestart );
309
310 $this->replaceLinkHolders( $text );
311
312 /**
313 * The page doesn't get language converted if
314 * a) It's disabled
315 * b) Content isn't converted
316 * c) It's a conversion table
317 */
318 if ( !( $wgDisableLangConversion
319 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
320 || $this->mTitle->isConversionTable() ) ) {
321
322 # The position of the convert() call should not be changed. it
323 # assumes that the links are all replaced and the only thing left
324 # is the <nowiki> mark.
325
326 $text = $wgContLang->convert( $text );
327 }
328
329 /**
330 * A page get its title converted except:
331 * a) Language conversion is globally disabled
332 * b) Title convert is globally disabled
333 * c) The page is a redirect page
334 * d) User request with a "linkconvert" set to "no"
335 * e) A "nocontentconvert" magic word has been set
336 * f) A "notitleconvert" magic word has been set
337 * g) User sets "noconvertlink" in his/her preference
338 *
339 * Note that if a user tries to set a title in a conversion
340 * rule but content conversion was not done, then the parser
341 * won't pick it up. This is probably expected behavior.
342 */
343 if ( !( $wgDisableLangConversion
344 || $wgDisableTitleConversion
345 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
346 || isset( $this->mDoubleUnderscores['notitleconvert'] )
347 || $this->mOutput->getDisplayTitle() !== false ) )
348 {
349 $convruletitle = $wgContLang->getConvRuleTitle();
350 if ( $convruletitle ) {
351 $this->mOutput->setTitleText( $convruletitle );
352 } else {
353 $titleText = $wgContLang->convertTitle( $title );
354 $this->mOutput->setTitleText( $titleText );
355 }
356 }
357
358 $text = $this->mStripState->unstripNoWiki( $text );
359
360 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
361
362 //!JF Move to its own function
363
364 $uniq_prefix = $this->mUniqPrefix;
365 $matches = array();
366 $elements = array_keys( $this->mTransparentTagHooks );
367 $text = $this->extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
368
369 foreach ( $matches as $marker => $data ) {
370 list( $element, $content, $params, $tag ) = $data;
371 $tagName = strtolower( $element );
372 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
373 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
374 } else {
375 $output = $tag;
376 }
377 $this->mStripState->general->setPair( $marker, $output );
378 }
379 $text = $this->mStripState->unstripGeneral( $text );
380
381 $text = Sanitizer::normalizeCharReferences( $text );
382
383 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
384 $text = MWTidy::tidy( $text );
385 } else {
386 # attempt to sanitize at least some nesting problems
387 # (bug #2702 and quite a few others)
388 $tidyregs = array(
389 # ''Something [http://www.cool.com cool''] -->
390 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
391 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
392 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
393 # fix up an anchor inside another anchor, only
394 # at least for a single single nested link (bug 3695)
395 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
396 '\\1\\2</a>\\3</a>\\1\\4</a>',
397 # fix div inside inline elements- doBlockLevels won't wrap a line which
398 # contains a div, so fix it up here; replace
399 # div with escaped text
400 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
401 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
402 # remove empty italic or bold tag pairs, some
403 # introduced by rules above
404 '/<([bi])><\/\\1>/' => '',
405 );
406
407 $text = preg_replace(
408 array_keys( $tidyregs ),
409 array_values( $tidyregs ),
410 $text );
411 }
412 global $wgExpensiveParserFunctionLimit;
413 if ( $this->mExpensiveFunctionCount > $wgExpensiveParserFunctionLimit ) {
414 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount, $wgExpensiveParserFunctionLimit );
415 }
416
417 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
418
419 # Information on include size limits, for the benefit of users who try to skirt them
420 if ( $this->mOptions->getEnableLimitReport() ) {
421 $max = $this->mOptions->getMaxIncludeSize();
422 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
423 $limitReport =
424 "NewPP limit report\n" .
425 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
426 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
427 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
428 $PFreport;
429 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
430 $text .= "\n<!-- \n$limitReport-->\n";
431 }
432 $this->mOutput->setText( $text );
433
434 $this->mRevisionId = $oldRevisionId;
435 $this->mRevisionObject = $oldRevisionObject;
436 $this->mRevisionTimestamp = $oldRevisionTimestamp;
437 $this->mRevisionUser = $oldRevisionUser;
438 wfProfileOut( $fname );
439 wfProfileOut( __METHOD__ );
440
441 return $this->mOutput;
442 }
443
444 /**
445 * Recursive parser entry point that can be called from an extension tag
446 * hook.
447 *
448 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
449 *
450 * @param $text String: text extension wants to have parsed
451 * @param $frame PPFrame: The frame to use for expanding any template variables
452 */
453 function recursiveTagParse( $text, $frame=false ) {
454 wfProfileIn( __METHOD__ );
455 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
456 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
457 $text = $this->internalParse( $text, false, $frame );
458 wfProfileOut( __METHOD__ );
459 return $text;
460 }
461
462 /**
463 * Expand templates and variables in the text, producing valid, static wikitext.
464 * Also removes comments.
465 */
466 function preprocess( $text, $title, $options, $revid = null ) {
467 wfProfileIn( __METHOD__ );
468 $this->clearState();
469 $this->setOutputType( self::OT_PREPROCESS );
470 $options->resetUsage();
471 $this->mOptions = $options;
472 $this->setTitle( $title );
473 if ( $revid !== null ) {
474 $this->mRevisionId = $revid;
475 }
476 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
477 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
478 $text = $this->replaceVariables( $text );
479 $text = $this->mStripState->unstripBoth( $text );
480 wfProfileOut( __METHOD__ );
481 return $text;
482 }
483
484 /**
485 * Process the wikitext for the ?preload= feature. (bug 5210)
486 *
487 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
488 * comments, templates, arguments, tags hooks and parser functions are untouched.
489 */
490 public function getPreloadText( $text, $title, $options ) {
491 # Parser (re)initialisation
492 $this->clearState();
493 $this->setOutputType( self::OT_PLAIN );
494 $options->resetUsage();
495 $this->mOptions = $options;
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;'), urldecode( $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] = urldecode( $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'']] -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1834 $text = $this->doQuotes($text);
1835 }
1836
1837 # Link not escaped by : , create the various objects
1838 if ( $noforce ) {
1839
1840 # Interwikis
1841 wfProfileIn( __METHOD__."-interwiki" );
1842 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1843 $this->mOutput->addLanguageLink( $nt->getFullText() );
1844 $s = rtrim( $s . $prefix );
1845 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
1846 wfProfileOut( __METHOD__."-interwiki" );
1847 continue;
1848 }
1849 wfProfileOut( __METHOD__."-interwiki" );
1850
1851 if ( $ns == NS_FILE ) {
1852 wfProfileIn( __METHOD__."-image" );
1853 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1854 if ( $wasblank ) {
1855 # if no parameters were passed, $text
1856 # becomes something like "File:Foo.png",
1857 # which we don't want to pass on to the
1858 # image generator
1859 $text = '';
1860 } else {
1861 # recursively parse links inside the image caption
1862 # actually, this will parse them in any other parameters, too,
1863 # but it might be hard to fix that, and it doesn't matter ATM
1864 $text = $this->replaceExternalLinks( $text );
1865 $holders->merge( $this->replaceInternalLinks2( $text ) );
1866 }
1867 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1868 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1869 } else {
1870 $s .= $prefix . $trail;
1871 }
1872 $this->mOutput->addImage( $nt->getDBkey() );
1873 wfProfileOut( __METHOD__."-image" );
1874 continue;
1875
1876 }
1877
1878 if ( $ns == NS_CATEGORY ) {
1879 wfProfileIn( __METHOD__."-category" );
1880 $s = rtrim( $s . "\n" ); # bug 87
1881
1882 if ( $wasblank ) {
1883 $sortkey = $this->getDefaultSort();
1884 } else {
1885 $sortkey = $text;
1886 }
1887 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1888 $sortkey = str_replace( "\n", '', $sortkey );
1889 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1890 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1891
1892 /**
1893 * Strip the whitespace Category links produce, see bug 87
1894 * @todo We might want to use trim($tmp, "\n") here.
1895 */
1896 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
1897
1898 wfProfileOut( __METHOD__."-category" );
1899 continue;
1900 }
1901 }
1902
1903 # Self-link checking
1904 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL ) {
1905 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1906 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1907 continue;
1908 }
1909 }
1910
1911 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1912 # FIXME: Should do batch file existence checks, see comment below
1913 if ( $ns == NS_MEDIA ) {
1914 wfProfileIn( __METHOD__."-media" );
1915 # Give extensions a chance to select the file revision for us
1916 $skip = $time = false;
1917 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1918 if ( $skip ) {
1919 $link = $sk->link( $nt );
1920 } else {
1921 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1922 }
1923 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1924 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1925 $this->mOutput->addImage( $nt->getDBkey() );
1926 wfProfileOut( __METHOD__."-media" );
1927 continue;
1928 }
1929
1930 wfProfileIn( __METHOD__."-always_known" );
1931 # Some titles, such as valid special pages or files in foreign repos, should
1932 # be shown as bluelinks even though they're not included in the page table
1933 #
1934 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1935 # batch file existence checks for NS_FILE and NS_MEDIA
1936 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1937 $this->mOutput->addLink( $nt );
1938 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1939 } else {
1940 # Links will be added to the output link list after checking
1941 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1942 }
1943 wfProfileOut( __METHOD__."-always_known" );
1944 }
1945 wfProfileOut( __METHOD__ );
1946 return $holders;
1947 }
1948
1949 /**
1950 * Make a link placeholder. The text returned can be later resolved to a real link with
1951 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1952 * parsing of interwiki links, and secondly to allow all existence checks and
1953 * article length checks (for stub links) to be bundled into a single query.
1954 *
1955 * @deprecated
1956 */
1957 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1958 return $this->mLinkHolders->makeHolder( $nt, $text, $query, $trail, $prefix );
1959 }
1960
1961 /**
1962 * Render a forced-blue link inline; protect against double expansion of
1963 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1964 * Since this little disaster has to split off the trail text to avoid
1965 * breaking URLs in the following text without breaking trails on the
1966 * wiki links, it's been made into a horrible function.
1967 *
1968 * @param $nt Title
1969 * @param $text String
1970 * @param $query String
1971 * @param $trail String
1972 * @param $prefix String
1973 * @return String: HTML-wikitext mix oh yuck
1974 */
1975 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1976 list( $inside, $trail ) = Linker::splitTrail( $trail );
1977 $sk = $this->mOptions->getSkin( $this->mTitle );
1978 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1979 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1980 return $this->armorLinks( $link ) . $trail;
1981 }
1982
1983 /**
1984 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1985 * going to go through further parsing steps before inline URL expansion.
1986 *
1987 * Not needed quite as much as it used to be since free links are a bit
1988 * more sensible these days. But bracketed links are still an issue.
1989 *
1990 * @param $text String: more-or-less HTML
1991 * @return String: less-or-more HTML with NOPARSE bits
1992 */
1993 function armorLinks( $text ) {
1994 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1995 "{$this->mUniqPrefix}NOPARSE$1", $text );
1996 }
1997
1998 /**
1999 * Return true if subpage links should be expanded on this page.
2000 * @return Boolean
2001 */
2002 function areSubpagesAllowed() {
2003 # Some namespaces don't allow subpages
2004 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2005 }
2006
2007 /**
2008 * Handle link to subpage if necessary
2009 *
2010 * @param $target String: the source of the link
2011 * @param &$text String: the link text, modified as necessary
2012 * @return string the full name of the link
2013 * @private
2014 */
2015 function maybeDoSubpageLink( $target, &$text ) {
2016 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2017 }
2018
2019 /**#@+
2020 * Used by doBlockLevels()
2021 * @private
2022 */
2023 function closeParagraph() {
2024 $result = '';
2025 if ( $this->mLastSection != '' ) {
2026 $result = '</' . $this->mLastSection . ">\n";
2027 }
2028 $this->mInPre = false;
2029 $this->mLastSection = '';
2030 return $result;
2031 }
2032
2033 /**
2034 * getCommon() returns the length of the longest common substring
2035 * of both arguments, starting at the beginning of both.
2036 * @private
2037 */
2038 function getCommon( $st1, $st2 ) {
2039 $fl = strlen( $st1 );
2040 $shorter = strlen( $st2 );
2041 if ( $fl < $shorter ) {
2042 $shorter = $fl;
2043 }
2044
2045 for ( $i = 0; $i < $shorter; ++$i ) {
2046 if ( $st1{$i} != $st2{$i} ) {
2047 break;
2048 }
2049 }
2050 return $i;
2051 }
2052
2053 /**
2054 * These next three functions open, continue, and close the list
2055 * element appropriate to the prefix character passed into them.
2056 * @private
2057 */
2058 function openList( $char ) {
2059 $result = $this->closeParagraph();
2060
2061 if ( '*' === $char ) {
2062 $result .= '<ul><li>';
2063 } elseif ( '#' === $char ) {
2064 $result .= '<ol><li>';
2065 } elseif ( ':' === $char ) {
2066 $result .= '<dl><dd>';
2067 } elseif ( ';' === $char ) {
2068 $result .= '<dl><dt>';
2069 $this->mDTopen = true;
2070 } else {
2071 $result = '<!-- ERR 1 -->';
2072 }
2073
2074 return $result;
2075 }
2076
2077 /**
2078 * TODO: document
2079 * @param $char String
2080 * @private
2081 */
2082 function nextItem( $char ) {
2083 if ( '*' === $char || '#' === $char ) {
2084 return '</li><li>';
2085 } elseif ( ':' === $char || ';' === $char ) {
2086 $close = '</dd>';
2087 if ( $this->mDTopen ) {
2088 $close = '</dt>';
2089 }
2090 if ( ';' === $char ) {
2091 $this->mDTopen = true;
2092 return $close . '<dt>';
2093 } else {
2094 $this->mDTopen = false;
2095 return $close . '<dd>';
2096 }
2097 }
2098 return '<!-- ERR 2 -->';
2099 }
2100
2101 /**
2102 * TODO: document
2103 * @param $char String
2104 * @private
2105 */
2106 function closeList( $char ) {
2107 if ( '*' === $char ) {
2108 $text = '</li></ul>';
2109 } elseif ( '#' === $char ) {
2110 $text = '</li></ol>';
2111 } elseif ( ':' === $char ) {
2112 if ( $this->mDTopen ) {
2113 $this->mDTopen = false;
2114 $text = '</dt></dl>';
2115 } else {
2116 $text = '</dd></dl>';
2117 }
2118 } else {
2119 return '<!-- ERR 3 -->';
2120 }
2121 return $text."\n";
2122 }
2123 /**#@-*/
2124
2125 /**
2126 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2127 *
2128 * @param $text String
2129 * @param $linestart Boolean: whether or not this is at the start of a line.
2130 * @private
2131 * @return string the lists rendered as HTML
2132 */
2133 function doBlockLevels( $text, $linestart ) {
2134 wfProfileIn( __METHOD__ );
2135
2136 # Parsing through the text line by line. The main thing
2137 # happening here is handling of block-level elements p, pre,
2138 # and making lists from lines starting with * # : etc.
2139 #
2140 $textLines = StringUtils::explode( "\n", $text );
2141
2142 $lastPrefix = $output = '';
2143 $this->mDTopen = $inBlockElem = false;
2144 $prefixLength = 0;
2145 $paragraphStack = false;
2146
2147 foreach ( $textLines as $oLine ) {
2148 # Fix up $linestart
2149 if ( !$linestart ) {
2150 $output .= $oLine;
2151 $linestart = true;
2152 continue;
2153 }
2154 # * = ul
2155 # # = ol
2156 # ; = dt
2157 # : = dd
2158
2159 $lastPrefixLength = strlen( $lastPrefix );
2160 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2161 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2162 # If not in a <pre> element, scan for and figure out what prefixes are there.
2163 if ( !$this->mInPre ) {
2164 # Multiple prefixes may abut each other for nested lists.
2165 $prefixLength = strspn( $oLine, '*#:;' );
2166 $prefix = substr( $oLine, 0, $prefixLength );
2167
2168 # eh?
2169 # ; and : are both from definition-lists, so they're equivalent
2170 # for the purposes of determining whether or not we need to open/close
2171 # elements.
2172 $prefix2 = str_replace( ';', ':', $prefix );
2173 $t = substr( $oLine, $prefixLength );
2174 $this->mInPre = (bool)$preOpenMatch;
2175 } else {
2176 # Don't interpret any other prefixes in preformatted text
2177 $prefixLength = 0;
2178 $prefix = $prefix2 = '';
2179 $t = $oLine;
2180 }
2181
2182 # List generation
2183 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2184 # Same as the last item, so no need to deal with nesting or opening stuff
2185 $output .= $this->nextItem( substr( $prefix, -1 ) );
2186 $paragraphStack = false;
2187
2188 if ( substr( $prefix, -1 ) === ';') {
2189 # The one nasty exception: definition lists work like this:
2190 # ; title : definition text
2191 # So we check for : in the remainder text to split up the
2192 # title and definition, without b0rking links.
2193 $term = $t2 = '';
2194 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2195 $t = $t2;
2196 $output .= $term . $this->nextItem( ':' );
2197 }
2198 }
2199 } elseif ( $prefixLength || $lastPrefixLength ) {
2200 # We need to open or close prefixes, or both.
2201
2202 # Either open or close a level...
2203 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2204 $paragraphStack = false;
2205
2206 # Close all the prefixes which aren't shared.
2207 while ( $commonPrefixLength < $lastPrefixLength ) {
2208 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2209 --$lastPrefixLength;
2210 }
2211
2212 # Continue the current prefix if appropriate.
2213 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2214 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2215 }
2216
2217 # Open prefixes where appropriate.
2218 while ( $prefixLength > $commonPrefixLength ) {
2219 $char = substr( $prefix, $commonPrefixLength, 1 );
2220 $output .= $this->openList( $char );
2221
2222 if ( ';' === $char ) {
2223 # FIXME: This is dupe of code above
2224 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2225 $t = $t2;
2226 $output .= $term . $this->nextItem( ':' );
2227 }
2228 }
2229 ++$commonPrefixLength;
2230 }
2231 $lastPrefix = $prefix2;
2232 }
2233
2234 # If we have no prefixes, go to paragraph mode.
2235 if ( 0 == $prefixLength ) {
2236 wfProfileIn( __METHOD__."-paragraph" );
2237 # No prefix (not in list)--go to paragraph mode
2238 # XXX: use a stack for nestable elements like span, table and div
2239 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2240 $closematch = preg_match(
2241 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2242 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2243 if ( $openmatch or $closematch ) {
2244 $paragraphStack = false;
2245 # TODO bug 5718: paragraph closed
2246 $output .= $this->closeParagraph();
2247 if ( $preOpenMatch and !$preCloseMatch ) {
2248 $this->mInPre = true;
2249 }
2250 $inBlockElem = !$closematch;
2251 } elseif ( !$inBlockElem && !$this->mInPre ) {
2252 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) ) {
2253 # pre
2254 if ( $this->mLastSection !== 'pre' ) {
2255 $paragraphStack = false;
2256 $output .= $this->closeParagraph().'<pre>';
2257 $this->mLastSection = 'pre';
2258 }
2259 $t = substr( $t, 1 );
2260 } else {
2261 # paragraph
2262 if ( trim( $t ) === '' ) {
2263 if ( $paragraphStack ) {
2264 $output .= $paragraphStack.'<br />';
2265 $paragraphStack = false;
2266 $this->mLastSection = 'p';
2267 } else {
2268 if ( $this->mLastSection !== 'p' ) {
2269 $output .= $this->closeParagraph();
2270 $this->mLastSection = '';
2271 $paragraphStack = '<p>';
2272 } else {
2273 $paragraphStack = '</p><p>';
2274 }
2275 }
2276 } else {
2277 if ( $paragraphStack ) {
2278 $output .= $paragraphStack;
2279 $paragraphStack = false;
2280 $this->mLastSection = 'p';
2281 } elseif ( $this->mLastSection !== 'p' ) {
2282 $output .= $this->closeParagraph().'<p>';
2283 $this->mLastSection = 'p';
2284 }
2285 }
2286 }
2287 }
2288 wfProfileOut( __METHOD__."-paragraph" );
2289 }
2290 # somewhere above we forget to get out of pre block (bug 785)
2291 if ( $preCloseMatch && $this->mInPre ) {
2292 $this->mInPre = false;
2293 }
2294 if ( $paragraphStack === false ) {
2295 $output .= $t."\n";
2296 }
2297 }
2298 while ( $prefixLength ) {
2299 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2300 --$prefixLength;
2301 }
2302 if ( $this->mLastSection != '' ) {
2303 $output .= '</' . $this->mLastSection . '>';
2304 $this->mLastSection = '';
2305 }
2306
2307 wfProfileOut( __METHOD__ );
2308 return $output;
2309 }
2310
2311 /**
2312 * Split up a string on ':', ignoring any occurences inside tags
2313 * to prevent illegal overlapping.
2314 *
2315 * @param $str String: the string to split
2316 * @param &$before String: set to everything before the ':'
2317 * @param &$after String: set to everything after the ':'
2318 * return String: the position of the ':', or false if none found
2319 */
2320 function findColonNoLinks( $str, &$before, &$after ) {
2321 wfProfileIn( __METHOD__ );
2322
2323 $pos = strpos( $str, ':' );
2324 if ( $pos === false ) {
2325 # Nothing to find!
2326 wfProfileOut( __METHOD__ );
2327 return false;
2328 }
2329
2330 $lt = strpos( $str, '<' );
2331 if ( $lt === false || $lt > $pos ) {
2332 # Easy; no tag nesting to worry about
2333 $before = substr( $str, 0, $pos );
2334 $after = substr( $str, $pos+1 );
2335 wfProfileOut( __METHOD__ );
2336 return $pos;
2337 }
2338
2339 # Ugly state machine to walk through avoiding tags.
2340 $state = self::COLON_STATE_TEXT;
2341 $stack = 0;
2342 $len = strlen( $str );
2343 for( $i = 0; $i < $len; $i++ ) {
2344 $c = $str{$i};
2345
2346 switch( $state ) {
2347 # (Using the number is a performance hack for common cases)
2348 case 0: # self::COLON_STATE_TEXT:
2349 switch( $c ) {
2350 case "<":
2351 # Could be either a <start> tag or an </end> tag
2352 $state = self::COLON_STATE_TAGSTART;
2353 break;
2354 case ":":
2355 if ( $stack == 0 ) {
2356 # We found it!
2357 $before = substr( $str, 0, $i );
2358 $after = substr( $str, $i + 1 );
2359 wfProfileOut( __METHOD__ );
2360 return $i;
2361 }
2362 # Embedded in a tag; don't break it.
2363 break;
2364 default:
2365 # Skip ahead looking for something interesting
2366 $colon = strpos( $str, ':', $i );
2367 if ( $colon === false ) {
2368 # Nothing else interesting
2369 wfProfileOut( __METHOD__ );
2370 return false;
2371 }
2372 $lt = strpos( $str, '<', $i );
2373 if ( $stack === 0 ) {
2374 if ( $lt === false || $colon < $lt ) {
2375 # We found it!
2376 $before = substr( $str, 0, $colon );
2377 $after = substr( $str, $colon + 1 );
2378 wfProfileOut( __METHOD__ );
2379 return $i;
2380 }
2381 }
2382 if ( $lt === false ) {
2383 # Nothing else interesting to find; abort!
2384 # We're nested, but there's no close tags left. Abort!
2385 break 2;
2386 }
2387 # Skip ahead to next tag start
2388 $i = $lt;
2389 $state = self::COLON_STATE_TAGSTART;
2390 }
2391 break;
2392 case 1: # self::COLON_STATE_TAG:
2393 # In a <tag>
2394 switch( $c ) {
2395 case ">":
2396 $stack++;
2397 $state = self::COLON_STATE_TEXT;
2398 break;
2399 case "/":
2400 # Slash may be followed by >?
2401 $state = self::COLON_STATE_TAGSLASH;
2402 break;
2403 default:
2404 # ignore
2405 }
2406 break;
2407 case 2: # self::COLON_STATE_TAGSTART:
2408 switch( $c ) {
2409 case "/":
2410 $state = self::COLON_STATE_CLOSETAG;
2411 break;
2412 case "!":
2413 $state = self::COLON_STATE_COMMENT;
2414 break;
2415 case ">":
2416 # Illegal early close? This shouldn't happen D:
2417 $state = self::COLON_STATE_TEXT;
2418 break;
2419 default:
2420 $state = self::COLON_STATE_TAG;
2421 }
2422 break;
2423 case 3: # self::COLON_STATE_CLOSETAG:
2424 # In a </tag>
2425 if ( $c === ">" ) {
2426 $stack--;
2427 if ( $stack < 0 ) {
2428 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
2429 wfProfileOut( __METHOD__ );
2430 return false;
2431 }
2432 $state = self::COLON_STATE_TEXT;
2433 }
2434 break;
2435 case self::COLON_STATE_TAGSLASH:
2436 if ( $c === ">" ) {
2437 # Yes, a self-closed tag <blah/>
2438 $state = self::COLON_STATE_TEXT;
2439 } else {
2440 # Probably we're jumping the gun, and this is an attribute
2441 $state = self::COLON_STATE_TAG;
2442 }
2443 break;
2444 case 5: # self::COLON_STATE_COMMENT:
2445 if ( $c === "-" ) {
2446 $state = self::COLON_STATE_COMMENTDASH;
2447 }
2448 break;
2449 case self::COLON_STATE_COMMENTDASH:
2450 if ( $c === "-" ) {
2451 $state = self::COLON_STATE_COMMENTDASHDASH;
2452 } else {
2453 $state = self::COLON_STATE_COMMENT;
2454 }
2455 break;
2456 case self::COLON_STATE_COMMENTDASHDASH:
2457 if ( $c === ">" ) {
2458 $state = self::COLON_STATE_TEXT;
2459 } else {
2460 $state = self::COLON_STATE_COMMENT;
2461 }
2462 break;
2463 default:
2464 throw new MWException( "State machine error in " . __METHOD__ );
2465 }
2466 }
2467 if ( $stack > 0 ) {
2468 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2469 return false;
2470 }
2471 wfProfileOut( __METHOD__ );
2472 return false;
2473 }
2474
2475 /**
2476 * Return value of a magic variable (like PAGENAME)
2477 *
2478 * @private
2479 */
2480 function getVariableValue( $index, $frame=false ) {
2481 global $wgContLang, $wgSitename, $wgServer;
2482 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2483
2484 /**
2485 * Some of these require message or data lookups and can be
2486 * expensive to check many times.
2487 */
2488 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2489 if ( isset( $this->mVarCache[$index] ) ) {
2490 return $this->mVarCache[$index];
2491 }
2492 }
2493
2494 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2495 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2496
2497 # Use the time zone
2498 global $wgLocaltimezone;
2499 if ( isset( $wgLocaltimezone ) ) {
2500 $oldtz = date_default_timezone_get();
2501 date_default_timezone_set( $wgLocaltimezone );
2502 }
2503
2504 $localTimestamp = date( 'YmdHis', $ts );
2505 $localMonth = date( 'm', $ts );
2506 $localMonth1 = date( 'n', $ts );
2507 $localMonthName = date( 'n', $ts );
2508 $localDay = date( 'j', $ts );
2509 $localDay2 = date( 'd', $ts );
2510 $localDayOfWeek = date( 'w', $ts );
2511 $localWeek = date( 'W', $ts );
2512 $localYear = date( 'Y', $ts );
2513 $localHour = date( 'H', $ts );
2514 if ( isset( $wgLocaltimezone ) ) {
2515 date_default_timezone_set( $oldtz );
2516 }
2517
2518 switch ( $index ) {
2519 case 'currentmonth':
2520 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2521 break;
2522 case 'currentmonth1':
2523 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2524 break;
2525 case 'currentmonthname':
2526 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2527 break;
2528 case 'currentmonthnamegen':
2529 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2530 break;
2531 case 'currentmonthabbrev':
2532 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2533 break;
2534 case 'currentday':
2535 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2536 break;
2537 case 'currentday2':
2538 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2539 break;
2540 case 'localmonth':
2541 $value = $wgContLang->formatNum( $localMonth );
2542 break;
2543 case 'localmonth1':
2544 $value = $wgContLang->formatNum( $localMonth1 );
2545 break;
2546 case 'localmonthname':
2547 $value = $wgContLang->getMonthName( $localMonthName );
2548 break;
2549 case 'localmonthnamegen':
2550 $value = $wgContLang->getMonthNameGen( $localMonthName );
2551 break;
2552 case 'localmonthabbrev':
2553 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2554 break;
2555 case 'localday':
2556 $value = $wgContLang->formatNum( $localDay );
2557 break;
2558 case 'localday2':
2559 $value = $wgContLang->formatNum( $localDay2 );
2560 break;
2561 case 'pagename':
2562 $value = wfEscapeWikiText( $this->mTitle->getText() );
2563 break;
2564 case 'pagenamee':
2565 $value = $this->mTitle->getPartialURL();
2566 break;
2567 case 'fullpagename':
2568 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2569 break;
2570 case 'fullpagenamee':
2571 $value = $this->mTitle->getPrefixedURL();
2572 break;
2573 case 'subpagename':
2574 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2575 break;
2576 case 'subpagenamee':
2577 $value = $this->mTitle->getSubpageUrlForm();
2578 break;
2579 case 'basepagename':
2580 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2581 break;
2582 case 'basepagenamee':
2583 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2584 break;
2585 case 'talkpagename':
2586 if ( $this->mTitle->canTalk() ) {
2587 $talkPage = $this->mTitle->getTalkPage();
2588 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2589 } else {
2590 $value = '';
2591 }
2592 break;
2593 case 'talkpagenamee':
2594 if ( $this->mTitle->canTalk() ) {
2595 $talkPage = $this->mTitle->getTalkPage();
2596 $value = $talkPage->getPrefixedUrl();
2597 } else {
2598 $value = '';
2599 }
2600 break;
2601 case 'subjectpagename':
2602 $subjPage = $this->mTitle->getSubjectPage();
2603 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2604 break;
2605 case 'subjectpagenamee':
2606 $subjPage = $this->mTitle->getSubjectPage();
2607 $value = $subjPage->getPrefixedUrl();
2608 break;
2609 case 'revisionid':
2610 # Let the edit saving system know we should parse the page
2611 # *after* a revision ID has been assigned.
2612 $this->mOutput->setFlag( 'vary-revision' );
2613 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2614 $value = $this->mRevisionId;
2615 break;
2616 case 'revisionday':
2617 # Let the edit saving system know we should parse the page
2618 # *after* a revision ID has been assigned. This is for null edits.
2619 $this->mOutput->setFlag( 'vary-revision' );
2620 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2621 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2622 break;
2623 case 'revisionday2':
2624 # Let the edit saving system know we should parse the page
2625 # *after* a revision ID has been assigned. This is for null edits.
2626 $this->mOutput->setFlag( 'vary-revision' );
2627 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2628 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2629 break;
2630 case 'revisionmonth':
2631 # Let the edit saving system know we should parse the page
2632 # *after* a revision ID has been assigned. This is for null edits.
2633 $this->mOutput->setFlag( 'vary-revision' );
2634 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2635 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2636 break;
2637 case 'revisionmonth1':
2638 # Let the edit saving system know we should parse the page
2639 # *after* a revision ID has been assigned. This is for null edits.
2640 $this->mOutput->setFlag( 'vary-revision' );
2641 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2642 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2643 break;
2644 case 'revisionyear':
2645 # Let the edit saving system know we should parse the page
2646 # *after* a revision ID has been assigned. This is for null edits.
2647 $this->mOutput->setFlag( 'vary-revision' );
2648 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2649 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2650 break;
2651 case 'revisiontimestamp':
2652 # Let the edit saving system know we should parse the page
2653 # *after* a revision ID has been assigned. This is for null edits.
2654 $this->mOutput->setFlag( 'vary-revision' );
2655 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2656 $value = $this->getRevisionTimestamp();
2657 break;
2658 case 'revisionuser':
2659 # Let the edit saving system know we should parse the page
2660 # *after* a revision ID has been assigned. This is for null edits.
2661 $this->mOutput->setFlag( 'vary-revision' );
2662 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2663 $value = $this->getRevisionUser();
2664 break;
2665 case 'namespace':
2666 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2667 break;
2668 case 'namespacee':
2669 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2670 break;
2671 case 'talkspace':
2672 $value = $this->mTitle->canTalk() ? str_replace( '_',' ',$this->mTitle->getTalkNsText() ) : '';
2673 break;
2674 case 'talkspacee':
2675 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2676 break;
2677 case 'subjectspace':
2678 $value = $this->mTitle->getSubjectNsText();
2679 break;
2680 case 'subjectspacee':
2681 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2682 break;
2683 case 'currentdayname':
2684 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2685 break;
2686 case 'currentyear':
2687 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2688 break;
2689 case 'currenttime':
2690 $value = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2691 break;
2692 case 'currenthour':
2693 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2694 break;
2695 case 'currentweek':
2696 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2697 # int to remove the padding
2698 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2699 break;
2700 case 'currentdow':
2701 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2702 break;
2703 case 'localdayname':
2704 $value = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2705 break;
2706 case 'localyear':
2707 $value = $wgContLang->formatNum( $localYear, true );
2708 break;
2709 case 'localtime':
2710 $value = $wgContLang->time( $localTimestamp, false, false );
2711 break;
2712 case 'localhour':
2713 $value = $wgContLang->formatNum( $localHour, true );
2714 break;
2715 case 'localweek':
2716 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2717 # int to remove the padding
2718 $value = $wgContLang->formatNum( (int)$localWeek );
2719 break;
2720 case 'localdow':
2721 $value = $wgContLang->formatNum( $localDayOfWeek );
2722 break;
2723 case 'numberofarticles':
2724 $value = $wgContLang->formatNum( SiteStats::articles() );
2725 break;
2726 case 'numberoffiles':
2727 $value = $wgContLang->formatNum( SiteStats::images() );
2728 break;
2729 case 'numberofusers':
2730 $value = $wgContLang->formatNum( SiteStats::users() );
2731 break;
2732 case 'numberofactiveusers':
2733 $value = $wgContLang->formatNum( SiteStats::activeUsers() );
2734 break;
2735 case 'numberofpages':
2736 $value = $wgContLang->formatNum( SiteStats::pages() );
2737 break;
2738 case 'numberofadmins':
2739 $value = $wgContLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2740 break;
2741 case 'numberofedits':
2742 $value = $wgContLang->formatNum( SiteStats::edits() );
2743 break;
2744 case 'numberofviews':
2745 $value = $wgContLang->formatNum( SiteStats::views() );
2746 break;
2747 case 'currenttimestamp':
2748 $value = wfTimestamp( TS_MW, $ts );
2749 break;
2750 case 'localtimestamp':
2751 $value = $localTimestamp;
2752 break;
2753 case 'currentversion':
2754 $value = SpecialVersion::getVersion();
2755 break;
2756 case 'articlepath':
2757 return $wgArticlePath;
2758 case 'sitename':
2759 return $wgSitename;
2760 case 'server':
2761 return $wgServer;
2762 case 'servername':
2763 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2764 $serverName = parse_url( $wgServer, PHP_URL_HOST );
2765 wfRestoreWarnings();
2766 return $serverName ? $serverName : $wgServer;
2767 case 'scriptpath':
2768 return $wgScriptPath;
2769 case 'stylepath':
2770 return $wgStylePath;
2771 case 'directionmark':
2772 return $wgContLang->getDirMark();
2773 case 'contentlanguage':
2774 global $wgLanguageCode;
2775 return $wgLanguageCode;
2776 default:
2777 $ret = null;
2778 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) ) {
2779 return $ret;
2780 } else {
2781 return null;
2782 }
2783 }
2784
2785 if ( $index )
2786 $this->mVarCache[$index] = $value;
2787
2788 return $value;
2789 }
2790
2791 /**
2792 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2793 *
2794 * @private
2795 */
2796 function initialiseVariables() {
2797 wfProfileIn( __METHOD__ );
2798 $variableIDs = MagicWord::getVariableIDs();
2799 $substIDs = MagicWord::getSubstIDs();
2800
2801 $this->mVariables = new MagicWordArray( $variableIDs );
2802 $this->mSubstWords = new MagicWordArray( $substIDs );
2803 wfProfileOut( __METHOD__ );
2804 }
2805
2806 /**
2807 * Preprocess some wikitext and return the document tree.
2808 * This is the ghost of replace_variables().
2809 *
2810 * @param $text String: The text to parse
2811 * @param $flags Integer: bitwise combination of:
2812 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2813 * included. Default is to assume a direct page view.
2814 *
2815 * The generated DOM tree must depend only on the input text and the flags.
2816 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2817 *
2818 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2819 * change in the DOM tree for a given text, must be passed through the section identifier
2820 * in the section edit link and thus back to extractSections().
2821 *
2822 * The output of this function is currently only cached in process memory, but a persistent
2823 * cache may be implemented at a later date which takes further advantage of these strict
2824 * dependency requirements.
2825 *
2826 * @private
2827 */
2828 function preprocessToDom( $text, $flags = 0 ) {
2829 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2830 return $dom;
2831 }
2832
2833 /**
2834 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2835 */
2836 public static function splitWhitespace( $s ) {
2837 $ltrimmed = ltrim( $s );
2838 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2839 $trimmed = rtrim( $ltrimmed );
2840 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2841 if ( $diff > 0 ) {
2842 $w2 = substr( $ltrimmed, -$diff );
2843 } else {
2844 $w2 = '';
2845 }
2846 return array( $w1, $trimmed, $w2 );
2847 }
2848
2849 /**
2850 * Replace magic variables, templates, and template arguments
2851 * with the appropriate text. Templates are substituted recursively,
2852 * taking care to avoid infinite loops.
2853 *
2854 * Note that the substitution depends on value of $mOutputType:
2855 * self::OT_WIKI: only {{subst:}} templates
2856 * self::OT_PREPROCESS: templates but not extension tags
2857 * self::OT_HTML: all templates and extension tags
2858 *
2859 * @param $text String: the text to transform
2860 * @param $frame PPFrame Object describing the arguments passed to the template.
2861 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2862 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2863 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2864 * @private
2865 */
2866 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2867 # Is there any text? Also, Prevent too big inclusions!
2868 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2869 return $text;
2870 }
2871 wfProfileIn( __METHOD__ );
2872
2873 if ( $frame === false ) {
2874 $frame = $this->getPreprocessor()->newFrame();
2875 } elseif ( !( $frame instanceof PPFrame ) ) {
2876 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2877 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2878 }
2879
2880 $dom = $this->preprocessToDom( $text );
2881 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2882 $text = $frame->expand( $dom, $flags );
2883
2884 wfProfileOut( __METHOD__ );
2885 return $text;
2886 }
2887
2888 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2889 static function createAssocArgs( $args ) {
2890 $assocArgs = array();
2891 $index = 1;
2892 foreach ( $args as $arg ) {
2893 $eqpos = strpos( $arg, '=' );
2894 if ( $eqpos === false ) {
2895 $assocArgs[$index++] = $arg;
2896 } else {
2897 $name = trim( substr( $arg, 0, $eqpos ) );
2898 $value = trim( substr( $arg, $eqpos+1 ) );
2899 if ( $value === false ) {
2900 $value = '';
2901 }
2902 if ( $name !== false ) {
2903 $assocArgs[$name] = $value;
2904 }
2905 }
2906 }
2907
2908 return $assocArgs;
2909 }
2910
2911 /**
2912 * Warn the user when a parser limitation is reached
2913 * Will warn at most once the user per limitation type
2914 *
2915 * @param $limitationType String: should be one of:
2916 * 'expensive-parserfunction' (corresponding messages:
2917 * 'expensive-parserfunction-warning',
2918 * 'expensive-parserfunction-category')
2919 * 'post-expand-template-argument' (corresponding messages:
2920 * 'post-expand-template-argument-warning',
2921 * 'post-expand-template-argument-category')
2922 * 'post-expand-template-inclusion' (corresponding messages:
2923 * 'post-expand-template-inclusion-warning',
2924 * 'post-expand-template-inclusion-category')
2925 * @param $current Current value
2926 * @param $max Maximum allowed, when an explicit limit has been
2927 * exceeded, provide the values (optional)
2928 */
2929 function limitationWarn( $limitationType, $current=null, $max=null) {
2930 # does no harm if $current and $max are present but are unnecessary for the message
2931 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2932 $this->mOutput->addWarning( $warning );
2933 $this->addTrackingCategory( "$limitationType-category" );
2934 }
2935
2936 /**
2937 * Return the text of a template, after recursively
2938 * replacing any variables or templates within the template.
2939 *
2940 * @param $piece Array: the parts of the template
2941 * $piece['title']: the title, i.e. the part before the |
2942 * $piece['parts']: the parameter array
2943 * $piece['lineStart']: whether the brace was at the start of a line
2944 * @param $frame PPFrame The current frame, contains template arguments
2945 * @return String: the text of the template
2946 * @private
2947 */
2948 function braceSubstitution( $piece, $frame ) {
2949 global $wgContLang, $wgNonincludableNamespaces;
2950 wfProfileIn( __METHOD__ );
2951 wfProfileIn( __METHOD__.'-setup' );
2952
2953 # Flags
2954 $found = false; # $text has been filled
2955 $nowiki = false; # wiki markup in $text should be escaped
2956 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2957 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2958 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2959 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2960
2961 # Title object, where $text came from
2962 $title = null;
2963
2964 # $part1 is the bit before the first |, and must contain only title characters.
2965 # Various prefixes will be stripped from it later.
2966 $titleWithSpaces = $frame->expand( $piece['title'] );
2967 $part1 = trim( $titleWithSpaces );
2968 $titleText = false;
2969
2970 # Original title text preserved for various purposes
2971 $originalTitle = $part1;
2972
2973 # $args is a list of argument nodes, starting from index 0, not including $part1
2974 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
2975 wfProfileOut( __METHOD__.'-setup' );
2976
2977 # SUBST
2978 wfProfileIn( __METHOD__.'-modifiers' );
2979 if ( !$found ) {
2980
2981 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
2982
2983 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2984 # Decide whether to expand template or keep wikitext as-is.
2985 if ( $this->ot['wiki'] ) {
2986 if ( $substMatch === false ) {
2987 $literal = true; # literal when in PST with no prefix
2988 } else {
2989 $literal = false; # expand when in PST with subst: or safesubst:
2990 }
2991 } else {
2992 if ( $substMatch == 'subst' ) {
2993 $literal = true; # literal when not in PST with plain subst:
2994 } else {
2995 $literal = false; # expand when not in PST with safesubst: or no prefix
2996 }
2997 }
2998 if ( $literal ) {
2999 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3000 $isLocalObj = true;
3001 $found = true;
3002 }
3003 }
3004
3005 # Variables
3006 if ( !$found && $args->getLength() == 0 ) {
3007 $id = $this->mVariables->matchStartToEnd( $part1 );
3008 if ( $id !== false ) {
3009 $text = $this->getVariableValue( $id, $frame );
3010 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3011 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3012 }
3013 $found = true;
3014 }
3015 }
3016
3017 # MSG, MSGNW and RAW
3018 if ( !$found ) {
3019 # Check for MSGNW:
3020 $mwMsgnw = MagicWord::get( 'msgnw' );
3021 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3022 $nowiki = true;
3023 } else {
3024 # Remove obsolete MSG:
3025 $mwMsg = MagicWord::get( 'msg' );
3026 $mwMsg->matchStartAndRemove( $part1 );
3027 }
3028
3029 # Check for RAW:
3030 $mwRaw = MagicWord::get( 'raw' );
3031 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3032 $forceRawInterwiki = true;
3033 }
3034 }
3035 wfProfileOut( __METHOD__.'-modifiers' );
3036
3037 # Parser functions
3038 if ( !$found ) {
3039 wfProfileIn( __METHOD__ . '-pfunc' );
3040
3041 $colonPos = strpos( $part1, ':' );
3042 if ( $colonPos !== false ) {
3043 # Case sensitive functions
3044 $function = substr( $part1, 0, $colonPos );
3045 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3046 $function = $this->mFunctionSynonyms[1][$function];
3047 } else {
3048 # Case insensitive functions
3049 $function = $wgContLang->lc( $function );
3050 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3051 $function = $this->mFunctionSynonyms[0][$function];
3052 } else {
3053 $function = false;
3054 }
3055 }
3056 if ( $function ) {
3057 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3058 $initialArgs = array( &$this );
3059 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3060 if ( $flags & SFH_OBJECT_ARGS ) {
3061 # Add a frame parameter, and pass the arguments as an array
3062 $allArgs = $initialArgs;
3063 $allArgs[] = $frame;
3064 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3065 $funcArgs[] = $args->item( $i );
3066 }
3067 $allArgs[] = $funcArgs;
3068 } else {
3069 # Convert arguments to plain text
3070 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3071 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3072 }
3073 $allArgs = array_merge( $initialArgs, $funcArgs );
3074 }
3075
3076 # Workaround for PHP bug 35229 and similar
3077 if ( !is_callable( $callback ) ) {
3078 wfProfileOut( __METHOD__ . '-pfunc' );
3079 wfProfileOut( __METHOD__ );
3080 throw new MWException( "Tag hook for $function is not callable\n" );
3081 }
3082 $result = call_user_func_array( $callback, $allArgs );
3083 $found = true;
3084 $noparse = true;
3085 $preprocessFlags = 0;
3086
3087 if ( is_array( $result ) ) {
3088 if ( isset( $result[0] ) ) {
3089 $text = $result[0];
3090 unset( $result[0] );
3091 }
3092
3093 # Extract flags into the local scope
3094 # This allows callers to set flags such as nowiki, found, etc.
3095 extract( $result );
3096 } else {
3097 $text = $result;
3098 }
3099 if ( !$noparse ) {
3100 $text = $this->preprocessToDom( $text, $preprocessFlags );
3101 $isChildObj = true;
3102 }
3103 }
3104 }
3105 wfProfileOut( __METHOD__ . '-pfunc' );
3106 }
3107
3108 # Finish mangling title and then check for loops.
3109 # Set $title to a Title object and $titleText to the PDBK
3110 if ( !$found ) {
3111 $ns = NS_TEMPLATE;
3112 # Split the title into page and subpage
3113 $subpage = '';
3114 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3115 if ( $subpage !== '' ) {
3116 $ns = $this->mTitle->getNamespace();
3117 }
3118 $title = Title::newFromText( $part1, $ns );
3119 if ( $title ) {
3120 $titleText = $title->getPrefixedText();
3121 # Check for language variants if the template is not found
3122 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3123 $wgContLang->findVariantLink( $part1, $title, true );
3124 }
3125 # Do recursion depth check
3126 $limit = $this->mOptions->getMaxTemplateDepth();
3127 if ( $frame->depth >= $limit ) {
3128 $found = true;
3129 $text = '<span class="error">'
3130 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3131 . '</span>';
3132 }
3133 }
3134 }
3135
3136 # Load from database
3137 if ( !$found && $title ) {
3138 wfProfileIn( __METHOD__ . '-loadtpl' );
3139 if ( !$title->isExternal() ) {
3140 if ( $title->getNamespace() == NS_SPECIAL
3141 && $this->mOptions->getAllowSpecialInclusion()
3142 && $this->ot['html'] )
3143 {
3144 $text = SpecialPage::capturePath( $title );
3145 if ( is_string( $text ) ) {
3146 $found = true;
3147 $isHTML = true;
3148 $this->disableCache();
3149 }
3150 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3151 $found = false; # access denied
3152 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
3153 } else {
3154 list( $text, $title ) = $this->getTemplateDom( $title );
3155 if ( $text !== false ) {
3156 $found = true;
3157 $isChildObj = true;
3158 }
3159 }
3160
3161 # If the title is valid but undisplayable, make a link to it
3162 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3163 $text = "[[:$titleText]]";
3164 $found = true;
3165 }
3166 } elseif ( $title->isTrans() ) {
3167 # Interwiki transclusion
3168 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3169 $text = $this->interwikiTransclude( $title, 'render' );
3170 $isHTML = true;
3171 } else {
3172 $text = $this->interwikiTransclude( $title, 'raw' );
3173 # Preprocess it like a template
3174 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3175 $isChildObj = true;
3176 }
3177 $found = true;
3178 }
3179
3180 # Do infinite loop check
3181 # This has to be done after redirect resolution to avoid infinite loops via redirects
3182 if ( !$frame->loopCheck( $title ) ) {
3183 $found = true;
3184 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3185 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
3186 }
3187 wfProfileOut( __METHOD__ . '-loadtpl' );
3188 }
3189
3190 # If we haven't found text to substitute by now, we're done
3191 # Recover the source wikitext and return it
3192 if ( !$found ) {
3193 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3194 wfProfileOut( __METHOD__ );
3195 return array( 'object' => $text );
3196 }
3197
3198 # Expand DOM-style return values in a child frame
3199 if ( $isChildObj ) {
3200 # Clean up argument array
3201 $newFrame = $frame->newChild( $args, $title );
3202
3203 if ( $nowiki ) {
3204 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3205 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3206 # Expansion is eligible for the empty-frame cache
3207 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3208 $text = $this->mTplExpandCache[$titleText];
3209 } else {
3210 $text = $newFrame->expand( $text );
3211 $this->mTplExpandCache[$titleText] = $text;
3212 }
3213 } else {
3214 # Uncached expansion
3215 $text = $newFrame->expand( $text );
3216 }
3217 }
3218 if ( $isLocalObj && $nowiki ) {
3219 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3220 $isLocalObj = false;
3221 }
3222
3223 # Replace raw HTML by a placeholder
3224 # Add a blank line preceding, to prevent it from mucking up
3225 # immediately preceding headings
3226 if ( $isHTML ) {
3227 $text = "\n\n" . $this->insertStripItem( $text );
3228 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3229 # Escape nowiki-style return values
3230 $text = wfEscapeWikiText( $text );
3231 } elseif ( is_string( $text )
3232 && !$piece['lineStart']
3233 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3234 {
3235 # Bug 529: if the template begins with a table or block-level
3236 # element, it should be treated as beginning a new line.
3237 # This behaviour is somewhat controversial.
3238 $text = "\n" . $text;
3239 }
3240
3241 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3242 # Error, oversize inclusion
3243 if ( $titleText !== false ) {
3244 # Make a working, properly escaped link if possible (bug 23588)
3245 $text = "[[:$titleText]]";
3246 } else {
3247 # This will probably not be a working link, but at least it may
3248 # provide some hint of where the problem is
3249 preg_replace( '/^:/', '', $originalTitle );
3250 $text = "[[:$originalTitle]]";
3251 }
3252 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3253 $this->limitationWarn( 'post-expand-template-inclusion' );
3254 }
3255
3256 if ( $isLocalObj ) {
3257 $ret = array( 'object' => $text );
3258 } else {
3259 $ret = array( 'text' => $text );
3260 }
3261
3262 wfProfileOut( __METHOD__ );
3263 return $ret;
3264 }
3265
3266 /**
3267 * Get the semi-parsed DOM representation of a template with a given title,
3268 * and its redirect destination title. Cached.
3269 */
3270 function getTemplateDom( $title ) {
3271 $cacheTitle = $title;
3272 $titleText = $title->getPrefixedDBkey();
3273
3274 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3275 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3276 $title = Title::makeTitle( $ns, $dbk );
3277 $titleText = $title->getPrefixedDBkey();
3278 }
3279 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3280 return array( $this->mTplDomCache[$titleText], $title );
3281 }
3282
3283 # Cache miss, go to the database
3284 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3285
3286 if ( $text === false ) {
3287 $this->mTplDomCache[$titleText] = false;
3288 return array( false, $title );
3289 }
3290
3291 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3292 $this->mTplDomCache[ $titleText ] = $dom;
3293
3294 if ( !$title->equals( $cacheTitle ) ) {
3295 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3296 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3297 }
3298
3299 return array( $dom, $title );
3300 }
3301
3302 /**
3303 * Fetch the unparsed text of a template and register a reference to it.
3304 */
3305 function fetchTemplateAndTitle( $title ) {
3306 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3307 $stuff = call_user_func( $templateCb, $title, $this );
3308 $text = $stuff['text'];
3309 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3310 if ( isset( $stuff['deps'] ) ) {
3311 foreach ( $stuff['deps'] as $dep ) {
3312 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3313 }
3314 }
3315 return array( $text, $finalTitle );
3316 }
3317
3318 function fetchTemplate( $title ) {
3319 $rv = $this->fetchTemplateAndTitle( $title );
3320 return $rv[0];
3321 }
3322
3323 /**
3324 * Static function to get a template
3325 * Can be overridden via ParserOptions::setTemplateCallback().
3326 */
3327 static function statelessFetchTemplate( $title, $parser=false ) {
3328 $text = $skip = false;
3329 $finalTitle = $title;
3330 $deps = array();
3331
3332 # Loop to fetch the article, with up to 1 redirect
3333 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3334 # Give extensions a chance to select the revision instead
3335 $id = false; # Assume current
3336 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3337
3338 if ( $skip ) {
3339 $text = false;
3340 $deps[] = array(
3341 'title' => $title,
3342 'page_id' => $title->getArticleID(),
3343 'rev_id' => null );
3344 break;
3345 }
3346 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3347 $rev_id = $rev ? $rev->getId() : 0;
3348 # If there is no current revision, there is no page
3349 if ( $id === false && !$rev ) {
3350 $linkCache = LinkCache::singleton();
3351 $linkCache->addBadLinkObj( $title );
3352 }
3353
3354 $deps[] = array(
3355 'title' => $title,
3356 'page_id' => $title->getArticleID(),
3357 'rev_id' => $rev_id );
3358
3359 if ( $rev ) {
3360 $text = $rev->getText();
3361 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3362 global $wgContLang;
3363 $message = $wgContLang->lcfirst( $title->getText() );
3364 $text = wfMsgForContentNoTrans( $message );
3365 if ( wfEmptyMsg( $message, $text ) ) {
3366 $text = false;
3367 break;
3368 }
3369 } else {
3370 break;
3371 }
3372 if ( $text === false ) {
3373 break;
3374 }
3375 # Redirect?
3376 $finalTitle = $title;
3377 $title = Title::newFromRedirect( $text );
3378 }
3379 return array(
3380 'text' => $text,
3381 'finalTitle' => $finalTitle,
3382 'deps' => $deps );
3383 }
3384
3385 /**
3386 * Transclude an interwiki link.
3387 */
3388 function interwikiTransclude( $title, $action ) {
3389 global $wgEnableScaryTranscluding;
3390
3391 if ( !$wgEnableScaryTranscluding ) {
3392 return wfMsgForContent('scarytranscludedisabled');
3393 }
3394
3395 $url = $title->getFullUrl( "action=$action" );
3396
3397 if ( strlen( $url ) > 255 ) {
3398 return wfMsgForContent( 'scarytranscludetoolong' );
3399 }
3400 return $this->fetchScaryTemplateMaybeFromCache( $url );
3401 }
3402
3403 function fetchScaryTemplateMaybeFromCache( $url ) {
3404 global $wgTranscludeCacheExpiry;
3405 $dbr = wfGetDB( DB_SLAVE );
3406 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3407 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3408 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3409 if ( $obj ) {
3410 return $obj->tc_contents;
3411 }
3412
3413 $text = Http::get( $url );
3414 if ( !$text ) {
3415 return wfMsgForContent( 'scarytranscludefailed', $url );
3416 }
3417
3418 $dbw = wfGetDB( DB_MASTER );
3419 $dbw->replace( 'transcache', array('tc_url'), array(
3420 'tc_url' => $url,
3421 'tc_time' => $dbw->timestamp( time() ),
3422 'tc_contents' => $text)
3423 );
3424 return $text;
3425 }
3426
3427
3428 /**
3429 * Triple brace replacement -- used for template arguments
3430 * @private
3431 */
3432 function argSubstitution( $piece, $frame ) {
3433 wfProfileIn( __METHOD__ );
3434
3435 $error = false;
3436 $parts = $piece['parts'];
3437 $nameWithSpaces = $frame->expand( $piece['title'] );
3438 $argName = trim( $nameWithSpaces );
3439 $object = false;
3440 $text = $frame->getArgument( $argName );
3441 if ( $text === false && $parts->getLength() > 0
3442 && (
3443 $this->ot['html']
3444 || $this->ot['pre']
3445 || ( $this->ot['wiki'] && $frame->isTemplate() )
3446 )
3447 ) {
3448 # No match in frame, use the supplied default
3449 $object = $parts->item( 0 )->getChildren();
3450 }
3451 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3452 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3453 $this->limitationWarn( 'post-expand-template-argument' );
3454 }
3455
3456 if ( $text === false && $object === false ) {
3457 # No match anywhere
3458 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3459 }
3460 if ( $error !== false ) {
3461 $text .= $error;
3462 }
3463 if ( $object !== false ) {
3464 $ret = array( 'object' => $object );
3465 } else {
3466 $ret = array( 'text' => $text );
3467 }
3468
3469 wfProfileOut( __METHOD__ );
3470 return $ret;
3471 }
3472
3473 /**
3474 * Return the text to be used for a given extension tag.
3475 * This is the ghost of strip().
3476 *
3477 * @param $params Associative array of parameters:
3478 * name PPNode for the tag name
3479 * attr PPNode for unparsed text where tag attributes are thought to be
3480 * attributes Optional associative array of parsed attributes
3481 * inner Contents of extension element
3482 * noClose Original text did not have a close tag
3483 * @param $frame PPFrame
3484 */
3485 function extensionSubstitution( $params, $frame ) {
3486 $name = $frame->expand( $params['name'] );
3487 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3488 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3489 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3490
3491 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) &&
3492 ( $this->ot['html'] || $this->ot['pre'] );
3493 if ( $isFunctionTag ) {
3494 $markerType = 'none';
3495 } else {
3496 $markerType = 'general';
3497 }
3498 if ( $this->ot['html'] || $isFunctionTag ) {
3499 $name = strtolower( $name );
3500 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3501 if ( isset( $params['attributes'] ) ) {
3502 $attributes = $attributes + $params['attributes'];
3503 }
3504
3505 if ( isset( $this->mTagHooks[$name] ) ) {
3506 # Workaround for PHP bug 35229 and similar
3507 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3508 throw new MWException( "Tag hook for $name is not callable\n" );
3509 }
3510 $output = call_user_func_array( $this->mTagHooks[$name],
3511 array( $content, $attributes, $this, $frame ) );
3512 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3513 list( $callback, $flags ) = $this->mFunctionTagHooks[$name];
3514 if ( !is_callable( $callback ) ) {
3515 throw new MWException( "Tag hook for $name is not callable\n" );
3516 }
3517
3518 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3519 } else {
3520 $output = '<span class="error">Invalid tag extension name: ' .
3521 htmlspecialchars( $name ) . '</span>';
3522 }
3523
3524 if ( is_array( $output ) ) {
3525 # Extract flags to local scope (to override $markerType)
3526 $flags = $output;
3527 $output = $flags[0];
3528 unset( $flags[0] );
3529 extract( $flags );
3530 }
3531 } else {
3532 if ( is_null( $attrText ) ) {
3533 $attrText = '';
3534 }
3535 if ( isset( $params['attributes'] ) ) {
3536 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3537 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3538 htmlspecialchars( $attrValue ) . '"';
3539 }
3540 }
3541 if ( $content === null ) {
3542 $output = "<$name$attrText/>";
3543 } else {
3544 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3545 $output = "<$name$attrText>$content$close";
3546 }
3547 }
3548
3549 if ( $markerType === 'none' ) {
3550 return $output;
3551 } elseif ( $markerType === 'nowiki' ) {
3552 $this->mStripState->nowiki->setPair( $marker, $output );
3553 } elseif ( $markerType === 'general' ) {
3554 $this->mStripState->general->setPair( $marker, $output );
3555 } else {
3556 throw new MWException( __METHOD__.': invalid marker type' );
3557 }
3558 return $marker;
3559 }
3560
3561 /**
3562 * Increment an include size counter
3563 *
3564 * @param $type String: the type of expansion
3565 * @param $size Integer: the size of the text
3566 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3567 */
3568 function incrementIncludeSize( $type, $size ) {
3569 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3570 return false;
3571 } else {
3572 $this->mIncludeSizes[$type] += $size;
3573 return true;
3574 }
3575 }
3576
3577 /**
3578 * Increment the expensive function count
3579 *
3580 * @return Boolean: false if the limit has been exceeded
3581 */
3582 function incrementExpensiveFunctionCount() {
3583 global $wgExpensiveParserFunctionLimit;
3584 $this->mExpensiveFunctionCount++;
3585 if ( $this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit ) {
3586 return true;
3587 }
3588 return false;
3589 }
3590
3591 /**
3592 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3593 * Fills $this->mDoubleUnderscores, returns the modified text
3594 */
3595 function doDoubleUnderscore( $text ) {
3596 wfProfileIn( __METHOD__ );
3597
3598 # The position of __TOC__ needs to be recorded
3599 $mw = MagicWord::get( 'toc' );
3600 if ( $mw->match( $text ) ) {
3601 $this->mShowToc = true;
3602 $this->mForceTocPosition = true;
3603
3604 # Set a placeholder. At the end we'll fill it in with the TOC.
3605 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3606
3607 # Only keep the first one.
3608 $text = $mw->replace( '', $text );
3609 }
3610
3611 # Now match and remove the rest of them
3612 $mwa = MagicWord::getDoubleUnderscoreArray();
3613 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3614
3615 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3616 $this->mOutput->mNoGallery = true;
3617 }
3618 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3619 $this->mShowToc = false;
3620 }
3621 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3622 $this->addTrackingCategory( 'hidden-category-category' );
3623 }
3624 # (bug 8068) Allow control over whether robots index a page.
3625 #
3626 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3627 # is not desirable, the last one on the page should win.
3628 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
3629 $this->mOutput->setIndexPolicy( 'noindex' );
3630 $this->addTrackingCategory( 'noindex-category' );
3631 }
3632 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
3633 $this->mOutput->setIndexPolicy( 'index' );
3634 $this->addTrackingCategory( 'index-category' );
3635 }
3636
3637 # Cache all double underscores in the database
3638 foreach ( $this->mDoubleUnderscores as $key => $val ) {
3639 $this->mOutput->setProperty( $key, '' );
3640 }
3641
3642 wfProfileOut( __METHOD__ );
3643 return $text;
3644 }
3645
3646 /**
3647 * Add a tracking category, getting the title from a system message,
3648 * or print a debug message if the title is invalid.
3649 *
3650 * @param $msg String: message key
3651 * @return Boolean: whether the addition was successful
3652 */
3653 protected function addTrackingCategory( $msg ) {
3654 $cat = wfMsgForContent( $msg );
3655
3656 # Allow tracking categories to be disabled by setting them to "-"
3657 if ( $cat === '-' ) {
3658 return false;
3659 }
3660
3661 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
3662 if ( $containerCategory ) {
3663 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3664 return true;
3665 } else {
3666 wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" );
3667 return false;
3668 }
3669 }
3670
3671 /**
3672 * This function accomplishes several tasks:
3673 * 1) Auto-number headings if that option is enabled
3674 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3675 * 3) Add a Table of contents on the top for users who have enabled the option
3676 * 4) Auto-anchor headings
3677 *
3678 * It loops through all headlines, collects the necessary data, then splits up the
3679 * string and re-inserts the newly formatted headlines.
3680 *
3681 * @param $text String
3682 * @param $origText String: original, untouched wikitext
3683 * @param $isMain Boolean
3684 * @private
3685 */
3686 function formatHeadings( $text, $origText, $isMain=true ) {
3687 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3688
3689 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3690
3691 # Inhibit editsection links if requested in the page
3692 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3693 $showEditLink = 0;
3694 } else {
3695 $showEditLink = $this->mOptions->getEditSection();
3696 }
3697
3698 # Get all headlines for numbering them and adding funky stuff like [edit]
3699 # links - this is for later, but we need the number of headlines right now
3700 $matches = array();
3701 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3702
3703 # if there are fewer than 4 headlines in the article, do not show TOC
3704 # unless it's been explicitly enabled.
3705 $enoughToc = $this->mShowToc &&
3706 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
3707
3708 # Allow user to stipulate that a page should have a "new section"
3709 # link added via __NEWSECTIONLINK__
3710 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3711 $this->mOutput->setNewSection( true );
3712 }
3713
3714 # Allow user to remove the "new section"
3715 # link via __NONEWSECTIONLINK__
3716 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
3717 $this->mOutput->hideNewSection( true );
3718 }
3719
3720 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3721 # override above conditions and always show TOC above first header
3722 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3723 $this->mShowToc = true;
3724 $enoughToc = true;
3725 }
3726
3727 # We need this to perform operations on the HTML
3728 $sk = $this->mOptions->getSkin( $this->mTitle );
3729
3730 # headline counter
3731 $headlineCount = 0;
3732 $numVisible = 0;
3733
3734 # Ugh .. the TOC should have neat indentation levels which can be
3735 # passed to the skin functions. These are determined here
3736 $toc = '';
3737 $full = '';
3738 $head = array();
3739 $sublevelCount = array();
3740 $levelCount = array();
3741 $level = 0;
3742 $prevlevel = 0;
3743 $toclevel = 0;
3744 $prevtoclevel = 0;
3745 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3746 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3747 $oldType = $this->mOutputType;
3748 $this->setOutputType( self::OT_WIKI );
3749 $frame = $this->getPreprocessor()->newFrame();
3750 $root = $this->preprocessToDom( $origText );
3751 $node = $root->getFirstChild();
3752 $byteOffset = 0;
3753 $tocraw = array();
3754 $refers = array();
3755
3756 foreach ( $matches[3] as $headline ) {
3757 $isTemplate = false;
3758 $titleText = false;
3759 $sectionIndex = false;
3760 $numbering = '';
3761 $markerMatches = array();
3762 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3763 $serial = $markerMatches[1];
3764 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3765 $isTemplate = ( $titleText != $baseTitleText );
3766 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3767 }
3768
3769 if ( $toclevel ) {
3770 $prevlevel = $level;
3771 }
3772 $level = $matches[1][$headlineCount];
3773
3774 if ( $level > $prevlevel ) {
3775 # Increase TOC level
3776 $toclevel++;
3777 $sublevelCount[$toclevel] = 0;
3778 if ( $toclevel<$wgMaxTocLevel ) {
3779 $prevtoclevel = $toclevel;
3780 $toc .= $sk->tocIndent();
3781 $numVisible++;
3782 }
3783 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3784 # Decrease TOC level, find level to jump to
3785
3786 for ( $i = $toclevel; $i > 0; $i-- ) {
3787 if ( $levelCount[$i] == $level ) {
3788 # Found last matching level
3789 $toclevel = $i;
3790 break;
3791 } elseif ( $levelCount[$i] < $level ) {
3792 # Found first matching level below current level
3793 $toclevel = $i + 1;
3794 break;
3795 }
3796 }
3797 if ( $i == 0 ) {
3798 $toclevel = 1;
3799 }
3800 if ( $toclevel<$wgMaxTocLevel ) {
3801 if ( $prevtoclevel < $wgMaxTocLevel ) {
3802 # Unindent only if the previous toc level was shown :p
3803 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3804 $prevtoclevel = $toclevel;
3805 } else {
3806 $toc .= $sk->tocLineEnd();
3807 }
3808 }
3809 } else {
3810 # No change in level, end TOC line
3811 if ( $toclevel<$wgMaxTocLevel ) {
3812 $toc .= $sk->tocLineEnd();
3813 }
3814 }
3815
3816 $levelCount[$toclevel] = $level;
3817
3818 # count number of headlines for each level
3819 @$sublevelCount[$toclevel]++;
3820 $dot = 0;
3821 for( $i = 1; $i <= $toclevel; $i++ ) {
3822 if ( !empty( $sublevelCount[$i] ) ) {
3823 if ( $dot ) {
3824 $numbering .= '.';
3825 }
3826 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3827 $dot = 1;
3828 }
3829 }
3830
3831 # The safe header is a version of the header text safe to use for links
3832 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3833 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3834
3835 # Remove link placeholders by the link text.
3836 # <!--LINK number-->
3837 # turns into
3838 # link text with suffix
3839 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3840
3841 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3842 $tocline = preg_replace(
3843 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3844 array( '', '<$1>' ),
3845 $safeHeadline
3846 );
3847 $tocline = trim( $tocline );
3848
3849 # For the anchor, strip out HTML-y stuff period
3850 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3851 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
3852
3853 # Save headline for section edit hint before it's escaped
3854 $headlineHint = $safeHeadline;
3855
3856 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3857 # For reverse compatibility, provide an id that's
3858 # HTML4-compatible, like we used to.
3859 #
3860 # It may be worth noting, academically, that it's possible for
3861 # the legacy anchor to conflict with a non-legacy headline
3862 # anchor on the page. In this case likely the "correct" thing
3863 # would be to either drop the legacy anchors or make sure
3864 # they're numbered first. However, this would require people
3865 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3866 # manually, so let's not bother worrying about it.
3867 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
3868 array( 'noninitial', 'legacy' ) );
3869 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3870
3871 if ( $legacyHeadline == $safeHeadline ) {
3872 # No reason to have both (in fact, we can't)
3873 $legacyHeadline = false;
3874 }
3875 } else {
3876 $legacyHeadline = false;
3877 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
3878 'noninitial' );
3879 }
3880
3881 # HTML names must be case-insensitively unique (bug 10721).
3882 # This does not apply to Unicode characters per
3883 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3884 # FIXME: We may be changing them depending on the current locale.
3885 $arrayKey = strtolower( $safeHeadline );
3886 if ( $legacyHeadline === false ) {
3887 $legacyArrayKey = false;
3888 } else {
3889 $legacyArrayKey = strtolower( $legacyHeadline );
3890 }
3891
3892 # count how many in assoc. array so we can track dupes in anchors
3893 if ( isset( $refers[$arrayKey] ) ) {
3894 $refers[$arrayKey]++;
3895 } else {
3896 $refers[$arrayKey] = 1;
3897 }
3898 if ( isset( $refers[$legacyArrayKey] ) ) {
3899 $refers[$legacyArrayKey]++;
3900 } else {
3901 $refers[$legacyArrayKey] = 1;
3902 }
3903
3904 # Don't number the heading if it is the only one (looks silly)
3905 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3906 # the two are different if the line contains a link
3907 $headline = $numbering . ' ' . $headline;
3908 }
3909
3910 # Create the anchor for linking from the TOC to the section
3911 $anchor = $safeHeadline;
3912 $legacyAnchor = $legacyHeadline;
3913 if ( $refers[$arrayKey] > 1 ) {
3914 $anchor .= '_' . $refers[$arrayKey];
3915 }
3916 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3917 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3918 }
3919 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
3920 $toc .= $sk->tocLine( $anchor, $tocline,
3921 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
3922 }
3923
3924 # Add the section to the section tree
3925 # Find the DOM node for this header
3926 while ( $node && !$isTemplate ) {
3927 if ( $node->getName() === 'h' ) {
3928 $bits = $node->splitHeading();
3929 if ( $bits['i'] == $sectionIndex ) {
3930 break;
3931 }
3932 }
3933 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
3934 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
3935 $node = $node->getNextSibling();
3936 }
3937 $tocraw[] = array(
3938 'toclevel' => $toclevel,
3939 'level' => $level,
3940 'line' => $tocline,
3941 'number' => $numbering,
3942 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
3943 'fromtitle' => $titleText,
3944 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
3945 'anchor' => $anchor,
3946 );
3947
3948 # give headline the correct <h#> tag
3949 if ( $showEditLink && $sectionIndex !== false ) {
3950 if ( $isTemplate ) {
3951 # Put a T flag in the section identifier, to indicate to extractSections()
3952 # that sections inside <includeonly> should be counted.
3953 $editlink = $sk->doEditSectionLink( Title::newFromText( $titleText ), "T-$sectionIndex", null, $this->mOptions->getUserLang() );
3954 } else {
3955 $editlink = $sk->doEditSectionLink( $this->mTitle, $sectionIndex, $headlineHint, $this->mOptions->getUserLang() );
3956 }
3957 } else {
3958 $editlink = '';
3959 }
3960 $head[$headlineCount] = $sk->makeHeadline( $level,
3961 $matches['attrib'][$headlineCount], $anchor, $headline,
3962 $editlink, $legacyAnchor );
3963
3964 $headlineCount++;
3965 }
3966
3967 $this->setOutputType( $oldType );
3968
3969 # Never ever show TOC if no headers
3970 if ( $numVisible < 1 ) {
3971 $enoughToc = false;
3972 }
3973
3974 if ( $enoughToc ) {
3975 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3976 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3977 }
3978 $toc = $sk->tocList( $toc );
3979 $this->mOutput->setTOCHTML( $toc );
3980 }
3981
3982 if ( $isMain ) {
3983 $this->mOutput->setSections( $tocraw );
3984 }
3985
3986 # split up and insert constructed headlines
3987
3988 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3989 $i = 0;
3990
3991 foreach ( $blocks as $block ) {
3992 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3993 # This is the [edit] link that appears for the top block of text when
3994 # section editing is enabled
3995
3996 # Disabled because it broke block formatting
3997 # For example, a bullet point in the top line
3998 # $full .= $sk->editSectionLink(0);
3999 }
4000 $full .= $block;
4001 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
4002 # Top anchor now in skin
4003 $full = $full.$toc;
4004 }
4005
4006 if ( !empty( $head[$i] ) ) {
4007 $full .= $head[$i];
4008 }
4009 $i++;
4010 }
4011 if ( $this->mForceTocPosition ) {
4012 return str_replace( '<!--MWTOC-->', $toc, $full );
4013 } else {
4014 return $full;
4015 }
4016 }
4017
4018 /**
4019 * Transform wiki markup when saving a page by doing \r\n -> \n
4020 * conversion, substitting signatures, {{subst:}} templates, etc.
4021 *
4022 * @param $text String: the text to transform
4023 * @param $title Title: the Title object for the current article
4024 * @param $user User: the User object describing the current user
4025 * @param $options ParserOptions: parsing options
4026 * @param $clearState Boolean: whether to clear the parser state first
4027 * @return String: the altered wiki markup
4028 */
4029 public function preSaveTransform( $text, Title $title, $user, $options, $clearState = true ) {
4030 $options->resetUsage();
4031 $this->mOptions = $options;
4032 $this->setTitle( $title );
4033 $this->setUser( $user );
4034 $this->setOutputType( self::OT_WIKI );
4035
4036 if ( $clearState ) {
4037 $this->clearState();
4038 }
4039
4040 $pairs = array(
4041 "\r\n" => "\n",
4042 );
4043 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4044 $text = $this->pstPass2( $text, $user );
4045 $text = $this->mStripState->unstripBoth( $text );
4046
4047 $this->setUser( null ); #Reset
4048
4049 return $text;
4050 }
4051
4052 /**
4053 * Pre-save transform helper function
4054 * @private
4055 */
4056 function pstPass2( $text, $user ) {
4057 global $wgContLang, $wgLocaltimezone;
4058
4059 # Note: This is the timestamp saved as hardcoded wikitext to
4060 # the database, we use $wgContLang here in order to give
4061 # everyone the same signature and use the default one rather
4062 # than the one selected in each user's preferences.
4063 # (see also bug 12815)
4064 $ts = $this->mOptions->getTimestamp();
4065 if ( isset( $wgLocaltimezone ) ) {
4066 $tz = $wgLocaltimezone;
4067 } else {
4068 $tz = date_default_timezone_get();
4069 }
4070
4071 $unixts = wfTimestamp( TS_UNIX, $ts );
4072 $oldtz = date_default_timezone_get();
4073 date_default_timezone_set( $tz );
4074 $ts = date( 'YmdHis', $unixts );
4075 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4076
4077 # Allow translation of timezones through wiki. date() can return
4078 # whatever crap the system uses, localised or not, so we cannot
4079 # ship premade translations.
4080 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4081 $value = wfMsgForContent( $key );
4082 if ( !wfEmptyMsg( $key, $value ) ) {
4083 $tzMsg = $value;
4084 }
4085
4086 date_default_timezone_set( $oldtz );
4087
4088 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4089
4090 # Variable replacement
4091 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4092 $text = $this->replaceVariables( $text );
4093
4094 # Signatures
4095 $sigText = $this->getUserSig( $user );
4096 $text = strtr( $text, array(
4097 '~~~~~' => $d,
4098 '~~~~' => "$sigText $d",
4099 '~~~' => $sigText
4100 ) );
4101
4102 # Context links: [[|name]] and [[name (context)|]]
4103 global $wgLegalTitleChars;
4104 $tc = "[$wgLegalTitleChars]";
4105 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4106
4107 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4108 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4109 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4110 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4111
4112 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4113 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4114 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4115 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4116
4117 $t = $this->mTitle->getText();
4118 $m = array();
4119 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4120 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4121 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4122 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4123 } else {
4124 # if there's no context, don't bother duplicating the title
4125 $text = preg_replace( $p2, '[[\\1]]', $text );
4126 }
4127
4128 # Trim trailing whitespace
4129 $text = rtrim( $text );
4130
4131 return $text;
4132 }
4133
4134 /**
4135 * Fetch the user's signature text, if any, and normalize to
4136 * validated, ready-to-insert wikitext.
4137 * If you have pre-fetched the nickname or the fancySig option, you can
4138 * specify them here to save a database query.
4139 *
4140 * @param $user User
4141 * @param $nickname String: nickname to use or false to use user's default nickname
4142 * @param $fancySig Boolean: whether the nicknname is the complete signature
4143 * or null to use default value
4144 * @return string
4145 */
4146 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4147 global $wgMaxSigChars;
4148
4149 $username = $user->getName();
4150
4151 # If not given, retrieve from the user object.
4152 if ( $nickname === false )
4153 $nickname = $user->getOption( 'nickname' );
4154
4155 if ( is_null( $fancySig ) ) {
4156 $fancySig = $user->getBoolOption( 'fancysig' );
4157 }
4158
4159 $nickname = $nickname == null ? $username : $nickname;
4160
4161 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4162 $nickname = $username;
4163 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4164 } elseif ( $fancySig !== false ) {
4165 # Sig. might contain markup; validate this
4166 if ( $this->validateSig( $nickname ) !== false ) {
4167 # Validated; clean up (if needed) and return it
4168 return $this->cleanSig( $nickname, true );
4169 } else {
4170 # Failed to validate; fall back to the default
4171 $nickname = $username;
4172 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
4173 }
4174 }
4175
4176 # Make sure nickname doesnt get a sig in a sig
4177 $nickname = $this->cleanSigInSig( $nickname );
4178
4179 # If we're still here, make it a link to the user page
4180 $userText = wfEscapeWikiText( $username );
4181 $nickText = wfEscapeWikiText( $nickname );
4182 if ( $user->isAnon() ) {
4183 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4184 } else {
4185 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4186 }
4187 }
4188
4189 /**
4190 * Check that the user's signature contains no bad XML
4191 *
4192 * @param $text String
4193 * @return mixed An expanded string, or false if invalid.
4194 */
4195 function validateSig( $text ) {
4196 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
4197 }
4198
4199 /**
4200 * Clean up signature text
4201 *
4202 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4203 * 2) Substitute all transclusions
4204 *
4205 * @param $text String
4206 * @param $parsing Whether we're cleaning (preferences save) or parsing
4207 * @return String: signature text
4208 */
4209 function cleanSig( $text, $parsing = false ) {
4210 if ( !$parsing ) {
4211 global $wgTitle;
4212 $this->clearState();
4213 $this->setTitle( $wgTitle );
4214 $this->mOptions = new ParserOptions;
4215 $this->setOutputType = self::OT_PREPROCESS;
4216 }
4217
4218 # Option to disable this feature
4219 if ( !$this->mOptions->getCleanSignatures() ) {
4220 return $text;
4221 }
4222
4223 # FIXME: regex doesn't respect extension tags or nowiki
4224 # => Move this logic to braceSubstitution()
4225 $substWord = MagicWord::get( 'subst' );
4226 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4227 $substText = '{{' . $substWord->getSynonym( 0 );
4228
4229 $text = preg_replace( $substRegex, $substText, $text );
4230 $text = $this->cleanSigInSig( $text );
4231 $dom = $this->preprocessToDom( $text );
4232 $frame = $this->getPreprocessor()->newFrame();
4233 $text = $frame->expand( $dom );
4234
4235 if ( !$parsing ) {
4236 $text = $this->mStripState->unstripBoth( $text );
4237 }
4238
4239 return $text;
4240 }
4241
4242 /**
4243 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4244 *
4245 * @param $text String
4246 * @return String: signature text with /~{3,5}/ removed
4247 */
4248 function cleanSigInSig( $text ) {
4249 $text = preg_replace( '/~{3,5}/', '', $text );
4250 return $text;
4251 }
4252
4253 /**
4254 * Set up some variables which are usually set up in parse()
4255 * so that an external function can call some class members with confidence
4256 */
4257 public function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4258 $this->setTitle( $title );
4259 $options->resetUsage();
4260 $this->mOptions = $options;
4261 $this->setOutputType( $outputType );
4262 if ( $clearState ) {
4263 $this->clearState();
4264 }
4265 }
4266
4267 /**
4268 * Wrapper for preprocess()
4269 *
4270 * @param $text String: the text to preprocess
4271 * @param $options ParserOptions: options
4272 * @return String
4273 */
4274 public function transformMsg( $text, $options ) {
4275 global $wgTitle;
4276 static $executing = false;
4277
4278 # Guard against infinite recursion
4279 if ( $executing ) {
4280 return $text;
4281 }
4282 $executing = true;
4283
4284 wfProfileIn( __METHOD__ );
4285 $text = $this->preprocess( $text, $wgTitle, $options );
4286
4287 $executing = false;
4288 wfProfileOut( __METHOD__ );
4289 return $text;
4290 }
4291
4292 /**
4293 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4294 * The callback should have the following form:
4295 * function myParserHook( $text, $params, $parser ) { ... }
4296 *
4297 * Transform and return $text. Use $parser for any required context, e.g. use
4298 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4299 *
4300 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4301 * @param $callback Mixed: the callback function (and object) to use for the tag
4302 * @return The old value of the mTagHooks array associated with the hook
4303 */
4304 public function setHook( $tag, $callback ) {
4305 $tag = strtolower( $tag );
4306 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4307 $this->mTagHooks[$tag] = $callback;
4308 if ( !in_array( $tag, $this->mStripList ) ) {
4309 $this->mStripList[] = $tag;
4310 }
4311
4312 return $oldVal;
4313 }
4314
4315 function setTransparentTagHook( $tag, $callback ) {
4316 $tag = strtolower( $tag );
4317 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4318 $this->mTransparentTagHooks[$tag] = $callback;
4319
4320 return $oldVal;
4321 }
4322
4323 /**
4324 * Remove all tag hooks
4325 */
4326 function clearTagHooks() {
4327 $this->mTagHooks = array();
4328 $this->mStripList = $this->mDefaultStripList;
4329 }
4330
4331 /**
4332 * Create a function, e.g. {{sum:1|2|3}}
4333 * The callback function should have the form:
4334 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4335 *
4336 * Or with SFH_OBJECT_ARGS:
4337 * function myParserFunction( $parser, $frame, $args ) { ... }
4338 *
4339 * The callback may either return the text result of the function, or an array with the text
4340 * in element 0, and a number of flags in the other elements. The names of the flags are
4341 * specified in the keys. Valid flags are:
4342 * found The text returned is valid, stop processing the template. This
4343 * is on by default.
4344 * nowiki Wiki markup in the return value should be escaped
4345 * isHTML The returned text is HTML, armour it against wikitext transformation
4346 *
4347 * @param $id String: The magic word ID
4348 * @param $callback Mixed: the callback function (and object) to use
4349 * @param $flags Integer: a combination of the following flags:
4350 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4351 *
4352 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4353 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4354 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4355 * the arguments, and to control the way they are expanded.
4356 *
4357 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4358 * arguments, for instance:
4359 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4360 *
4361 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4362 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4363 * working if/when this is changed.
4364 *
4365 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4366 * expansion.
4367 *
4368 * Please read the documentation in includes/parser/Preprocessor.php for more information
4369 * about the methods available in PPFrame and PPNode.
4370 *
4371 * @return The old callback function for this name, if any
4372 */
4373 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4374 global $wgContLang;
4375
4376 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4377 $this->mFunctionHooks[$id] = array( $callback, $flags );
4378
4379 # Add to function cache
4380 $mw = MagicWord::get( $id );
4381 if ( !$mw )
4382 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4383
4384 $synonyms = $mw->getSynonyms();
4385 $sensitive = intval( $mw->isCaseSensitive() );
4386
4387 foreach ( $synonyms as $syn ) {
4388 # Case
4389 if ( !$sensitive ) {
4390 $syn = $wgContLang->lc( $syn );
4391 }
4392 # Add leading hash
4393 if ( !( $flags & SFH_NO_HASH ) ) {
4394 $syn = '#' . $syn;
4395 }
4396 # Remove trailing colon
4397 if ( substr( $syn, -1, 1 ) === ':' ) {
4398 $syn = substr( $syn, 0, -1 );
4399 }
4400 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4401 }
4402 return $oldVal;
4403 }
4404
4405 /**
4406 * Get all registered function hook identifiers
4407 *
4408 * @return Array
4409 */
4410 function getFunctionHooks() {
4411 return array_keys( $this->mFunctionHooks );
4412 }
4413
4414 /**
4415 * Create a tag function, e.g. <test>some stuff</test>.
4416 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4417 * Unlike parser functions, their content is not preprocessed.
4418 */
4419 function setFunctionTagHook( $tag, $callback, $flags ) {
4420 $tag = strtolower( $tag );
4421 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4422 $this->mFunctionTagHooks[$tag] : null;
4423 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4424
4425 if ( !in_array( $tag, $this->mStripList ) ) {
4426 $this->mStripList[] = $tag;
4427 }
4428
4429 return $old;
4430 }
4431
4432 /**
4433 * FIXME: update documentation. makeLinkObj() is deprecated.
4434 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4435 * Placeholders created in Skin::makeLinkObj()
4436 * Returns an array of link CSS classes, indexed by PDBK.
4437 */
4438 function replaceLinkHolders( &$text, $options = 0 ) {
4439 return $this->mLinkHolders->replace( $text );
4440 }
4441
4442 /**
4443 * Replace <!--LINK--> link placeholders with plain text of links
4444 * (not HTML-formatted).
4445 *
4446 * @param $text String
4447 * @return String
4448 */
4449 function replaceLinkHoldersText( $text ) {
4450 return $this->mLinkHolders->replaceText( $text );
4451 }
4452
4453 /**
4454 * Renders an image gallery from a text with one line per image.
4455 * text labels may be given by using |-style alternative text. E.g.
4456 * Image:one.jpg|The number "1"
4457 * Image:tree.jpg|A tree
4458 * given as text will return the HTML of a gallery with two images,
4459 * labeled 'The number "1"' and
4460 * 'A tree'.
4461 */
4462 function renderImageGallery( $text, $params ) {
4463 $ig = new ImageGallery();
4464 $ig->setContextTitle( $this->mTitle );
4465 $ig->setShowBytes( false );
4466 $ig->setShowFilename( false );
4467 $ig->setParser( $this );
4468 $ig->setHideBadImages();
4469 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4470 $ig->useSkin( $this->mOptions->getSkin( $this->mTitle ) );
4471 $ig->mRevisionId = $this->mRevisionId;
4472
4473 if ( isset( $params['showfilename'] ) ) {
4474 $ig->setShowFilename( true );
4475 } else {
4476 $ig->setShowFilename( false );
4477 }
4478 if ( isset( $params['caption'] ) ) {
4479 $caption = $params['caption'];
4480 $caption = htmlspecialchars( $caption );
4481 $caption = $this->replaceInternalLinks( $caption );
4482 $ig->setCaptionHtml( $caption );
4483 }
4484 if ( isset( $params['perrow'] ) ) {
4485 $ig->setPerRow( $params['perrow'] );
4486 }
4487 if ( isset( $params['widths'] ) ) {
4488 $ig->setWidths( $params['widths'] );
4489 }
4490 if ( isset( $params['heights'] ) ) {
4491 $ig->setHeights( $params['heights'] );
4492 }
4493
4494 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4495
4496 $lines = StringUtils::explode( "\n", $text );
4497 foreach ( $lines as $line ) {
4498 # match lines like these:
4499 # Image:someimage.jpg|This is some image
4500 $matches = array();
4501 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4502 # Skip empty lines
4503 if ( count( $matches ) == 0 ) {
4504 continue;
4505 }
4506
4507 if ( strpos( $matches[0], '%' ) !== false ) {
4508 $matches[1] = urldecode( $matches[1] );
4509 }
4510 $tp = Title::newFromText( $matches[1] );
4511 $nt =& $tp;
4512 if ( is_null( $nt ) ) {
4513 # Bogus title. Ignore these so we don't bomb out later.
4514 continue;
4515 }
4516 if ( isset( $matches[3] ) ) {
4517 $label = $matches[3];
4518 } else {
4519 $label = '';
4520 }
4521
4522 $html = $this->recursiveTagParse( trim( $label ) );
4523
4524 $ig->add( $nt, $html );
4525
4526 # Only add real images (bug #5586)
4527 if ( $nt->getNamespace() == NS_FILE ) {
4528 $this->mOutput->addImage( $nt->getDBkey() );
4529 }
4530 }
4531 return $ig->toHTML();
4532 }
4533
4534 function getImageParams( $handler ) {
4535 if ( $handler ) {
4536 $handlerClass = get_class( $handler );
4537 } else {
4538 $handlerClass = '';
4539 }
4540 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4541 # Initialise static lists
4542 static $internalParamNames = array(
4543 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4544 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4545 'bottom', 'text-bottom' ),
4546 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4547 'upright', 'border', 'link', 'alt' ),
4548 );
4549 static $internalParamMap;
4550 if ( !$internalParamMap ) {
4551 $internalParamMap = array();
4552 foreach ( $internalParamNames as $type => $names ) {
4553 foreach ( $names as $name ) {
4554 $magicName = str_replace( '-', '_', "img_$name" );
4555 $internalParamMap[$magicName] = array( $type, $name );
4556 }
4557 }
4558 }
4559
4560 # Add handler params
4561 $paramMap = $internalParamMap;
4562 if ( $handler ) {
4563 $handlerParamMap = $handler->getParamMap();
4564 foreach ( $handlerParamMap as $magic => $paramName ) {
4565 $paramMap[$magic] = array( 'handler', $paramName );
4566 }
4567 }
4568 $this->mImageParams[$handlerClass] = $paramMap;
4569 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4570 }
4571 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4572 }
4573
4574 /**
4575 * Parse image options text and use it to make an image
4576 *
4577 * @param $title Title
4578 * @param $options String
4579 * @param $holders LinkHolderArray
4580 */
4581 function makeImage( $title, $options, $holders = false ) {
4582 # Check if the options text is of the form "options|alt text"
4583 # Options are:
4584 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4585 # * left no resizing, just left align. label is used for alt= only
4586 # * right same, but right aligned
4587 # * none same, but not aligned
4588 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4589 # * center center the image
4590 # * frame Keep original image size, no magnify-button.
4591 # * framed Same as "frame"
4592 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4593 # * upright reduce width for upright images, rounded to full __0 px
4594 # * border draw a 1px border around the image
4595 # * alt Text for HTML alt attribute (defaults to empty)
4596 # * link Set the target of the image link. Can be external, interwiki, or local
4597 # vertical-align values (no % or length right now):
4598 # * baseline
4599 # * sub
4600 # * super
4601 # * top
4602 # * text-top
4603 # * middle
4604 # * bottom
4605 # * text-bottom
4606
4607 $parts = StringUtils::explode( "|", $options );
4608 $sk = $this->mOptions->getSkin( $this->mTitle );
4609
4610 # Give extensions a chance to select the file revision for us
4611 $skip = $time = $descQuery = false;
4612 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4613
4614 if ( $skip ) {
4615 return $sk->link( $title );
4616 }
4617
4618 # Get the file
4619 $file = wfFindFile( $title, array( 'time' => $time ) );
4620 # Get parameter map
4621 $handler = $file ? $file->getHandler() : false;
4622
4623 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4624
4625 # Process the input parameters
4626 $caption = '';
4627 $params = array( 'frame' => array(), 'handler' => array(),
4628 'horizAlign' => array(), 'vertAlign' => array() );
4629 foreach ( $parts as $part ) {
4630 $part = trim( $part );
4631 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4632 $validated = false;
4633 if ( isset( $paramMap[$magicName] ) ) {
4634 list( $type, $paramName ) = $paramMap[$magicName];
4635
4636 # Special case; width and height come in one variable together
4637 if ( $type === 'handler' && $paramName === 'width' ) {
4638 $m = array();
4639 # (bug 13500) In both cases (width/height and width only),
4640 # permit trailing "px" for backward compatibility.
4641 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4642 $width = intval( $m[1] );
4643 $height = intval( $m[2] );
4644 if ( $handler->validateParam( 'width', $width ) ) {
4645 $params[$type]['width'] = $width;
4646 $validated = true;
4647 }
4648 if ( $handler->validateParam( 'height', $height ) ) {
4649 $params[$type]['height'] = $height;
4650 $validated = true;
4651 }
4652 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4653 $width = intval( $value );
4654 if ( $handler->validateParam( 'width', $width ) ) {
4655 $params[$type]['width'] = $width;
4656 $validated = true;
4657 }
4658 } # else no validation -- bug 13436
4659 } else {
4660 if ( $type === 'handler' ) {
4661 # Validate handler parameter
4662 $validated = $handler->validateParam( $paramName, $value );
4663 } else {
4664 # Validate internal parameters
4665 switch( $paramName ) {
4666 case 'manualthumb':
4667 case 'alt':
4668 # @todo Fixme: possibly check validity here for
4669 # manualthumb? downstream behavior seems odd with
4670 # missing manual thumbs.
4671 $validated = true;
4672 $value = $this->stripAltText( $value, $holders );
4673 break;
4674 case 'link':
4675 $chars = self::EXT_LINK_URL_CLASS;
4676 $prots = $this->mUrlProtocols;
4677 if ( $value === '' ) {
4678 $paramName = 'no-link';
4679 $value = true;
4680 $validated = true;
4681 } elseif ( preg_match( "/^$prots/", $value ) ) {
4682 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4683 $paramName = 'link-url';
4684 $this->mOutput->addExternalLink( $value );
4685 if ( $this->mOptions->getExternalLinkTarget() ) {
4686 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
4687 }
4688 $validated = true;
4689 }
4690 } else {
4691 $linkTitle = Title::newFromText( $value );
4692 if ( $linkTitle ) {
4693 $paramName = 'link-title';
4694 $value = $linkTitle;
4695 $this->mOutput->addLink( $linkTitle );
4696 $validated = true;
4697 }
4698 }
4699 break;
4700 default:
4701 # Most other things appear to be empty or numeric...
4702 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4703 }
4704 }
4705
4706 if ( $validated ) {
4707 $params[$type][$paramName] = $value;
4708 }
4709 }
4710 }
4711 if ( !$validated ) {
4712 $caption = $part;
4713 }
4714 }
4715
4716 # Process alignment parameters
4717 if ( $params['horizAlign'] ) {
4718 $params['frame']['align'] = key( $params['horizAlign'] );
4719 }
4720 if ( $params['vertAlign'] ) {
4721 $params['frame']['valign'] = key( $params['vertAlign'] );
4722 }
4723
4724 $params['frame']['caption'] = $caption;
4725
4726 # Will the image be presented in a frame, with the caption below?
4727 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4728 isset( $params['frame']['framed'] ) ||
4729 isset( $params['frame']['thumbnail'] ) ||
4730 isset( $params['frame']['manualthumb'] );
4731
4732 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4733 # came to also set the caption, ordinary text after the image -- which
4734 # makes no sense, because that just repeats the text multiple times in
4735 # screen readers. It *also* came to set the title attribute.
4736 #
4737 # Now that we have an alt attribute, we should not set the alt text to
4738 # equal the caption: that's worse than useless, it just repeats the
4739 # text. This is the framed/thumbnail case. If there's no caption, we
4740 # use the unnamed parameter for alt text as well, just for the time be-
4741 # ing, if the unnamed param is set and the alt param is not.
4742 #
4743 # For the future, we need to figure out if we want to tweak this more,
4744 # e.g., introducing a title= parameter for the title; ignoring the un-
4745 # named parameter entirely for images without a caption; adding an ex-
4746 # plicit caption= parameter and preserving the old magic unnamed para-
4747 # meter for BC; ...
4748 if ( $imageIsFramed ) { # Framed image
4749 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4750 # No caption or alt text, add the filename as the alt text so
4751 # that screen readers at least get some description of the image
4752 $params['frame']['alt'] = $title->getText();
4753 }
4754 # Do not set $params['frame']['title'] because tooltips don't make sense
4755 # for framed images
4756 } else { # Inline image
4757 if ( !isset( $params['frame']['alt'] ) ) {
4758 # No alt text, use the "caption" for the alt text
4759 if ( $caption !== '') {
4760 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4761 } else {
4762 # No caption, fall back to using the filename for the
4763 # alt text
4764 $params['frame']['alt'] = $title->getText();
4765 }
4766 }
4767 # Use the "caption" for the tooltip text
4768 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4769 }
4770
4771 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4772
4773 # Linker does the rest
4774 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions->getThumbSize() );
4775
4776 # Give the handler a chance to modify the parser object
4777 if ( $handler ) {
4778 $handler->parserTransformHook( $this, $file );
4779 }
4780
4781 return $ret;
4782 }
4783
4784 protected function stripAltText( $caption, $holders ) {
4785 # Strip bad stuff out of the title (tooltip). We can't just use
4786 # replaceLinkHoldersText() here, because if this function is called
4787 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4788 if ( $holders ) {
4789 $tooltip = $holders->replaceText( $caption );
4790 } else {
4791 $tooltip = $this->replaceLinkHoldersText( $caption );
4792 }
4793
4794 # make sure there are no placeholders in thumbnail attributes
4795 # that are later expanded to html- so expand them now and
4796 # remove the tags
4797 $tooltip = $this->mStripState->unstripBoth( $tooltip );
4798 $tooltip = Sanitizer::stripAllTags( $tooltip );
4799
4800 return $tooltip;
4801 }
4802
4803 /**
4804 * Set a flag in the output object indicating that the content is dynamic and
4805 * shouldn't be cached.
4806 */
4807 function disableCache() {
4808 wfDebug( "Parser output marked as uncacheable.\n" );
4809 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
4810 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
4811 }
4812
4813 /**
4814 * Callback from the Sanitizer for expanding items found in HTML attribute
4815 * values, so they can be safely tested and escaped.
4816 *
4817 * @param $text String
4818 * @param $frame PPFrame
4819 * @return String
4820 * @private
4821 */
4822 function attributeStripCallback( &$text, $frame = false ) {
4823 $text = $this->replaceVariables( $text, $frame );
4824 $text = $this->mStripState->unstripBoth( $text );
4825 return $text;
4826 }
4827
4828 /**
4829 * Accessor
4830 */
4831 function getTags() {
4832 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ) );
4833 }
4834
4835 /**
4836 * Break wikitext input into sections, and either pull or replace
4837 * some particular section's text.
4838 *
4839 * External callers should use the getSection and replaceSection methods.
4840 *
4841 * @param $text String: Page wikitext
4842 * @param $section String: a section identifier string of the form:
4843 * <flag1> - <flag2> - ... - <section number>
4844 *
4845 * Currently the only recognised flag is "T", which means the target section number
4846 * was derived during a template inclusion parse, in other words this is a template
4847 * section edit link. If no flags are given, it was an ordinary section edit link.
4848 * This flag is required to avoid a section numbering mismatch when a section is
4849 * enclosed by <includeonly> (bug 6563).
4850 *
4851 * The section number 0 pulls the text before the first heading; other numbers will
4852 * pull the given section along with its lower-level subsections. If the section is
4853 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4854 *
4855 * @param $mode String: one of "get" or "replace"
4856 * @param $newText String: replacement text for section data.
4857 * @return String: for "get", the extracted section text.
4858 * for "replace", the whole page with the section replaced.
4859 */
4860 private function extractSections( $text, $section, $mode, $newText='' ) {
4861 global $wgTitle;
4862 $this->clearState();
4863 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4864 $this->mOptions = new ParserOptions;
4865 $this->setOutputType( self::OT_PLAIN );
4866 $outText = '';
4867 $frame = $this->getPreprocessor()->newFrame();
4868
4869 # Process section extraction flags
4870 $flags = 0;
4871 $sectionParts = explode( '-', $section );
4872 $sectionIndex = array_pop( $sectionParts );
4873 foreach ( $sectionParts as $part ) {
4874 if ( $part === 'T' ) {
4875 $flags |= self::PTD_FOR_INCLUSION;
4876 }
4877 }
4878 # Preprocess the text
4879 $root = $this->preprocessToDom( $text, $flags );
4880
4881 # <h> nodes indicate section breaks
4882 # They can only occur at the top level, so we can find them by iterating the root's children
4883 $node = $root->getFirstChild();
4884
4885 # Find the target section
4886 if ( $sectionIndex == 0 ) {
4887 # Section zero doesn't nest, level=big
4888 $targetLevel = 1000;
4889 } else {
4890 while ( $node ) {
4891 if ( $node->getName() === 'h' ) {
4892 $bits = $node->splitHeading();
4893 if ( $bits['i'] == $sectionIndex ) {
4894 $targetLevel = $bits['level'];
4895 break;
4896 }
4897 }
4898 if ( $mode === 'replace' ) {
4899 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4900 }
4901 $node = $node->getNextSibling();
4902 }
4903 }
4904
4905 if ( !$node ) {
4906 # Not found
4907 if ( $mode === 'get' ) {
4908 return $newText;
4909 } else {
4910 return $text;
4911 }
4912 }
4913
4914 # Find the end of the section, including nested sections
4915 do {
4916 if ( $node->getName() === 'h' ) {
4917 $bits = $node->splitHeading();
4918 $curLevel = $bits['level'];
4919 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4920 break;
4921 }
4922 }
4923 if ( $mode === 'get' ) {
4924 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4925 }
4926 $node = $node->getNextSibling();
4927 } while ( $node );
4928
4929 # Write out the remainder (in replace mode only)
4930 if ( $mode === 'replace' ) {
4931 # Output the replacement text
4932 # Add two newlines on -- trailing whitespace in $newText is conventionally
4933 # stripped by the editor, so we need both newlines to restore the paragraph gap
4934 # Only add trailing whitespace if there is newText
4935 if ( $newText != "" ) {
4936 $outText .= $newText . "\n\n";
4937 }
4938
4939 while ( $node ) {
4940 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4941 $node = $node->getNextSibling();
4942 }
4943 }
4944
4945 if ( is_string( $outText ) ) {
4946 # Re-insert stripped tags
4947 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4948 }
4949
4950 return $outText;
4951 }
4952
4953 /**
4954 * This function returns the text of a section, specified by a number ($section).
4955 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4956 * the first section before any such heading (section 0).
4957 *
4958 * If a section contains subsections, these are also returned.
4959 *
4960 * @param $text String: text to look in
4961 * @param $section String: section identifier
4962 * @param $deftext String: default to return if section is not found
4963 * @return string text of the requested section
4964 */
4965 public function getSection( $text, $section, $deftext='' ) {
4966 return $this->extractSections( $text, $section, "get", $deftext );
4967 }
4968
4969 public function replaceSection( $oldtext, $section, $text ) {
4970 return $this->extractSections( $oldtext, $section, "replace", $text );
4971 }
4972
4973 /**
4974 * Get the ID of the revision we are parsing
4975 *
4976 * @return Mixed: integer or null
4977 */
4978 function getRevisionId() {
4979 return $this->mRevisionId;
4980 }
4981
4982 /**
4983 * Get the revision object for $this->mRevisionId
4984 *
4985 * @return either a Revision object or null
4986 */
4987 protected function getRevisionObject() {
4988 if ( !is_null( $this->mRevisionObject ) ) {
4989 return $this->mRevisionObject;
4990 }
4991 if ( is_null( $this->mRevisionId ) ) {
4992 return null;
4993 }
4994
4995 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
4996 return $this->mRevisionObject;
4997 }
4998
4999 /**
5000 * Get the timestamp associated with the current revision, adjusted for
5001 * the default server-local timestamp
5002 */
5003 function getRevisionTimestamp() {
5004 if ( is_null( $this->mRevisionTimestamp ) ) {
5005 wfProfileIn( __METHOD__ );
5006
5007 $revObject = $this->getRevisionObject();
5008 $timestamp = $revObject ? $revObject->getTimestamp() : false;
5009
5010 if( $timestamp !== false ) {
5011 global $wgContLang;
5012
5013 # The cryptic '' timezone parameter tells to use the site-default
5014 # timezone offset instead of the user settings.
5015 #
5016 # Since this value will be saved into the parser cache, served
5017 # to other users, and potentially even used inside links and such,
5018 # it needs to be consistent for all visitors.
5019 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5020 }
5021
5022 wfProfileOut( __METHOD__ );
5023 }
5024 return $this->mRevisionTimestamp;
5025 }
5026
5027 /**
5028 * Get the name of the user that edited the last revision
5029 *
5030 * @return String: user name
5031 */
5032 function getRevisionUser() {
5033 if( is_null( $this->mRevisionUser ) ) {
5034 $revObject = $this->getRevisionObject();
5035
5036 # if this template is subst: the revision id will be blank,
5037 # so just use the current user's name
5038 if( $revObject ) {
5039 $this->mRevisionUser = $revObject->getUserText();
5040 } elseif( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5041 $this->mRevisionUser = $this->getUser()->getName();
5042 }
5043 }
5044 return $this->mRevisionUser;
5045 }
5046
5047 /**
5048 * Mutator for $mDefaultSort
5049 *
5050 * @param $sort New value
5051 */
5052 public function setDefaultSort( $sort ) {
5053 $this->mDefaultSort = $sort;
5054 $this->mOutput->setProperty( 'defaultsort', $sort );
5055 }
5056
5057 /**
5058 * Accessor for $mDefaultSort
5059 * Will use the title/prefixed title if none is set
5060 *
5061 * @return string
5062 */
5063 public function getDefaultSort() {
5064 if ( $this->mDefaultSort !== false ) {
5065 return $this->mDefaultSort;
5066 } else {
5067 return $this->mTitle->getCategorySortkey();
5068 }
5069 }
5070
5071 /**
5072 * Accessor for $mDefaultSort
5073 * Unlike getDefaultSort(), will return false if none is set
5074 *
5075 * @return string or false
5076 */
5077 public function getCustomDefaultSort() {
5078 return $this->mDefaultSort;
5079 }
5080
5081 /**
5082 * Try to guess the section anchor name based on a wikitext fragment
5083 * presumably extracted from a heading, for example "Header" from
5084 * "== Header ==".
5085 */
5086 public function guessSectionNameFromWikiText( $text ) {
5087 # Strip out wikitext links(they break the anchor)
5088 $text = $this->stripSectionName( $text );
5089 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5090 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5091 }
5092
5093 /**
5094 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5095 * instead. For use in redirects, since IE6 interprets Redirect: headers
5096 * as something other than UTF-8 (apparently?), resulting in breakage.
5097 *
5098 * @param $text String: The section name
5099 * @return string An anchor
5100 */
5101 public function guessLegacySectionNameFromWikiText( $text ) {
5102 # Strip out wikitext links(they break the anchor)
5103 $text = $this->stripSectionName( $text );
5104 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5105 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
5106 }
5107
5108 /**
5109 * Strips a text string of wikitext for use in a section anchor
5110 *
5111 * Accepts a text string and then removes all wikitext from the
5112 * string and leaves only the resultant text (i.e. the result of
5113 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5114 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5115 * to create valid section anchors by mimicing the output of the
5116 * parser when headings are parsed.
5117 *
5118 * @param $text String: text string to be stripped of wikitext
5119 * for use in a Section anchor
5120 * @return Filtered text string
5121 */
5122 public function stripSectionName( $text ) {
5123 # Strip internal link markup
5124 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5125 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5126
5127 # Strip external link markup (FIXME: Not Tolerant to blank link text
5128 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5129 # on how many empty links there are on the page - need to figure that out.
5130 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5131
5132 # Parse wikitext quotes (italics & bold)
5133 $text = $this->doQuotes( $text );
5134
5135 # Strip HTML tags
5136 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5137 return $text;
5138 }
5139
5140 /**
5141 * strip/replaceVariables/unstrip for preprocessor regression testing
5142 */
5143 function testSrvus( $text, $title, $options, $outputType = self::OT_HTML ) {
5144 $this->clearState();
5145 if ( !$title instanceof Title ) {
5146 $title = Title::newFromText( $title );
5147 }
5148 $this->mTitle = $title;
5149 $options->resetUsage();
5150 $this->mOptions = $options;
5151 $this->setOutputType( $outputType );
5152 $text = $this->replaceVariables( $text );
5153 $text = $this->mStripState->unstripBoth( $text );
5154 $text = Sanitizer::removeHTMLtags( $text );
5155 return $text;
5156 }
5157
5158 function testPst( $text, $title, $options ) {
5159 global $wgUser;
5160 if ( !$title instanceof Title ) {
5161 $title = Title::newFromText( $title );
5162 }
5163 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5164 }
5165
5166 function testPreprocess( $text, $title, $options ) {
5167 if ( !$title instanceof Title ) {
5168 $title = Title::newFromText( $title );
5169 }
5170 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5171 }
5172
5173 function markerSkipCallback( $s, $callback ) {
5174 $i = 0;
5175 $out = '';
5176 while ( $i < strlen( $s ) ) {
5177 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5178 if ( $markerStart === false ) {
5179 $out .= call_user_func( $callback, substr( $s, $i ) );
5180 break;
5181 } else {
5182 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5183 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5184 if ( $markerEnd === false ) {
5185 $out .= substr( $s, $markerStart );
5186 break;
5187 } else {
5188 $markerEnd += strlen( self::MARKER_SUFFIX );
5189 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5190 $i = $markerEnd;
5191 }
5192 }
5193 }
5194 return $out;
5195 }
5196
5197 function serialiseHalfParsedText( $text ) {
5198 $data = array();
5199 $data['text'] = $text;
5200
5201 # First, find all strip markers, and store their
5202 # data in an array.
5203 $stripState = new StripState;
5204 $pos = 0;
5205 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix, $pos ) )
5206 && ( $end_pos = strpos( $text, self::MARKER_SUFFIX, $pos ) ) )
5207 {
5208 $end_pos += strlen( self::MARKER_SUFFIX );
5209 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5210
5211 if ( !empty( $this->mStripState->general->data[$marker] ) ) {
5212 $replaceArray = $stripState->general;
5213 $stripText = $this->mStripState->general->data[$marker];
5214 } elseif ( !empty( $this->mStripState->nowiki->data[$marker] ) ) {
5215 $replaceArray = $stripState->nowiki;
5216 $stripText = $this->mStripState->nowiki->data[$marker];
5217 } else {
5218 throw new MWException( "Hanging strip marker: '$marker'." );
5219 }
5220
5221 $replaceArray->setPair( $marker, $stripText );
5222 $pos = $end_pos;
5223 }
5224 $data['stripstate'] = $stripState;
5225
5226 # Now, find all of our links, and store THEIR
5227 # data in an array! :)
5228 $links = array( 'internal' => array(), 'interwiki' => array() );
5229 $pos = 0;
5230
5231 # Internal links
5232 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5233 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos + strlen( '<!--LINK ' ) ), 2 );
5234
5235 $ns = trim( $ns );
5236 if ( empty( $links['internal'][$ns] ) ) {
5237 $links['internal'][$ns] = array();
5238 }
5239
5240 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5241 $links['internal'][$ns][] = $this->mLinkHolders->internals[$ns][$key];
5242 $pos = $start_pos + strlen( "<!--LINK $ns:$key-->" );
5243 }
5244
5245 $pos = 0;
5246
5247 # Interwiki links
5248 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5249 $data = substr( $text, $start_pos );
5250 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5251 $links['interwiki'][] = $this->mLinkHolders->interwiki[$key];
5252 $pos = $start_pos + strlen( "<!--IWLINK $key-->" );
5253 }
5254
5255 $data['linkholder'] = $links;
5256
5257 return $data;
5258 }
5259
5260 /**
5261 * TODO: document
5262 * @param $data Array
5263 * @param $intPrefix String unique identifying prefix
5264 * @return String
5265 */
5266 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5267 if ( !$intPrefix ) {
5268 $intPrefix = self::getRandomString();
5269 }
5270
5271 # First, extract the strip state.
5272 $stripState = $data['stripstate'];
5273 $this->mStripState->general->merge( $stripState->general );
5274 $this->mStripState->nowiki->merge( $stripState->nowiki );
5275
5276 # Now, extract the text, and renumber links
5277 $text = $data['text'];
5278 $links = $data['linkholder'];
5279
5280 # Internal...
5281 foreach ( $links['internal'] as $ns => $nsLinks ) {
5282 foreach ( $nsLinks as $key => $entry ) {
5283 $newKey = $intPrefix . '-' . $key;
5284 $this->mLinkHolders->internals[$ns][$newKey] = $entry;
5285
5286 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5287 }
5288 }
5289
5290 # Interwiki...
5291 foreach ( $links['interwiki'] as $key => $entry ) {
5292 $newKey = "$intPrefix-$key";
5293 $this->mLinkHolders->interwikis[$newKey] = $entry;
5294
5295 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5296 }
5297
5298 # Should be good to go.
5299 return $text;
5300 }
5301 }
5302
5303 /**
5304 * @todo document, briefly.
5305 * @ingroup Parser
5306 */
5307 class StripState {
5308 var $general, $nowiki;
5309
5310 function __construct() {
5311 $this->general = new ReplacementArray;
5312 $this->nowiki = new ReplacementArray;
5313 }
5314
5315 function unstripGeneral( $text ) {
5316 wfProfileIn( __METHOD__ );
5317 do {
5318 $oldText = $text;
5319 $text = $this->general->replace( $text );
5320 } while ( $text !== $oldText );
5321 wfProfileOut( __METHOD__ );
5322 return $text;
5323 }
5324
5325 function unstripNoWiki( $text ) {
5326 wfProfileIn( __METHOD__ );
5327 do {
5328 $oldText = $text;
5329 $text = $this->nowiki->replace( $text );
5330 } while ( $text !== $oldText );
5331 wfProfileOut( __METHOD__ );
5332 return $text;
5333 }
5334
5335 function unstripBoth( $text ) {
5336 wfProfileIn( __METHOD__ );
5337 do {
5338 $oldText = $text;
5339 $text = $this->general->replace( $text );
5340 $text = $this->nowiki->replace( $text );
5341 } while ( $text !== $oldText );
5342 wfProfileOut( __METHOD__ );
5343 return $text;
5344 }
5345 }
5346
5347 /**
5348 * @todo document, briefly.
5349 * @ingroup Parser
5350 */
5351 class OnlyIncludeReplacer {
5352 var $output = '';
5353
5354 function replace( $matches ) {
5355 if ( substr( $matches[1], -1 ) === "\n" ) {
5356 $this->output .= substr( $matches[1], 0, -1 );
5357 } else {
5358 $this->output .= $matches[1];
5359 }
5360 }
5361 }