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