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