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