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