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