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