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