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