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