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