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