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