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