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