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