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