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