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