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