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