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