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