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