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