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