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