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