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