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