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