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