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