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