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