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