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