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