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