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