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