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