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