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