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