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