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