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