Merge "Set wgScript in LinkerTest"
[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 global $wgExtraInterlanguageLinkPrefixes;
1880 wfProfileIn( __METHOD__ );
1881
1882 wfProfileIn( __METHOD__ . '-setup' );
1883 static $tc = false, $e1, $e1_img;
1884 # the % is needed to support urlencoded titles as well
1885 if ( !$tc ) {
1886 $tc = Title::legalChars() . '#%';
1887 # Match a link having the form [[namespace:link|alternate]]trail
1888 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1889 # Match cases where there is no "]]", which might still be images
1890 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1891 }
1892
1893 $holders = new LinkHolderArray( $this );
1894
1895 # split the entire text string on occurrences of [[
1896 $a = StringUtils::explode( '[[', ' ' . $s );
1897 # get the first element (all text up to first [[), and remove the space we added
1898 $s = $a->current();
1899 $a->next();
1900 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1901 $s = substr( $s, 1 );
1902
1903 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1904 $e2 = null;
1905 if ( $useLinkPrefixExtension ) {
1906 # Match the end of a line for a word that's not followed by whitespace,
1907 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1908 global $wgContLang;
1909 $charset = $wgContLang->linkPrefixCharset();
1910 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
1911 }
1912
1913 if ( is_null( $this->mTitle ) ) {
1914 wfProfileOut( __METHOD__ . '-setup' );
1915 wfProfileOut( __METHOD__ );
1916 throw new MWException( __METHOD__ . ": \$this->mTitle is null\n" );
1917 }
1918 $nottalk = !$this->mTitle->isTalkPage();
1919
1920 if ( $useLinkPrefixExtension ) {
1921 $m = array();
1922 if ( preg_match( $e2, $s, $m ) ) {
1923 $first_prefix = $m[2];
1924 } else {
1925 $first_prefix = false;
1926 }
1927 } else {
1928 $prefix = '';
1929 }
1930
1931 $useSubpages = $this->areSubpagesAllowed();
1932 wfProfileOut( __METHOD__ . '-setup' );
1933
1934 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
1935 # Loop for each link
1936 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1937 // @codingStandardsIgnoreStart
1938
1939 # Check for excessive memory usage
1940 if ( $holders->isBig() ) {
1941 # Too big
1942 # Do the existence check, replace the link holders and clear the array
1943 $holders->replace( $s );
1944 $holders->clear();
1945 }
1946
1947 if ( $useLinkPrefixExtension ) {
1948 wfProfileIn( __METHOD__ . '-prefixhandling' );
1949 if ( preg_match( $e2, $s, $m ) ) {
1950 $prefix = $m[2];
1951 $s = $m[1];
1952 } else {
1953 $prefix = '';
1954 }
1955 # first link
1956 if ( $first_prefix ) {
1957 $prefix = $first_prefix;
1958 $first_prefix = false;
1959 }
1960 wfProfileOut( __METHOD__ . '-prefixhandling' );
1961 }
1962
1963 $might_be_img = false;
1964
1965 wfProfileIn( __METHOD__ . "-e1" );
1966 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1967 $text = $m[2];
1968 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1969 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1970 # the real problem is with the $e1 regex
1971 # See bug 1300.
1972 #
1973 # Still some problems for cases where the ] is meant to be outside punctuation,
1974 # and no image is in sight. See bug 2095.
1975 #
1976 if ( $text !== ''
1977 && substr( $m[3], 0, 1 ) === ']'
1978 && strpos( $text, '[' ) !== false
1979 ) {
1980 $text .= ']'; # so that replaceExternalLinks($text) works later
1981 $m[3] = substr( $m[3], 1 );
1982 }
1983 # fix up urlencoded title texts
1984 if ( strpos( $m[1], '%' ) !== false ) {
1985 # Should anchors '#' also be rejected?
1986 $m[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $m[1] ) );
1987 }
1988 $trail = $m[3];
1989 } elseif ( preg_match( $e1_img, $line, $m ) ) {
1990 # Invalid, but might be an image with a link in its caption
1991 $might_be_img = true;
1992 $text = $m[2];
1993 if ( strpos( $m[1], '%' ) !== false ) {
1994 $m[1] = rawurldecode( $m[1] );
1995 }
1996 $trail = "";
1997 } else { # Invalid form; output directly
1998 $s .= $prefix . '[[' . $line;
1999 wfProfileOut( __METHOD__ . "-e1" );
2000 continue;
2001 }
2002 wfProfileOut( __METHOD__ . "-e1" );
2003 wfProfileIn( __METHOD__ . "-misc" );
2004
2005 # Don't allow internal links to pages containing
2006 # PROTO: where PROTO is a valid URL protocol; these
2007 # should be external links.
2008 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $m[1] ) ) {
2009 $s .= $prefix . '[[' . $line;
2010 wfProfileOut( __METHOD__ . "-misc" );
2011 continue;
2012 }
2013
2014 # Make subpage if necessary
2015 if ( $useSubpages ) {
2016 $link = $this->maybeDoSubpageLink( $m[1], $text );
2017 } else {
2018 $link = $m[1];
2019 }
2020
2021 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
2022 if ( !$noforce ) {
2023 # Strip off leading ':'
2024 $link = substr( $link, 1 );
2025 }
2026
2027 wfProfileOut( __METHOD__ . "-misc" );
2028 wfProfileIn( __METHOD__ . "-title" );
2029 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
2030 if ( $nt === null ) {
2031 $s .= $prefix . '[[' . $line;
2032 wfProfileOut( __METHOD__ . "-title" );
2033 continue;
2034 }
2035
2036 $ns = $nt->getNamespace();
2037 $iw = $nt->getInterwiki();
2038 wfProfileOut( __METHOD__ . "-title" );
2039
2040 if ( $might_be_img ) { # if this is actually an invalid link
2041 wfProfileIn( __METHOD__ . "-might_be_img" );
2042 if ( $ns == NS_FILE && $noforce ) { # but might be an image
2043 $found = false;
2044 while ( true ) {
2045 # look at the next 'line' to see if we can close it there
2046 $a->next();
2047 $next_line = $a->current();
2048 if ( $next_line === false || $next_line === null ) {
2049 break;
2050 }
2051 $m = explode( ']]', $next_line, 3 );
2052 if ( count( $m ) == 3 ) {
2053 # the first ]] closes the inner link, the second the image
2054 $found = true;
2055 $text .= "[[{$m[0]}]]{$m[1]}";
2056 $trail = $m[2];
2057 break;
2058 } elseif ( count( $m ) == 2 ) {
2059 # if there's exactly one ]] that's fine, we'll keep looking
2060 $text .= "[[{$m[0]}]]{$m[1]}";
2061 } else {
2062 # if $next_line is invalid too, we need look no further
2063 $text .= '[[' . $next_line;
2064 break;
2065 }
2066 }
2067 if ( !$found ) {
2068 # we couldn't find the end of this imageLink, so output it raw
2069 # but don't ignore what might be perfectly normal links in the text we've examined
2070 $holders->merge( $this->replaceInternalLinks2( $text ) );
2071 $s .= "{$prefix}[[$link|$text";
2072 # note: no $trail, because without an end, there *is* no trail
2073 wfProfileOut( __METHOD__ . "-might_be_img" );
2074 continue;
2075 }
2076 } else { # it's not an image, so output it raw
2077 $s .= "{$prefix}[[$link|$text";
2078 # note: no $trail, because without an end, there *is* no trail
2079 wfProfileOut( __METHOD__ . "-might_be_img" );
2080 continue;
2081 }
2082 wfProfileOut( __METHOD__ . "-might_be_img" );
2083 }
2084
2085 $wasblank = ( $text == '' );
2086 if ( $wasblank ) {
2087 $text = $link;
2088 } else {
2089 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2090 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2091 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2092 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2093 $text = $this->doQuotes( $text );
2094 }
2095
2096 # Link not escaped by : , create the various objects
2097 if ( $noforce ) {
2098 # Interwikis
2099 wfProfileIn( __METHOD__ . "-interwiki" );
2100 if (
2101 $iw && $this->mOptions->getInterwikiMagic() && $nottalk && (
2102 Language::fetchLanguageName( $iw, null, 'mw' ) ||
2103 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2104 )
2105 ) {
2106 # Bug 24502: filter duplicates
2107 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
2108 $this->mLangLinkLanguages[$iw] = true;
2109 $this->mOutput->addLanguageLink( $nt->getFullText() );
2110 }
2111
2112 $s = rtrim( $s . $prefix );
2113 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
2114 wfProfileOut( __METHOD__ . "-interwiki" );
2115 continue;
2116 }
2117 wfProfileOut( __METHOD__ . "-interwiki" );
2118
2119 if ( $ns == NS_FILE ) {
2120 wfProfileIn( __METHOD__ . "-image" );
2121 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
2122 if ( $wasblank ) {
2123 # if no parameters were passed, $text
2124 # becomes something like "File:Foo.png",
2125 # which we don't want to pass on to the
2126 # image generator
2127 $text = '';
2128 } else {
2129 # recursively parse links inside the image caption
2130 # actually, this will parse them in any other parameters, too,
2131 # but it might be hard to fix that, and it doesn't matter ATM
2132 $text = $this->replaceExternalLinks( $text );
2133 $holders->merge( $this->replaceInternalLinks2( $text ) );
2134 }
2135 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2136 $s .= $prefix . $this->armorLinks(
2137 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2138 } else {
2139 $s .= $prefix . $trail;
2140 }
2141 wfProfileOut( __METHOD__ . "-image" );
2142 continue;
2143 }
2144
2145 if ( $ns == NS_CATEGORY ) {
2146 wfProfileIn( __METHOD__ . "-category" );
2147 $s = rtrim( $s . "\n" ); # bug 87
2148
2149 if ( $wasblank ) {
2150 $sortkey = $this->getDefaultSort();
2151 } else {
2152 $sortkey = $text;
2153 }
2154 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2155 $sortkey = str_replace( "\n", '', $sortkey );
2156 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2157 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2158
2159 /**
2160 * Strip the whitespace Category links produce, see bug 87
2161 */
2162 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
2163
2164 wfProfileOut( __METHOD__ . "-category" );
2165 continue;
2166 }
2167 }
2168
2169 # Self-link checking. For some languages, variants of the title are checked in
2170 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2171 # for linking to a different variant.
2172 if ( $ns != NS_SPECIAL && $nt->equals( $this->mTitle ) && !$nt->hasFragment() ) {
2173 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2174 continue;
2175 }
2176
2177 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2178 # @todo FIXME: Should do batch file existence checks, see comment below
2179 if ( $ns == NS_MEDIA ) {
2180 wfProfileIn( __METHOD__ . "-media" );
2181 # Give extensions a chance to select the file revision for us
2182 $options = array();
2183 $descQuery = false;
2184 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2185 array( $this, $nt, &$options, &$descQuery ) );
2186 # Fetch and register the file (file title may be different via hooks)
2187 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2188 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2189 $s .= $prefix . $this->armorLinks(
2190 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2191 wfProfileOut( __METHOD__ . "-media" );
2192 continue;
2193 }
2194
2195 wfProfileIn( __METHOD__ . "-always_known" );
2196 # Some titles, such as valid special pages or files in foreign repos, should
2197 # be shown as bluelinks even though they're not included in the page table
2198 #
2199 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2200 # batch file existence checks for NS_FILE and NS_MEDIA
2201 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2202 $this->mOutput->addLink( $nt );
2203 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2204 } else {
2205 # Links will be added to the output link list after checking
2206 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2207 }
2208 wfProfileOut( __METHOD__ . "-always_known" );
2209 }
2210 wfProfileOut( __METHOD__ );
2211 return $holders;
2212 }
2213
2214 /**
2215 * Render a forced-blue link inline; protect against double expansion of
2216 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2217 * Since this little disaster has to split off the trail text to avoid
2218 * breaking URLs in the following text without breaking trails on the
2219 * wiki links, it's been made into a horrible function.
2220 *
2221 * @param Title $nt
2222 * @param string $text
2223 * @param array|string $query
2224 * @param string $trail
2225 * @param string $prefix
2226 * @return string HTML-wikitext mix oh yuck
2227 */
2228 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2229 list( $inside, $trail ) = Linker::splitTrail( $trail );
2230
2231 if ( is_string( $query ) ) {
2232 $query = wfCgiToArray( $query );
2233 }
2234 if ( $text == '' ) {
2235 $text = htmlspecialchars( $nt->getPrefixedText() );
2236 }
2237
2238 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2239
2240 return $this->armorLinks( $link ) . $trail;
2241 }
2242
2243 /**
2244 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2245 * going to go through further parsing steps before inline URL expansion.
2246 *
2247 * Not needed quite as much as it used to be since free links are a bit
2248 * more sensible these days. But bracketed links are still an issue.
2249 *
2250 * @param string $text More-or-less HTML
2251 * @return string Less-or-more HTML with NOPARSE bits
2252 */
2253 function armorLinks( $text ) {
2254 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2255 "{$this->mUniqPrefix}NOPARSE$1", $text );
2256 }
2257
2258 /**
2259 * Return true if subpage links should be expanded on this page.
2260 * @return bool
2261 */
2262 function areSubpagesAllowed() {
2263 # Some namespaces don't allow subpages
2264 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2265 }
2266
2267 /**
2268 * Handle link to subpage if necessary
2269 *
2270 * @param string $target The source of the link
2271 * @param string &$text The link text, modified as necessary
2272 * @return string The full name of the link
2273 * @private
2274 */
2275 function maybeDoSubpageLink( $target, &$text ) {
2276 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2277 }
2278
2279 /**#@+
2280 * Used by doBlockLevels()
2281 * @private
2282 *
2283 * @return string
2284 */
2285 function closeParagraph() {
2286 $result = '';
2287 if ( $this->mLastSection != '' ) {
2288 $result = '</' . $this->mLastSection . ">\n";
2289 }
2290 $this->mInPre = false;
2291 $this->mLastSection = '';
2292 return $result;
2293 }
2294
2295 /**
2296 * getCommon() returns the length of the longest common substring
2297 * of both arguments, starting at the beginning of both.
2298 * @private
2299 *
2300 * @param string $st1
2301 * @param string $st2
2302 *
2303 * @return int
2304 */
2305 function getCommon( $st1, $st2 ) {
2306 $fl = strlen( $st1 );
2307 $shorter = strlen( $st2 );
2308 if ( $fl < $shorter ) {
2309 $shorter = $fl;
2310 }
2311
2312 for ( $i = 0; $i < $shorter; ++$i ) {
2313 if ( $st1[$i] != $st2[$i] ) {
2314 break;
2315 }
2316 }
2317 return $i;
2318 }
2319
2320 /**
2321 * These next three functions open, continue, and close the list
2322 * element appropriate to the prefix character passed into them.
2323 * @private
2324 *
2325 * @param string $char
2326 *
2327 * @return string
2328 */
2329 function openList( $char ) {
2330 $result = $this->closeParagraph();
2331
2332 if ( '*' === $char ) {
2333 $result .= "<ul><li>";
2334 } elseif ( '#' === $char ) {
2335 $result .= "<ol><li>";
2336 } elseif ( ':' === $char ) {
2337 $result .= "<dl><dd>";
2338 } elseif ( ';' === $char ) {
2339 $result .= "<dl><dt>";
2340 $this->mDTopen = true;
2341 } else {
2342 $result = '<!-- ERR 1 -->';
2343 }
2344
2345 return $result;
2346 }
2347
2348 /**
2349 * TODO: document
2350 * @param string $char
2351 * @private
2352 *
2353 * @return string
2354 */
2355 function nextItem( $char ) {
2356 if ( '*' === $char || '#' === $char ) {
2357 return "</li>\n<li>";
2358 } elseif ( ':' === $char || ';' === $char ) {
2359 $close = "</dd>\n";
2360 if ( $this->mDTopen ) {
2361 $close = "</dt>\n";
2362 }
2363 if ( ';' === $char ) {
2364 $this->mDTopen = true;
2365 return $close . '<dt>';
2366 } else {
2367 $this->mDTopen = false;
2368 return $close . '<dd>';
2369 }
2370 }
2371 return '<!-- ERR 2 -->';
2372 }
2373
2374 /**
2375 * @todo Document
2376 * @param string $char
2377 * @private
2378 *
2379 * @return string
2380 */
2381 function closeList( $char ) {
2382 if ( '*' === $char ) {
2383 $text = "</li></ul>";
2384 } elseif ( '#' === $char ) {
2385 $text = "</li></ol>";
2386 } elseif ( ':' === $char ) {
2387 if ( $this->mDTopen ) {
2388 $this->mDTopen = false;
2389 $text = "</dt></dl>";
2390 } else {
2391 $text = "</dd></dl>";
2392 }
2393 } else {
2394 return '<!-- ERR 3 -->';
2395 }
2396 return $text;
2397 }
2398 /**#@-*/
2399
2400 /**
2401 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2402 *
2403 * @param string $text
2404 * @param bool $linestart Whether or not this is at the start of a line.
2405 * @private
2406 * @return string The lists rendered as HTML
2407 */
2408 function doBlockLevels( $text, $linestart ) {
2409 wfProfileIn( __METHOD__ );
2410
2411 # Parsing through the text line by line. The main thing
2412 # happening here is handling of block-level elements p, pre,
2413 # and making lists from lines starting with * # : etc.
2414 #
2415 $textLines = StringUtils::explode( "\n", $text );
2416
2417 $lastPrefix = $output = '';
2418 $this->mDTopen = $inBlockElem = false;
2419 $prefixLength = 0;
2420 $paragraphStack = false;
2421 $inBlockquote = false;
2422
2423 foreach ( $textLines as $oLine ) {
2424 # Fix up $linestart
2425 if ( !$linestart ) {
2426 $output .= $oLine;
2427 $linestart = true;
2428 continue;
2429 }
2430 # * = ul
2431 # # = ol
2432 # ; = dt
2433 # : = dd
2434
2435 $lastPrefixLength = strlen( $lastPrefix );
2436 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2437 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2438 # If not in a <pre> element, scan for and figure out what prefixes are there.
2439 if ( !$this->mInPre ) {
2440 # Multiple prefixes may abut each other for nested lists.
2441 $prefixLength = strspn( $oLine, '*#:;' );
2442 $prefix = substr( $oLine, 0, $prefixLength );
2443
2444 # eh?
2445 # ; and : are both from definition-lists, so they're equivalent
2446 # for the purposes of determining whether or not we need to open/close
2447 # elements.
2448 $prefix2 = str_replace( ';', ':', $prefix );
2449 $t = substr( $oLine, $prefixLength );
2450 $this->mInPre = (bool)$preOpenMatch;
2451 } else {
2452 # Don't interpret any other prefixes in preformatted text
2453 $prefixLength = 0;
2454 $prefix = $prefix2 = '';
2455 $t = $oLine;
2456 }
2457
2458 # List generation
2459 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2460 # Same as the last item, so no need to deal with nesting or opening stuff
2461 $output .= $this->nextItem( substr( $prefix, -1 ) );
2462 $paragraphStack = false;
2463
2464 if ( substr( $prefix, -1 ) === ';' ) {
2465 # The one nasty exception: definition lists work like this:
2466 # ; title : definition text
2467 # So we check for : in the remainder text to split up the
2468 # title and definition, without b0rking links.
2469 $term = $t2 = '';
2470 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2471 $t = $t2;
2472 $output .= $term . $this->nextItem( ':' );
2473 }
2474 }
2475 } elseif ( $prefixLength || $lastPrefixLength ) {
2476 # We need to open or close prefixes, or both.
2477
2478 # Either open or close a level...
2479 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2480 $paragraphStack = false;
2481
2482 # Close all the prefixes which aren't shared.
2483 while ( $commonPrefixLength < $lastPrefixLength ) {
2484 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2485 --$lastPrefixLength;
2486 }
2487
2488 # Continue the current prefix if appropriate.
2489 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2490 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2491 }
2492
2493 # Open prefixes where appropriate.
2494 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2495 $output .= "\n";
2496 }
2497 while ( $prefixLength > $commonPrefixLength ) {
2498 $char = substr( $prefix, $commonPrefixLength, 1 );
2499 $output .= $this->openList( $char );
2500
2501 if ( ';' === $char ) {
2502 # @todo FIXME: This is dupe of code above
2503 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2504 $t = $t2;
2505 $output .= $term . $this->nextItem( ':' );
2506 }
2507 }
2508 ++$commonPrefixLength;
2509 }
2510 if ( !$prefixLength && $lastPrefix ) {
2511 $output .= "\n";
2512 }
2513 $lastPrefix = $prefix2;
2514 }
2515
2516 # If we have no prefixes, go to paragraph mode.
2517 if ( 0 == $prefixLength ) {
2518 wfProfileIn( __METHOD__ . "-paragraph" );
2519 # No prefix (not in list)--go to paragraph mode
2520 # XXX: use a stack for nestable elements like span, table and div
2521 $openmatch = preg_match(
2522 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2523 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2524 $t
2525 );
2526 $closematch = preg_match(
2527 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2528 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2529 . $this->mUniqPrefix
2530 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2531 $t
2532 );
2533
2534 if ( $openmatch or $closematch ) {
2535 $paragraphStack = false;
2536 # @todo bug 5718: paragraph closed
2537 $output .= $this->closeParagraph();
2538 if ( $preOpenMatch and !$preCloseMatch ) {
2539 $this->mInPre = true;
2540 }
2541 $bqOffset = 0;
2542 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE, $bqOffset ) ) {
2543 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2544 $bqOffset = $bqMatch[0][1] + strlen( $bqMatch[0][0] );
2545 }
2546 $inBlockElem = !$closematch;
2547 } elseif ( !$inBlockElem && !$this->mInPre ) {
2548 if ( ' ' == substr( $t, 0, 1 )
2549 && ( $this->mLastSection === 'pre' || trim( $t ) != '' )
2550 && !$inBlockquote
2551 ) {
2552 # pre
2553 if ( $this->mLastSection !== 'pre' ) {
2554 $paragraphStack = false;
2555 $output .= $this->closeParagraph() . '<pre>';
2556 $this->mLastSection = 'pre';
2557 }
2558 $t = substr( $t, 1 );
2559 } else {
2560 # paragraph
2561 if ( trim( $t ) === '' ) {
2562 if ( $paragraphStack ) {
2563 $output .= $paragraphStack . '<br />';
2564 $paragraphStack = false;
2565 $this->mLastSection = 'p';
2566 } else {
2567 if ( $this->mLastSection !== 'p' ) {
2568 $output .= $this->closeParagraph();
2569 $this->mLastSection = '';
2570 $paragraphStack = '<p>';
2571 } else {
2572 $paragraphStack = '</p><p>';
2573 }
2574 }
2575 } else {
2576 if ( $paragraphStack ) {
2577 $output .= $paragraphStack;
2578 $paragraphStack = false;
2579 $this->mLastSection = 'p';
2580 } elseif ( $this->mLastSection !== 'p' ) {
2581 $output .= $this->closeParagraph() . '<p>';
2582 $this->mLastSection = 'p';
2583 }
2584 }
2585 }
2586 }
2587 wfProfileOut( __METHOD__ . "-paragraph" );
2588 }
2589 # somewhere above we forget to get out of pre block (bug 785)
2590 if ( $preCloseMatch && $this->mInPre ) {
2591 $this->mInPre = false;
2592 }
2593 if ( $paragraphStack === false ) {
2594 $output .= $t;
2595 if ( $prefixLength === 0 ) {
2596 $output .= "\n";
2597 }
2598 }
2599 }
2600 while ( $prefixLength ) {
2601 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2602 --$prefixLength;
2603 if ( !$prefixLength ) {
2604 $output .= "\n";
2605 }
2606 }
2607 if ( $this->mLastSection != '' ) {
2608 $output .= '</' . $this->mLastSection . '>';
2609 $this->mLastSection = '';
2610 }
2611
2612 wfProfileOut( __METHOD__ );
2613 return $output;
2614 }
2615
2616 /**
2617 * Split up a string on ':', ignoring any occurrences inside tags
2618 * to prevent illegal overlapping.
2619 *
2620 * @param string $str The string to split
2621 * @param string &$before Set to everything before the ':'
2622 * @param string &$after Set to everything after the ':'
2623 * @throws MWException
2624 * @return string The position of the ':', or false if none found
2625 */
2626 function findColonNoLinks( $str, &$before, &$after ) {
2627 wfProfileIn( __METHOD__ );
2628
2629 $pos = strpos( $str, ':' );
2630 if ( $pos === false ) {
2631 # Nothing to find!
2632 wfProfileOut( __METHOD__ );
2633 return false;
2634 }
2635
2636 $lt = strpos( $str, '<' );
2637 if ( $lt === false || $lt > $pos ) {
2638 # Easy; no tag nesting to worry about
2639 $before = substr( $str, 0, $pos );
2640 $after = substr( $str, $pos + 1 );
2641 wfProfileOut( __METHOD__ );
2642 return $pos;
2643 }
2644
2645 # Ugly state machine to walk through avoiding tags.
2646 $state = self::COLON_STATE_TEXT;
2647 $stack = 0;
2648 $len = strlen( $str );
2649 for ( $i = 0; $i < $len; $i++ ) {
2650 $c = $str[$i];
2651
2652 switch ( $state ) {
2653 # (Using the number is a performance hack for common cases)
2654 case 0: # self::COLON_STATE_TEXT:
2655 switch ( $c ) {
2656 case "<":
2657 # Could be either a <start> tag or an </end> tag
2658 $state = self::COLON_STATE_TAGSTART;
2659 break;
2660 case ":":
2661 if ( $stack == 0 ) {
2662 # We found it!
2663 $before = substr( $str, 0, $i );
2664 $after = substr( $str, $i + 1 );
2665 wfProfileOut( __METHOD__ );
2666 return $i;
2667 }
2668 # Embedded in a tag; don't break it.
2669 break;
2670 default:
2671 # Skip ahead looking for something interesting
2672 $colon = strpos( $str, ':', $i );
2673 if ( $colon === false ) {
2674 # Nothing else interesting
2675 wfProfileOut( __METHOD__ );
2676 return false;
2677 }
2678 $lt = strpos( $str, '<', $i );
2679 if ( $stack === 0 ) {
2680 if ( $lt === false || $colon < $lt ) {
2681 # We found it!
2682 $before = substr( $str, 0, $colon );
2683 $after = substr( $str, $colon + 1 );
2684 wfProfileOut( __METHOD__ );
2685 return $i;
2686 }
2687 }
2688 if ( $lt === false ) {
2689 # Nothing else interesting to find; abort!
2690 # We're nested, but there's no close tags left. Abort!
2691 break 2;
2692 }
2693 # Skip ahead to next tag start
2694 $i = $lt;
2695 $state = self::COLON_STATE_TAGSTART;
2696 }
2697 break;
2698 case 1: # self::COLON_STATE_TAG:
2699 # In a <tag>
2700 switch ( $c ) {
2701 case ">":
2702 $stack++;
2703 $state = self::COLON_STATE_TEXT;
2704 break;
2705 case "/":
2706 # Slash may be followed by >?
2707 $state = self::COLON_STATE_TAGSLASH;
2708 break;
2709 default:
2710 # ignore
2711 }
2712 break;
2713 case 2: # self::COLON_STATE_TAGSTART:
2714 switch ( $c ) {
2715 case "/":
2716 $state = self::COLON_STATE_CLOSETAG;
2717 break;
2718 case "!":
2719 $state = self::COLON_STATE_COMMENT;
2720 break;
2721 case ">":
2722 # Illegal early close? This shouldn't happen D:
2723 $state = self::COLON_STATE_TEXT;
2724 break;
2725 default:
2726 $state = self::COLON_STATE_TAG;
2727 }
2728 break;
2729 case 3: # self::COLON_STATE_CLOSETAG:
2730 # In a </tag>
2731 if ( $c === ">" ) {
2732 $stack--;
2733 if ( $stack < 0 ) {
2734 wfDebug( __METHOD__ . ": Invalid input; too many close tags\n" );
2735 wfProfileOut( __METHOD__ );
2736 return false;
2737 }
2738 $state = self::COLON_STATE_TEXT;
2739 }
2740 break;
2741 case self::COLON_STATE_TAGSLASH:
2742 if ( $c === ">" ) {
2743 # Yes, a self-closed tag <blah/>
2744 $state = self::COLON_STATE_TEXT;
2745 } else {
2746 # Probably we're jumping the gun, and this is an attribute
2747 $state = self::COLON_STATE_TAG;
2748 }
2749 break;
2750 case 5: # self::COLON_STATE_COMMENT:
2751 if ( $c === "-" ) {
2752 $state = self::COLON_STATE_COMMENTDASH;
2753 }
2754 break;
2755 case self::COLON_STATE_COMMENTDASH:
2756 if ( $c === "-" ) {
2757 $state = self::COLON_STATE_COMMENTDASHDASH;
2758 } else {
2759 $state = self::COLON_STATE_COMMENT;
2760 }
2761 break;
2762 case self::COLON_STATE_COMMENTDASHDASH:
2763 if ( $c === ">" ) {
2764 $state = self::COLON_STATE_TEXT;
2765 } else {
2766 $state = self::COLON_STATE_COMMENT;
2767 }
2768 break;
2769 default:
2770 wfProfileOut( __METHOD__ );
2771 throw new MWException( "State machine error in " . __METHOD__ );
2772 }
2773 }
2774 if ( $stack > 0 ) {
2775 wfDebug( __METHOD__ . ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2776 wfProfileOut( __METHOD__ );
2777 return false;
2778 }
2779 wfProfileOut( __METHOD__ );
2780 return false;
2781 }
2782
2783 /**
2784 * Return value of a magic variable (like PAGENAME)
2785 *
2786 * @private
2787 *
2788 * @param int $index
2789 * @param bool|PPFrame $frame
2790 *
2791 * @throws MWException
2792 * @return string
2793 */
2794 function getVariableValue( $index, $frame = false ) {
2795 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2796 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2797
2798 if ( is_null( $this->mTitle ) ) {
2799 // If no title set, bad things are going to happen
2800 // later. Title should always be set since this
2801 // should only be called in the middle of a parse
2802 // operation (but the unit-tests do funky stuff)
2803 throw new MWException( __METHOD__ . ' Should only be '
2804 . ' called while parsing (no title set)' );
2805 }
2806
2807 /**
2808 * Some of these require message or data lookups and can be
2809 * expensive to check many times.
2810 */
2811 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2812 if ( isset( $this->mVarCache[$index] ) ) {
2813 return $this->mVarCache[$index];
2814 }
2815 }
2816
2817 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2818 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2819
2820 $pageLang = $this->getFunctionLang();
2821
2822 switch ( $index ) {
2823 case 'currentmonth':
2824 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'm' ) );
2825 break;
2826 case 'currentmonth1':
2827 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2828 break;
2829 case 'currentmonthname':
2830 $value = $pageLang->getMonthName( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2831 break;
2832 case 'currentmonthnamegen':
2833 $value = $pageLang->getMonthNameGen( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2834 break;
2835 case 'currentmonthabbrev':
2836 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getInstance( $ts )->format( 'n' ) );
2837 break;
2838 case 'currentday':
2839 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'j' ) );
2840 break;
2841 case 'currentday2':
2842 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'd' ) );
2843 break;
2844 case 'localmonth':
2845 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'm' ) );
2846 break;
2847 case 'localmonth1':
2848 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2849 break;
2850 case 'localmonthname':
2851 $value = $pageLang->getMonthName( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2852 break;
2853 case 'localmonthnamegen':
2854 $value = $pageLang->getMonthNameGen( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2855 break;
2856 case 'localmonthabbrev':
2857 $value = $pageLang->getMonthAbbreviation( MWTimestamp::getLocalInstance( $ts )->format( 'n' ) );
2858 break;
2859 case 'localday':
2860 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'j' ) );
2861 break;
2862 case 'localday2':
2863 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'd' ) );
2864 break;
2865 case 'pagename':
2866 $value = wfEscapeWikiText( $this->mTitle->getText() );
2867 break;
2868 case 'pagenamee':
2869 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2870 break;
2871 case 'fullpagename':
2872 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2873 break;
2874 case 'fullpagenamee':
2875 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2876 break;
2877 case 'subpagename':
2878 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2879 break;
2880 case 'subpagenamee':
2881 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2882 break;
2883 case 'rootpagename':
2884 $value = wfEscapeWikiText( $this->mTitle->getRootText() );
2885 break;
2886 case 'rootpagenamee':
2887 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2888 ' ',
2889 '_',
2890 $this->mTitle->getRootText()
2891 ) ) );
2892 break;
2893 case 'basepagename':
2894 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2895 break;
2896 case 'basepagenamee':
2897 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2898 ' ',
2899 '_',
2900 $this->mTitle->getBaseText()
2901 ) ) );
2902 break;
2903 case 'talkpagename':
2904 if ( $this->mTitle->canTalk() ) {
2905 $talkPage = $this->mTitle->getTalkPage();
2906 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2907 } else {
2908 $value = '';
2909 }
2910 break;
2911 case 'talkpagenamee':
2912 if ( $this->mTitle->canTalk() ) {
2913 $talkPage = $this->mTitle->getTalkPage();
2914 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2915 } else {
2916 $value = '';
2917 }
2918 break;
2919 case 'subjectpagename':
2920 $subjPage = $this->mTitle->getSubjectPage();
2921 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2922 break;
2923 case 'subjectpagenamee':
2924 $subjPage = $this->mTitle->getSubjectPage();
2925 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2926 break;
2927 case 'pageid': // requested in bug 23427
2928 $pageid = $this->getTitle()->getArticleID();
2929 if ( $pageid == 0 ) {
2930 # 0 means the page doesn't exist in the database,
2931 # which means the user is previewing a new page.
2932 # The vary-revision flag must be set, because the magic word
2933 # will have a different value once the page is saved.
2934 $this->mOutput->setFlag( 'vary-revision' );
2935 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2936 }
2937 $value = $pageid ? $pageid : null;
2938 break;
2939 case 'revisionid':
2940 # Let the edit saving system know we should parse the page
2941 # *after* a revision ID has been assigned.
2942 $this->mOutput->setFlag( 'vary-revision' );
2943 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2944 $value = $this->mRevisionId;
2945 break;
2946 case 'revisionday':
2947 # Let the edit saving system know we should parse the page
2948 # *after* a revision ID has been assigned. This is for null edits.
2949 $this->mOutput->setFlag( 'vary-revision' );
2950 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2951 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2952 break;
2953 case 'revisionday2':
2954 # Let the edit saving system know we should parse the page
2955 # *after* a revision ID has been assigned. This is for null edits.
2956 $this->mOutput->setFlag( 'vary-revision' );
2957 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2958 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2959 break;
2960 case 'revisionmonth':
2961 # Let the edit saving system know we should parse the page
2962 # *after* a revision ID has been assigned. This is for null edits.
2963 $this->mOutput->setFlag( 'vary-revision' );
2964 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2965 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2966 break;
2967 case 'revisionmonth1':
2968 # Let the edit saving system know we should parse the page
2969 # *after* a revision ID has been assigned. This is for null edits.
2970 $this->mOutput->setFlag( 'vary-revision' );
2971 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2972 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2973 break;
2974 case 'revisionyear':
2975 # Let the edit saving system know we should parse the page
2976 # *after* a revision ID has been assigned. This is for null edits.
2977 $this->mOutput->setFlag( 'vary-revision' );
2978 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2979 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2980 break;
2981 case 'revisiontimestamp':
2982 # Let the edit saving system know we should parse the page
2983 # *after* a revision ID has been assigned. This is for null edits.
2984 $this->mOutput->setFlag( 'vary-revision' );
2985 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2986 $value = $this->getRevisionTimestamp();
2987 break;
2988 case 'revisionuser':
2989 # Let the edit saving system know we should parse the page
2990 # *after* a revision ID has been assigned. This is for null edits.
2991 $this->mOutput->setFlag( 'vary-revision' );
2992 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2993 $value = $this->getRevisionUser();
2994 break;
2995 case 'revisionsize':
2996 # Let the edit saving system know we should parse the page
2997 # *after* a revision ID has been assigned. This is for null edits.
2998 $this->mOutput->setFlag( 'vary-revision' );
2999 wfDebug( __METHOD__ . ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3000 $value = $this->getRevisionSize();
3001 break;
3002 case 'namespace':
3003 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
3004 break;
3005 case 'namespacee':
3006 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
3007 break;
3008 case 'namespacenumber':
3009 $value = $this->mTitle->getNamespace();
3010 break;
3011 case 'talkspace':
3012 $value = $this->mTitle->canTalk()
3013 ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() )
3014 : '';
3015 break;
3016 case 'talkspacee':
3017 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
3018 break;
3019 case 'subjectspace':
3020 $value = str_replace( '_', ' ', $this->mTitle->getSubjectNsText() );
3021 break;
3022 case 'subjectspacee':
3023 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
3024 break;
3025 case 'currentdayname':
3026 $value = $pageLang->getWeekdayName( (int)MWTimestamp::getInstance( $ts )->format( 'w' ) + 1 );
3027 break;
3028 case 'currentyear':
3029 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'Y' ), true );
3030 break;
3031 case 'currenttime':
3032 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
3033 break;
3034 case 'currenthour':
3035 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'H' ), true );
3036 break;
3037 case 'currentweek':
3038 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3039 # int to remove the padding
3040 $value = $pageLang->formatNum( (int)MWTimestamp::getInstance( $ts )->format( 'W' ) );
3041 break;
3042 case 'currentdow':
3043 $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) );
3044 break;
3045 case 'localdayname':
3046 $value = $pageLang->getWeekdayName(
3047 (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1
3048 );
3049 break;
3050 case 'localyear':
3051 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true );
3052 break;
3053 case 'localtime':
3054 $value = $pageLang->time(
3055 MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ),
3056 false,
3057 false
3058 );
3059 break;
3060 case 'localhour':
3061 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true );
3062 break;
3063 case 'localweek':
3064 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3065 # int to remove the padding
3066 $value = $pageLang->formatNum( (int)MWTimestamp::getLocalInstance( $ts )->format( 'W' ) );
3067 break;
3068 case 'localdow':
3069 $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'w' ) );
3070 break;
3071 case 'numberofarticles':
3072 $value = $pageLang->formatNum( SiteStats::articles() );
3073 break;
3074 case 'numberoffiles':
3075 $value = $pageLang->formatNum( SiteStats::images() );
3076 break;
3077 case 'numberofusers':
3078 $value = $pageLang->formatNum( SiteStats::users() );
3079 break;
3080 case 'numberofactiveusers':
3081 $value = $pageLang->formatNum( SiteStats::activeUsers() );
3082 break;
3083 case 'numberofpages':
3084 $value = $pageLang->formatNum( SiteStats::pages() );
3085 break;
3086 case 'numberofadmins':
3087 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
3088 break;
3089 case 'numberofedits':
3090 $value = $pageLang->formatNum( SiteStats::edits() );
3091 break;
3092 case 'numberofviews':
3093 global $wgDisableCounters;
3094 $value = !$wgDisableCounters ? $pageLang->formatNum( SiteStats::views() ) : '';
3095 break;
3096 case 'currenttimestamp':
3097 $value = wfTimestamp( TS_MW, $ts );
3098 break;
3099 case 'localtimestamp':
3100 $value = MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' );
3101 break;
3102 case 'currentversion':
3103 $value = SpecialVersion::getVersion();
3104 break;
3105 case 'articlepath':
3106 return $wgArticlePath;
3107 case 'sitename':
3108 return $wgSitename;
3109 case 'server':
3110 return $wgServer;
3111 case 'servername':
3112 return $wgServerName;
3113 case 'scriptpath':
3114 return $wgScriptPath;
3115 case 'stylepath':
3116 return $wgStylePath;
3117 case 'directionmark':
3118 return $pageLang->getDirMark();
3119 case 'contentlanguage':
3120 global $wgLanguageCode;
3121 return $wgLanguageCode;
3122 case 'cascadingsources':
3123 $value = CoreParserFunctions::cascadingsources( $this );
3124 break;
3125 default:
3126 $ret = null;
3127 wfRunHooks(
3128 'ParserGetVariableValueSwitch',
3129 array( &$this, &$this->mVarCache, &$index, &$ret, &$frame )
3130 );
3131
3132 return $ret;
3133 }
3134
3135 if ( $index ) {
3136 $this->mVarCache[$index] = $value;
3137 }
3138
3139 return $value;
3140 }
3141
3142 /**
3143 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3144 *
3145 * @private
3146 */
3147 function initialiseVariables() {
3148 wfProfileIn( __METHOD__ );
3149 $variableIDs = MagicWord::getVariableIDs();
3150 $substIDs = MagicWord::getSubstIDs();
3151
3152 $this->mVariables = new MagicWordArray( $variableIDs );
3153 $this->mSubstWords = new MagicWordArray( $substIDs );
3154 wfProfileOut( __METHOD__ );
3155 }
3156
3157 /**
3158 * Preprocess some wikitext and return the document tree.
3159 * This is the ghost of replace_variables().
3160 *
3161 * @param string $text The text to parse
3162 * @param int $flags Bitwise combination of:
3163 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3164 * included. Default is to assume a direct page view.
3165 *
3166 * The generated DOM tree must depend only on the input text and the flags.
3167 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3168 *
3169 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3170 * change in the DOM tree for a given text, must be passed through the section identifier
3171 * in the section edit link and thus back to extractSections().
3172 *
3173 * The output of this function is currently only cached in process memory, but a persistent
3174 * cache may be implemented at a later date which takes further advantage of these strict
3175 * dependency requirements.
3176 *
3177 * @return PPNode
3178 */
3179 function preprocessToDom( $text, $flags = 0 ) {
3180 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3181 return $dom;
3182 }
3183
3184 /**
3185 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3186 *
3187 * @param string $s
3188 *
3189 * @return array
3190 */
3191 public static function splitWhitespace( $s ) {
3192 $ltrimmed = ltrim( $s );
3193 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3194 $trimmed = rtrim( $ltrimmed );
3195 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3196 if ( $diff > 0 ) {
3197 $w2 = substr( $ltrimmed, -$diff );
3198 } else {
3199 $w2 = '';
3200 }
3201 return array( $w1, $trimmed, $w2 );
3202 }
3203
3204 /**
3205 * Replace magic variables, templates, and template arguments
3206 * with the appropriate text. Templates are substituted recursively,
3207 * taking care to avoid infinite loops.
3208 *
3209 * Note that the substitution depends on value of $mOutputType:
3210 * self::OT_WIKI: only {{subst:}} templates
3211 * self::OT_PREPROCESS: templates but not extension tags
3212 * self::OT_HTML: all templates and extension tags
3213 *
3214 * @param string $text The text to transform
3215 * @param bool|PPFrame $frame Object describing the arguments passed to the
3216 * template. Arguments may also be provided as an associative array, as
3217 * was the usual case before MW1.12. Providing arguments this way may be
3218 * useful for extensions wishing to perform variable replacement
3219 * explicitly.
3220 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3221 * double-brace expansion.
3222 * @return string
3223 */
3224 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3225 # Is there any text? Also, Prevent too big inclusions!
3226 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3227 return $text;
3228 }
3229 wfProfileIn( __METHOD__ );
3230
3231 if ( $frame === false ) {
3232 $frame = $this->getPreprocessor()->newFrame();
3233 } elseif ( !( $frame instanceof PPFrame ) ) {
3234 wfDebug( __METHOD__ . " called using plain parameters instead of "
3235 . "a PPFrame instance. Creating custom frame.\n" );
3236 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3237 }
3238
3239 $dom = $this->preprocessToDom( $text );
3240 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3241 $text = $frame->expand( $dom, $flags );
3242
3243 wfProfileOut( __METHOD__ );
3244 return $text;
3245 }
3246
3247 /**
3248 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3249 *
3250 * @param array $args
3251 *
3252 * @return array
3253 */
3254 static function createAssocArgs( $args ) {
3255 $assocArgs = array();
3256 $index = 1;
3257 foreach ( $args as $arg ) {
3258 $eqpos = strpos( $arg, '=' );
3259 if ( $eqpos === false ) {
3260 $assocArgs[$index++] = $arg;
3261 } else {
3262 $name = trim( substr( $arg, 0, $eqpos ) );
3263 $value = trim( substr( $arg, $eqpos + 1 ) );
3264 if ( $value === false ) {
3265 $value = '';
3266 }
3267 if ( $name !== false ) {
3268 $assocArgs[$name] = $value;
3269 }
3270 }
3271 }
3272
3273 return $assocArgs;
3274 }
3275
3276 /**
3277 * Warn the user when a parser limitation is reached
3278 * Will warn at most once the user per limitation type
3279 *
3280 * @param string $limitationType Should be one of:
3281 * 'expensive-parserfunction' (corresponding messages:
3282 * 'expensive-parserfunction-warning',
3283 * 'expensive-parserfunction-category')
3284 * 'post-expand-template-argument' (corresponding messages:
3285 * 'post-expand-template-argument-warning',
3286 * 'post-expand-template-argument-category')
3287 * 'post-expand-template-inclusion' (corresponding messages:
3288 * 'post-expand-template-inclusion-warning',
3289 * 'post-expand-template-inclusion-category')
3290 * 'node-count-exceeded' (corresponding messages:
3291 * 'node-count-exceeded-warning',
3292 * 'node-count-exceeded-category')
3293 * 'expansion-depth-exceeded' (corresponding messages:
3294 * 'expansion-depth-exceeded-warning',
3295 * 'expansion-depth-exceeded-category')
3296 * @param string|int|null $current Current value
3297 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3298 * exceeded, provide the values (optional)
3299 */
3300 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3301 # does no harm if $current and $max are present but are unnecessary for the message
3302 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3303 ->inLanguage( $this->mOptions->getUserLangObj() )->text();
3304 $this->mOutput->addWarning( $warning );
3305 $this->addTrackingCategory( "$limitationType-category" );
3306 }
3307
3308 /**
3309 * Return the text of a template, after recursively
3310 * replacing any variables or templates within the template.
3311 *
3312 * @param array $piece The parts of the template
3313 * $piece['title']: the title, i.e. the part before the |
3314 * $piece['parts']: the parameter array
3315 * $piece['lineStart']: whether the brace was at the start of a line
3316 * @param PPFrame $frame The current frame, contains template arguments
3317 * @throws Exception
3318 * @return string The text of the template
3319 */
3320 public function braceSubstitution( $piece, $frame ) {
3321 wfProfileIn( __METHOD__ );
3322 wfProfileIn( __METHOD__ . '-setup' );
3323
3324 // Flags
3325
3326 // $text has been filled
3327 $found = false;
3328 // wiki markup in $text should be escaped
3329 $nowiki = false;
3330 // $text is HTML, armour it against wikitext transformation
3331 $isHTML = false;
3332 // Force interwiki transclusion to be done in raw mode not rendered
3333 $forceRawInterwiki = false;
3334 // $text is a DOM node needing expansion in a child frame
3335 $isChildObj = false;
3336 // $text is a DOM node needing expansion in the current frame
3337 $isLocalObj = false;
3338
3339 # Title object, where $text came from
3340 $title = false;
3341
3342 # $part1 is the bit before the first |, and must contain only title characters.
3343 # Various prefixes will be stripped from it later.
3344 $titleWithSpaces = $frame->expand( $piece['title'] );
3345 $part1 = trim( $titleWithSpaces );
3346 $titleText = false;
3347
3348 # Original title text preserved for various purposes
3349 $originalTitle = $part1;
3350
3351 # $args is a list of argument nodes, starting from index 0, not including $part1
3352 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3353 # below won't work b/c this $args isn't an object
3354 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
3355 wfProfileOut( __METHOD__ . '-setup' );
3356
3357 $titleProfileIn = null; // profile templates
3358
3359 # SUBST
3360 wfProfileIn( __METHOD__ . '-modifiers' );
3361 if ( !$found ) {
3362
3363 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3364
3365 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3366 # Decide whether to expand template or keep wikitext as-is.
3367 if ( $this->ot['wiki'] ) {
3368 if ( $substMatch === false ) {
3369 $literal = true; # literal when in PST with no prefix
3370 } else {
3371 $literal = false; # expand when in PST with subst: or safesubst:
3372 }
3373 } else {
3374 if ( $substMatch == 'subst' ) {
3375 $literal = true; # literal when not in PST with plain subst:
3376 } else {
3377 $literal = false; # expand when not in PST with safesubst: or no prefix
3378 }
3379 }
3380 if ( $literal ) {
3381 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3382 $isLocalObj = true;
3383 $found = true;
3384 }
3385 }
3386
3387 # Variables
3388 if ( !$found && $args->getLength() == 0 ) {
3389 $id = $this->mVariables->matchStartToEnd( $part1 );
3390 if ( $id !== false ) {
3391 $text = $this->getVariableValue( $id, $frame );
3392 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3393 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3394 }
3395 $found = true;
3396 }
3397 }
3398
3399 # MSG, MSGNW and RAW
3400 if ( !$found ) {
3401 # Check for MSGNW:
3402 $mwMsgnw = MagicWord::get( 'msgnw' );
3403 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3404 $nowiki = true;
3405 } else {
3406 # Remove obsolete MSG:
3407 $mwMsg = MagicWord::get( 'msg' );
3408 $mwMsg->matchStartAndRemove( $part1 );
3409 }
3410
3411 # Check for RAW:
3412 $mwRaw = MagicWord::get( 'raw' );
3413 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3414 $forceRawInterwiki = true;
3415 }
3416 }
3417 wfProfileOut( __METHOD__ . '-modifiers' );
3418
3419 # Parser functions
3420 if ( !$found ) {
3421 wfProfileIn( __METHOD__ . '-pfunc' );
3422
3423 $colonPos = strpos( $part1, ':' );
3424 if ( $colonPos !== false ) {
3425 $func = substr( $part1, 0, $colonPos );
3426 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3427 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3428 $funcArgs[] = $args->item( $i );
3429 }
3430 try {
3431 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3432 } catch ( Exception $ex ) {
3433 wfProfileOut( __METHOD__ . '-pfunc' );
3434 wfProfileOut( __METHOD__ );
3435 throw $ex;
3436 }
3437
3438 # The interface for parser functions allows for extracting
3439 # flags into the local scope. Extract any forwarded flags
3440 # here.
3441 extract( $result );
3442 }
3443 wfProfileOut( __METHOD__ . '-pfunc' );
3444 }
3445
3446 # Finish mangling title and then check for loops.
3447 # Set $title to a Title object and $titleText to the PDBK
3448 if ( !$found ) {
3449 $ns = NS_TEMPLATE;
3450 # Split the title into page and subpage
3451 $subpage = '';
3452 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3453 if ( $part1 !== $relative ) {
3454 $part1 = $relative;
3455 $ns = $this->mTitle->getNamespace();
3456 }
3457 $title = Title::newFromText( $part1, $ns );
3458 if ( $title ) {
3459 $titleText = $title->getPrefixedText();
3460 # Check for language variants if the template is not found
3461 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3462 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3463 }
3464 # Do recursion depth check
3465 $limit = $this->mOptions->getMaxTemplateDepth();
3466 if ( $frame->depth >= $limit ) {
3467 $found = true;
3468 $text = '<span class="error">'
3469 . wfMessage( 'parser-template-recursion-depth-warning' )
3470 ->numParams( $limit )->inContentLanguage()->text()
3471 . '</span>';
3472 }
3473 }
3474 }
3475
3476 # Load from database
3477 if ( !$found && $title ) {
3478 if ( !Profiler::instance()->isPersistent() ) {
3479 # Too many unique items can kill profiling DBs/collectors
3480 $titleProfileIn = __METHOD__ . "-title-" . $title->getPrefixedDBkey();
3481 wfProfileIn( $titleProfileIn ); // template in
3482 }
3483 wfProfileIn( __METHOD__ . '-loadtpl' );
3484 if ( !$title->isExternal() ) {
3485 if ( $title->isSpecialPage()
3486 && $this->mOptions->getAllowSpecialInclusion()
3487 && $this->ot['html']
3488 ) {
3489 // Pass the template arguments as URL parameters.
3490 // "uselang" will have no effect since the Language object
3491 // is forced to the one defined in ParserOptions.
3492 $pageArgs = array();
3493 $argsLength = $args->getLength();
3494 for ( $i = 0; $i < $argsLength; $i++ ) {
3495 $bits = $args->item( $i )->splitArg();
3496 if ( strval( $bits['index'] ) === '' ) {
3497 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3498 $value = trim( $frame->expand( $bits['value'] ) );
3499 $pageArgs[$name] = $value;
3500 }
3501 }
3502
3503 // Create a new context to execute the special page
3504 $context = new RequestContext;
3505 $context->setTitle( $title );
3506 $context->setRequest( new FauxRequest( $pageArgs ) );
3507 $context->setUser( $this->getUser() );
3508 $context->setLanguage( $this->mOptions->getUserLangObj() );
3509 $ret = SpecialPageFactory::capturePath( $title, $context );
3510 if ( $ret ) {
3511 $text = $context->getOutput()->getHTML();
3512 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3513 $found = true;
3514 $isHTML = true;
3515 $this->disableCache();
3516 }
3517 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3518 $found = false; # access denied
3519 wfDebug( __METHOD__ . ": template inclusion denied for " .
3520 $title->getPrefixedDBkey() . "\n" );
3521 } else {
3522 list( $text, $title ) = $this->getTemplateDom( $title );
3523 if ( $text !== false ) {
3524 $found = true;
3525 $isChildObj = true;
3526 }
3527 }
3528
3529 # If the title is valid but undisplayable, make a link to it
3530 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3531 $text = "[[:$titleText]]";
3532 $found = true;
3533 }
3534 } elseif ( $title->isTrans() ) {
3535 # Interwiki transclusion
3536 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3537 $text = $this->interwikiTransclude( $title, 'render' );
3538 $isHTML = true;
3539 } else {
3540 $text = $this->interwikiTransclude( $title, 'raw' );
3541 # Preprocess it like a template
3542 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3543 $isChildObj = true;
3544 }
3545 $found = true;
3546 }
3547
3548 # Do infinite loop check
3549 # This has to be done after redirect resolution to avoid infinite loops via redirects
3550 if ( !$frame->loopCheck( $title ) ) {
3551 $found = true;
3552 $text = '<span class="error">'
3553 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3554 . '</span>';
3555 wfDebug( __METHOD__ . ": template loop broken at '$titleText'\n" );
3556 }
3557 wfProfileOut( __METHOD__ . '-loadtpl' );
3558 }
3559
3560 # If we haven't found text to substitute by now, we're done
3561 # Recover the source wikitext and return it
3562 if ( !$found ) {
3563 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3564 if ( $titleProfileIn ) {
3565 wfProfileOut( $titleProfileIn ); // template out
3566 }
3567 wfProfileOut( __METHOD__ );
3568 return array( 'object' => $text );
3569 }
3570
3571 # Expand DOM-style return values in a child frame
3572 if ( $isChildObj ) {
3573 # Clean up argument array
3574 $newFrame = $frame->newChild( $args, $title );
3575
3576 if ( $nowiki ) {
3577 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3578 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3579 # Expansion is eligible for the empty-frame cache
3580 $text = $newFrame->cachedExpand( $titleText, $text );
3581 } else {
3582 # Uncached expansion
3583 $text = $newFrame->expand( $text );
3584 }
3585 }
3586 if ( $isLocalObj && $nowiki ) {
3587 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3588 $isLocalObj = false;
3589 }
3590
3591 if ( $titleProfileIn ) {
3592 wfProfileOut( $titleProfileIn ); // template out
3593 }
3594
3595 # Replace raw HTML by a placeholder
3596 if ( $isHTML ) {
3597 $text = $this->insertStripItem( $text );
3598 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3599 # Escape nowiki-style return values
3600 $text = wfEscapeWikiText( $text );
3601 } elseif ( is_string( $text )
3602 && !$piece['lineStart']
3603 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3604 ) {
3605 # Bug 529: if the template begins with a table or block-level
3606 # element, it should be treated as beginning a new line.
3607 # This behavior is somewhat controversial.
3608 $text = "\n" . $text;
3609 }
3610
3611 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3612 # Error, oversize inclusion
3613 if ( $titleText !== false ) {
3614 # Make a working, properly escaped link if possible (bug 23588)
3615 $text = "[[:$titleText]]";
3616 } else {
3617 # This will probably not be a working link, but at least it may
3618 # provide some hint of where the problem is
3619 preg_replace( '/^:/', '', $originalTitle );
3620 $text = "[[:$originalTitle]]";
3621 }
3622 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3623 . 'post-expand include size too large -->' );
3624 $this->limitationWarn( 'post-expand-template-inclusion' );
3625 }
3626
3627 if ( $isLocalObj ) {
3628 $ret = array( 'object' => $text );
3629 } else {
3630 $ret = array( 'text' => $text );
3631 }
3632
3633 wfProfileOut( __METHOD__ );
3634 return $ret;
3635 }
3636
3637 /**
3638 * Call a parser function and return an array with text and flags.
3639 *
3640 * The returned array will always contain a boolean 'found', indicating
3641 * whether the parser function was found or not. It may also contain the
3642 * following:
3643 * text: string|object, resulting wikitext or PP DOM object
3644 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3645 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3646 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3647 * nowiki: bool, wiki markup in $text should be escaped
3648 *
3649 * @since 1.21
3650 * @param PPFrame $frame The current frame, contains template arguments
3651 * @param string $function Function name
3652 * @param array $args Arguments to the function
3653 * @throws MWException
3654 * @return array
3655 */
3656 public function callParserFunction( $frame, $function, array $args = array() ) {
3657 global $wgContLang;
3658
3659 wfProfileIn( __METHOD__ );
3660
3661 # Case sensitive functions
3662 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3663 $function = $this->mFunctionSynonyms[1][$function];
3664 } else {
3665 # Case insensitive functions
3666 $function = $wgContLang->lc( $function );
3667 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3668 $function = $this->mFunctionSynonyms[0][$function];
3669 } else {
3670 wfProfileOut( __METHOD__ );
3671 return array( 'found' => false );
3672 }
3673 }
3674
3675 wfProfileIn( __METHOD__ . '-pfunc-' . $function );
3676 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3677
3678 # Workaround for PHP bug 35229 and similar
3679 if ( !is_callable( $callback ) ) {
3680 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3681 wfProfileOut( __METHOD__ );
3682 throw new MWException( "Tag hook for $function is not callable\n" );
3683 }
3684
3685 $allArgs = array( &$this );
3686 if ( $flags & SFH_OBJECT_ARGS ) {
3687 # Convert arguments to PPNodes and collect for appending to $allArgs
3688 $funcArgs = array();
3689 foreach ( $args as $k => $v ) {
3690 if ( $v instanceof PPNode || $k === 0 ) {
3691 $funcArgs[] = $v;
3692 } else {
3693 $funcArgs[] = $this->mPreprocessor->newPartNodeArray( array( $k => $v ) )->item( 0 );
3694 }
3695 }
3696
3697 # Add a frame parameter, and pass the arguments as an array
3698 $allArgs[] = $frame;
3699 $allArgs[] = $funcArgs;
3700 } else {
3701 # Convert arguments to plain text and append to $allArgs
3702 foreach ( $args as $k => $v ) {
3703 if ( $v instanceof PPNode ) {
3704 $allArgs[] = trim( $frame->expand( $v ) );
3705 } elseif ( is_int( $k ) && $k >= 0 ) {
3706 $allArgs[] = trim( $v );
3707 } else {
3708 $allArgs[] = trim( "$k=$v" );
3709 }
3710 }
3711 }
3712
3713 $result = call_user_func_array( $callback, $allArgs );
3714
3715 # The interface for function hooks allows them to return a wikitext
3716 # string or an array containing the string and any flags. This mungs
3717 # things around to match what this method should return.
3718 if ( !is_array( $result ) ) {
3719 $result = array(
3720 'found' => true,
3721 'text' => $result,
3722 );
3723 } else {
3724 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3725 $result['text'] = $result[0];
3726 }
3727 unset( $result[0] );
3728 $result += array(
3729 'found' => true,
3730 );
3731 }
3732
3733 $noparse = true;
3734 $preprocessFlags = 0;
3735 if ( isset( $result['noparse'] ) ) {
3736 $noparse = $result['noparse'];
3737 }
3738 if ( isset( $result['preprocessFlags'] ) ) {
3739 $preprocessFlags = $result['preprocessFlags'];
3740 }
3741
3742 if ( !$noparse ) {
3743 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3744 $result['isChildObj'] = true;
3745 }
3746 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3747 wfProfileOut( __METHOD__ );
3748
3749 return $result;
3750 }
3751
3752 /**
3753 * Get the semi-parsed DOM representation of a template with a given title,
3754 * and its redirect destination title. Cached.
3755 *
3756 * @param Title $title
3757 *
3758 * @return array
3759 */
3760 function getTemplateDom( $title ) {
3761 $cacheTitle = $title;
3762 $titleText = $title->getPrefixedDBkey();
3763
3764 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3765 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3766 $title = Title::makeTitle( $ns, $dbk );
3767 $titleText = $title->getPrefixedDBkey();
3768 }
3769 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3770 return array( $this->mTplDomCache[$titleText], $title );
3771 }
3772
3773 # Cache miss, go to the database
3774 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3775
3776 if ( $text === false ) {
3777 $this->mTplDomCache[$titleText] = false;
3778 return array( false, $title );
3779 }
3780
3781 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3782 $this->mTplDomCache[$titleText] = $dom;
3783
3784 if ( !$title->equals( $cacheTitle ) ) {
3785 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3786 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3787 }
3788
3789 return array( $dom, $title );
3790 }
3791
3792 /**
3793 * Fetch the unparsed text of a template and register a reference to it.
3794 * @param Title $title
3795 * @return array ( string or false, Title )
3796 */
3797 function fetchTemplateAndTitle( $title ) {
3798 // Defaults to Parser::statelessFetchTemplate()
3799 $templateCb = $this->mOptions->getTemplateCallback();
3800 $stuff = call_user_func( $templateCb, $title, $this );
3801 $text = $stuff['text'];
3802 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3803 if ( isset( $stuff['deps'] ) ) {
3804 foreach ( $stuff['deps'] as $dep ) {
3805 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3806 if ( $dep['title']->equals( $this->getTitle() ) ) {
3807 // If we transclude ourselves, the final result
3808 // will change based on the new version of the page
3809 $this->mOutput->setFlag( 'vary-revision' );
3810 }
3811 }
3812 }
3813 return array( $text, $finalTitle );
3814 }
3815
3816 /**
3817 * Fetch the unparsed text of a template and register a reference to it.
3818 * @param Title $title
3819 * @return string|bool
3820 */
3821 function fetchTemplate( $title ) {
3822 $rv = $this->fetchTemplateAndTitle( $title );
3823 return $rv[0];
3824 }
3825
3826 /**
3827 * Static function to get a template
3828 * Can be overridden via ParserOptions::setTemplateCallback().
3829 *
3830 * @param Title $title
3831 * @param bool|Parser $parser
3832 *
3833 * @return array
3834 */
3835 static function statelessFetchTemplate( $title, $parser = false ) {
3836 $text = $skip = false;
3837 $finalTitle = $title;
3838 $deps = array();
3839
3840 # Loop to fetch the article, with up to 1 redirect
3841 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3842 # Give extensions a chance to select the revision instead
3843 $id = false; # Assume current
3844 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3845 array( $parser, $title, &$skip, &$id ) );
3846
3847 if ( $skip ) {
3848 $text = false;
3849 $deps[] = array(
3850 'title' => $title,
3851 'page_id' => $title->getArticleID(),
3852 'rev_id' => null
3853 );
3854 break;
3855 }
3856 # Get the revision
3857 $rev = $id
3858 ? Revision::newFromId( $id )
3859 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
3860 $rev_id = $rev ? $rev->getId() : 0;
3861 # If there is no current revision, there is no page
3862 if ( $id === false && !$rev ) {
3863 $linkCache = LinkCache::singleton();
3864 $linkCache->addBadLinkObj( $title );
3865 }
3866
3867 $deps[] = array(
3868 'title' => $title,
3869 'page_id' => $title->getArticleID(),
3870 'rev_id' => $rev_id );
3871 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3872 # We fetched a rev from a different title; register it too...
3873 $deps[] = array(
3874 'title' => $rev->getTitle(),
3875 'page_id' => $rev->getPage(),
3876 'rev_id' => $rev_id );
3877 }
3878
3879 if ( $rev ) {
3880 $content = $rev->getContent();
3881 $text = $content ? $content->getWikitextForTransclusion() : null;
3882
3883 if ( $text === false || $text === null ) {
3884 $text = false;
3885 break;
3886 }
3887 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3888 global $wgContLang;
3889 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3890 if ( !$message->exists() ) {
3891 $text = false;
3892 break;
3893 }
3894 $content = $message->content();
3895 $text = $message->plain();
3896 } else {
3897 break;
3898 }
3899 if ( !$content ) {
3900 break;
3901 }
3902 # Redirect?
3903 $finalTitle = $title;
3904 $title = $content->getRedirectTarget();
3905 }
3906 return array(
3907 'text' => $text,
3908 'finalTitle' => $finalTitle,
3909 'deps' => $deps );
3910 }
3911
3912 /**
3913 * Fetch a file and its title and register a reference to it.
3914 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3915 * @param Title $title
3916 * @param array $options Array of options to RepoGroup::findFile
3917 * @return File|bool
3918 */
3919 function fetchFile( $title, $options = array() ) {
3920 $res = $this->fetchFileAndTitle( $title, $options );
3921 return $res[0];
3922 }
3923
3924 /**
3925 * Fetch a file and its title and register a reference to it.
3926 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3927 * @param Title $title
3928 * @param array $options Array of options to RepoGroup::findFile
3929 * @return array ( File or false, Title of file )
3930 */
3931 function fetchFileAndTitle( $title, $options = array() ) {
3932 $file = $this->fetchFileNoRegister( $title, $options );
3933
3934 $time = $file ? $file->getTimestamp() : false;
3935 $sha1 = $file ? $file->getSha1() : false;
3936 # Register the file as a dependency...
3937 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3938 if ( $file && !$title->equals( $file->getTitle() ) ) {
3939 # Update fetched file title
3940 $title = $file->getTitle();
3941 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3942 }
3943 return array( $file, $title );
3944 }
3945
3946 /**
3947 * Helper function for fetchFileAndTitle.
3948 *
3949 * Also useful if you need to fetch a file but not use it yet,
3950 * for example to get the file's handler.
3951 *
3952 * @param Title $title
3953 * @param array $options Array of options to RepoGroup::findFile
3954 * @return File|bool
3955 */
3956 protected function fetchFileNoRegister( $title, $options = array() ) {
3957 if ( isset( $options['broken'] ) ) {
3958 $file = false; // broken thumbnail forced by hook
3959 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3960 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3961 } else { // get by (name,timestamp)
3962 $file = wfFindFile( $title, $options );
3963 }
3964 return $file;
3965 }
3966
3967 /**
3968 * Transclude an interwiki link.
3969 *
3970 * @param Title $title
3971 * @param string $action
3972 *
3973 * @return string
3974 */
3975 function interwikiTransclude( $title, $action ) {
3976 global $wgEnableScaryTranscluding;
3977
3978 if ( !$wgEnableScaryTranscluding ) {
3979 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3980 }
3981
3982 $url = $title->getFullURL( array( 'action' => $action ) );
3983
3984 if ( strlen( $url ) > 255 ) {
3985 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3986 }
3987 return $this->fetchScaryTemplateMaybeFromCache( $url );
3988 }
3989
3990 /**
3991 * @param string $url
3992 * @return mixed|string
3993 */
3994 function fetchScaryTemplateMaybeFromCache( $url ) {
3995 global $wgTranscludeCacheExpiry;
3996 $dbr = wfGetDB( DB_SLAVE );
3997 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3998 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3999 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4000 if ( $obj ) {
4001 return $obj->tc_contents;
4002 }
4003
4004 $req = MWHttpRequest::factory( $url );
4005 $status = $req->execute(); // Status object
4006 if ( $status->isOK() ) {
4007 $text = $req->getContent();
4008 } elseif ( $req->getStatus() != 200 ) {
4009 // Though we failed to fetch the content, this status is useless.
4010 return wfMessage( 'scarytranscludefailed-httpstatus' )
4011 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4012 } else {
4013 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4014 }
4015
4016 $dbw = wfGetDB( DB_MASTER );
4017 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4018 'tc_url' => $url,
4019 'tc_time' => $dbw->timestamp( time() ),
4020 'tc_contents' => $text
4021 ) );
4022 return $text;
4023 }
4024
4025 /**
4026 * Triple brace replacement -- used for template arguments
4027 * @private
4028 *
4029 * @param array $piece
4030 * @param PPFrame $frame
4031 *
4032 * @return array
4033 */
4034 function argSubstitution( $piece, $frame ) {
4035 wfProfileIn( __METHOD__ );
4036
4037 $error = false;
4038 $parts = $piece['parts'];
4039 $nameWithSpaces = $frame->expand( $piece['title'] );
4040 $argName = trim( $nameWithSpaces );
4041 $object = false;
4042 $text = $frame->getArgument( $argName );
4043 if ( $text === false && $parts->getLength() > 0
4044 && ( $this->ot['html']
4045 || $this->ot['pre']
4046 || ( $this->ot['wiki'] && $frame->isTemplate() )
4047 )
4048 ) {
4049 # No match in frame, use the supplied default
4050 $object = $parts->item( 0 )->getChildren();
4051 }
4052 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4053 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4054 $this->limitationWarn( 'post-expand-template-argument' );
4055 }
4056
4057 if ( $text === false && $object === false ) {
4058 # No match anywhere
4059 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4060 }
4061 if ( $error !== false ) {
4062 $text .= $error;
4063 }
4064 if ( $object !== false ) {
4065 $ret = array( 'object' => $object );
4066 } else {
4067 $ret = array( 'text' => $text );
4068 }
4069
4070 wfProfileOut( __METHOD__ );
4071 return $ret;
4072 }
4073
4074 /**
4075 * Return the text to be used for a given extension tag.
4076 * This is the ghost of strip().
4077 *
4078 * @param array $params Associative array of parameters:
4079 * name PPNode for the tag name
4080 * attr PPNode for unparsed text where tag attributes are thought to be
4081 * attributes Optional associative array of parsed attributes
4082 * inner Contents of extension element
4083 * noClose Original text did not have a close tag
4084 * @param PPFrame $frame
4085 *
4086 * @throws MWException
4087 * @return string
4088 */
4089 function extensionSubstitution( $params, $frame ) {
4090 $name = $frame->expand( $params['name'] );
4091 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
4092 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
4093 $marker = "{$this->mUniqPrefix}-$name-"
4094 . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
4095
4096 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) &&
4097 ( $this->ot['html'] || $this->ot['pre'] );
4098 if ( $isFunctionTag ) {
4099 $markerType = 'none';
4100 } else {
4101 $markerType = 'general';
4102 }
4103 if ( $this->ot['html'] || $isFunctionTag ) {
4104 $name = strtolower( $name );
4105 $attributes = Sanitizer::decodeTagAttributes( $attrText );
4106 if ( isset( $params['attributes'] ) ) {
4107 $attributes = $attributes + $params['attributes'];
4108 }
4109
4110 if ( isset( $this->mTagHooks[$name] ) ) {
4111 # Workaround for PHP bug 35229 and similar
4112 if ( !is_callable( $this->mTagHooks[$name] ) ) {
4113 throw new MWException( "Tag hook for $name is not callable\n" );
4114 }
4115 $output = call_user_func_array( $this->mTagHooks[$name],
4116 array( $content, $attributes, $this, $frame ) );
4117 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
4118 list( $callback, ) = $this->mFunctionTagHooks[$name];
4119 if ( !is_callable( $callback ) ) {
4120 throw new MWException( "Tag hook for $name is not callable\n" );
4121 }
4122
4123 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4124 } else {
4125 $output = '<span class="error">Invalid tag extension name: ' .
4126 htmlspecialchars( $name ) . '</span>';
4127 }
4128
4129 if ( is_array( $output ) ) {
4130 # Extract flags to local scope (to override $markerType)
4131 $flags = $output;
4132 $output = $flags[0];
4133 unset( $flags[0] );
4134 extract( $flags );
4135 }
4136 } else {
4137 if ( is_null( $attrText ) ) {
4138 $attrText = '';
4139 }
4140 if ( isset( $params['attributes'] ) ) {
4141 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4142 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4143 htmlspecialchars( $attrValue ) . '"';
4144 }
4145 }
4146 if ( $content === null ) {
4147 $output = "<$name$attrText/>";
4148 } else {
4149 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
4150 $output = "<$name$attrText>$content$close";
4151 }
4152 }
4153
4154 if ( $markerType === 'none' ) {
4155 return $output;
4156 } elseif ( $markerType === 'nowiki' ) {
4157 $this->mStripState->addNoWiki( $marker, $output );
4158 } elseif ( $markerType === 'general' ) {
4159 $this->mStripState->addGeneral( $marker, $output );
4160 } else {
4161 throw new MWException( __METHOD__ . ': invalid marker type' );
4162 }
4163 return $marker;
4164 }
4165
4166 /**
4167 * Increment an include size counter
4168 *
4169 * @param string $type The type of expansion
4170 * @param int $size The size of the text
4171 * @return bool False if this inclusion would take it over the maximum, true otherwise
4172 */
4173 function incrementIncludeSize( $type, $size ) {
4174 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
4175 return false;
4176 } else {
4177 $this->mIncludeSizes[$type] += $size;
4178 return true;
4179 }
4180 }
4181
4182 /**
4183 * Increment the expensive function count
4184 *
4185 * @return bool False if the limit has been exceeded
4186 */
4187 function incrementExpensiveFunctionCount() {
4188 $this->mExpensiveFunctionCount++;
4189 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
4190 }
4191
4192 /**
4193 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4194 * Fills $this->mDoubleUnderscores, returns the modified text
4195 *
4196 * @param string $text
4197 *
4198 * @return string
4199 */
4200 function doDoubleUnderscore( $text ) {
4201 wfProfileIn( __METHOD__ );
4202
4203 # The position of __TOC__ needs to be recorded
4204 $mw = MagicWord::get( 'toc' );
4205 if ( $mw->match( $text ) ) {
4206 $this->mShowToc = true;
4207 $this->mForceTocPosition = true;
4208
4209 # Set a placeholder. At the end we'll fill it in with the TOC.
4210 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4211
4212 # Only keep the first one.
4213 $text = $mw->replace( '', $text );
4214 }
4215
4216 # Now match and remove the rest of them
4217 $mwa = MagicWord::getDoubleUnderscoreArray();
4218 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
4219
4220 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
4221 $this->mOutput->mNoGallery = true;
4222 }
4223 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
4224 $this->mShowToc = false;
4225 }
4226 if ( isset( $this->mDoubleUnderscores['hiddencat'] )
4227 && $this->mTitle->getNamespace() == NS_CATEGORY
4228 ) {
4229 $this->addTrackingCategory( 'hidden-category-category' );
4230 }
4231 # (bug 8068) Allow control over whether robots index a page.
4232 #
4233 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4234 # is not desirable, the last one on the page should win.
4235 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
4236 $this->mOutput->setIndexPolicy( 'noindex' );
4237 $this->addTrackingCategory( 'noindex-category' );
4238 }
4239 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
4240 $this->mOutput->setIndexPolicy( 'index' );
4241 $this->addTrackingCategory( 'index-category' );
4242 }
4243
4244 # Cache all double underscores in the database
4245 foreach ( $this->mDoubleUnderscores as $key => $val ) {
4246 $this->mOutput->setProperty( $key, '' );
4247 }
4248
4249 wfProfileOut( __METHOD__ );
4250 return $text;
4251 }
4252
4253 /**
4254 * Add a tracking category, getting the title from a system message,
4255 * or print a debug message if the title is invalid.
4256 *
4257 * Please add any message that you use with this function to
4258 * $wgTrackingCategories. That way they will be listed on
4259 * Special:TrackingCategories.
4260 *
4261 * @param string $msg Message key
4262 * @return bool Whether the addition was successful
4263 */
4264 public function addTrackingCategory( $msg ) {
4265 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) {
4266 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
4267 return false;
4268 }
4269 // Important to parse with correct title (bug 31469)
4270 $cat = wfMessage( $msg )
4271 ->title( $this->getTitle() )
4272 ->inContentLanguage()
4273 ->text();
4274
4275 # Allow tracking categories to be disabled by setting them to "-"
4276 if ( $cat === '-' ) {
4277 return false;
4278 }
4279
4280 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
4281 if ( $containerCategory ) {
4282 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4283 return true;
4284 } else {
4285 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
4286 return false;
4287 }
4288 }
4289
4290 /**
4291 * This function accomplishes several tasks:
4292 * 1) Auto-number headings if that option is enabled
4293 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4294 * 3) Add a Table of contents on the top for users who have enabled the option
4295 * 4) Auto-anchor headings
4296 *
4297 * It loops through all headlines, collects the necessary data, then splits up the
4298 * string and re-inserts the newly formatted headlines.
4299 *
4300 * @param string $text
4301 * @param string $origText Original, untouched wikitext
4302 * @param bool $isMain
4303 * @return mixed|string
4304 * @private
4305 */
4306 function formatHeadings( $text, $origText, $isMain = true ) {
4307 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4308
4309 # Inhibit editsection links if requested in the page
4310 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4311 $maybeShowEditLink = $showEditLink = false;
4312 } else {
4313 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4314 $showEditLink = $this->mOptions->getEditSection();
4315 }
4316 if ( $showEditLink ) {
4317 $this->mOutput->setEditSectionTokens( true );
4318 }
4319
4320 # Get all headlines for numbering them and adding funky stuff like [edit]
4321 # links - this is for later, but we need the number of headlines right now
4322 $matches = array();
4323 $numMatches = preg_match_all(
4324 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4325 $text,
4326 $matches
4327 );
4328
4329 # if there are fewer than 4 headlines in the article, do not show TOC
4330 # unless it's been explicitly enabled.
4331 $enoughToc = $this->mShowToc &&
4332 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4333
4334 # Allow user to stipulate that a page should have a "new section"
4335 # link added via __NEWSECTIONLINK__
4336 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4337 $this->mOutput->setNewSection( true );
4338 }
4339
4340 # Allow user to remove the "new section"
4341 # link via __NONEWSECTIONLINK__
4342 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4343 $this->mOutput->hideNewSection( true );
4344 }
4345
4346 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4347 # override above conditions and always show TOC above first header
4348 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4349 $this->mShowToc = true;
4350 $enoughToc = true;
4351 }
4352
4353 # headline counter
4354 $headlineCount = 0;
4355 $numVisible = 0;
4356
4357 # Ugh .. the TOC should have neat indentation levels which can be
4358 # passed to the skin functions. These are determined here
4359 $toc = '';
4360 $full = '';
4361 $head = array();
4362 $sublevelCount = array();
4363 $levelCount = array();
4364 $level = 0;
4365 $prevlevel = 0;
4366 $toclevel = 0;
4367 $prevtoclevel = 0;
4368 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
4369 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4370 $oldType = $this->mOutputType;
4371 $this->setOutputType( self::OT_WIKI );
4372 $frame = $this->getPreprocessor()->newFrame();
4373 $root = $this->preprocessToDom( $origText );
4374 $node = $root->getFirstChild();
4375 $byteOffset = 0;
4376 $tocraw = array();
4377 $refers = array();
4378
4379 foreach ( $matches[3] as $headline ) {
4380 $isTemplate = false;
4381 $titleText = false;
4382 $sectionIndex = false;
4383 $numbering = '';
4384 $markerMatches = array();
4385 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4386 $serial = $markerMatches[1];
4387 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4388 $isTemplate = ( $titleText != $baseTitleText );
4389 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4390 }
4391
4392 if ( $toclevel ) {
4393 $prevlevel = $level;
4394 }
4395 $level = $matches[1][$headlineCount];
4396
4397 if ( $level > $prevlevel ) {
4398 # Increase TOC level
4399 $toclevel++;
4400 $sublevelCount[$toclevel] = 0;
4401 if ( $toclevel < $wgMaxTocLevel ) {
4402 $prevtoclevel = $toclevel;
4403 $toc .= Linker::tocIndent();
4404 $numVisible++;
4405 }
4406 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4407 # Decrease TOC level, find level to jump to
4408
4409 for ( $i = $toclevel; $i > 0; $i-- ) {
4410 if ( $levelCount[$i] == $level ) {
4411 # Found last matching level
4412 $toclevel = $i;
4413 break;
4414 } elseif ( $levelCount[$i] < $level ) {
4415 # Found first matching level below current level
4416 $toclevel = $i + 1;
4417 break;
4418 }
4419 }
4420 if ( $i == 0 ) {
4421 $toclevel = 1;
4422 }
4423 if ( $toclevel < $wgMaxTocLevel ) {
4424 if ( $prevtoclevel < $wgMaxTocLevel ) {
4425 # Unindent only if the previous toc level was shown :p
4426 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4427 $prevtoclevel = $toclevel;
4428 } else {
4429 $toc .= Linker::tocLineEnd();
4430 }
4431 }
4432 } else {
4433 # No change in level, end TOC line
4434 if ( $toclevel < $wgMaxTocLevel ) {
4435 $toc .= Linker::tocLineEnd();
4436 }
4437 }
4438
4439 $levelCount[$toclevel] = $level;
4440
4441 # count number of headlines for each level
4442 $sublevelCount[$toclevel]++;
4443 $dot = 0;
4444 for ( $i = 1; $i <= $toclevel; $i++ ) {
4445 if ( !empty( $sublevelCount[$i] ) ) {
4446 if ( $dot ) {
4447 $numbering .= '.';
4448 }
4449 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4450 $dot = 1;
4451 }
4452 }
4453
4454 # The safe header is a version of the header text safe to use for links
4455
4456 # Remove link placeholders by the link text.
4457 # <!--LINK number-->
4458 # turns into
4459 # link text with suffix
4460 # Do this before unstrip since link text can contain strip markers
4461 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4462
4463 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4464 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4465
4466 # Strip out HTML (first regex removes any tag not allowed)
4467 # Allowed tags are:
4468 # * <sup> and <sub> (bug 8393)
4469 # * <i> (bug 26375)
4470 # * <b> (r105284)
4471 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4472 #
4473 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4474 # to allow setting directionality in toc items.
4475 $tocline = preg_replace(
4476 array(
4477 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4478 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4479 ),
4480 array( '', '<$1>' ),
4481 $safeHeadline
4482 );
4483 $tocline = trim( $tocline );
4484
4485 # For the anchor, strip out HTML-y stuff period
4486 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4487 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4488
4489 # Save headline for section edit hint before it's escaped
4490 $headlineHint = $safeHeadline;
4491
4492 if ( $wgExperimentalHtmlIds ) {
4493 # For reverse compatibility, provide an id that's
4494 # HTML4-compatible, like we used to.
4495 #
4496 # It may be worth noting, academically, that it's possible for
4497 # the legacy anchor to conflict with a non-legacy headline
4498 # anchor on the page. In this case likely the "correct" thing
4499 # would be to either drop the legacy anchors or make sure
4500 # they're numbered first. However, this would require people
4501 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4502 # manually, so let's not bother worrying about it.
4503 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4504 array( 'noninitial', 'legacy' ) );
4505 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4506
4507 if ( $legacyHeadline == $safeHeadline ) {
4508 # No reason to have both (in fact, we can't)
4509 $legacyHeadline = false;
4510 }
4511 } else {
4512 $legacyHeadline = false;
4513 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4514 'noninitial' );
4515 }
4516
4517 # HTML names must be case-insensitively unique (bug 10721).
4518 # This does not apply to Unicode characters per
4519 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4520 # @todo FIXME: We may be changing them depending on the current locale.
4521 $arrayKey = strtolower( $safeHeadline );
4522 if ( $legacyHeadline === false ) {
4523 $legacyArrayKey = false;
4524 } else {
4525 $legacyArrayKey = strtolower( $legacyHeadline );
4526 }
4527
4528 # count how many in assoc. array so we can track dupes in anchors
4529 if ( isset( $refers[$arrayKey] ) ) {
4530 $refers[$arrayKey]++;
4531 } else {
4532 $refers[$arrayKey] = 1;
4533 }
4534 if ( isset( $refers[$legacyArrayKey] ) ) {
4535 $refers[$legacyArrayKey]++;
4536 } else {
4537 $refers[$legacyArrayKey] = 1;
4538 }
4539
4540 # Don't number the heading if it is the only one (looks silly)
4541 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4542 # the two are different if the line contains a link
4543 $headline = Html::element(
4544 'span',
4545 array( 'class' => 'mw-headline-number' ),
4546 $numbering
4547 ) . ' ' . $headline;
4548 }
4549
4550 # Create the anchor for linking from the TOC to the section
4551 $anchor = $safeHeadline;
4552 $legacyAnchor = $legacyHeadline;
4553 if ( $refers[$arrayKey] > 1 ) {
4554 $anchor .= '_' . $refers[$arrayKey];
4555 }
4556 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4557 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4558 }
4559 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4560 $toc .= Linker::tocLine( $anchor, $tocline,
4561 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4562 }
4563
4564 # Add the section to the section tree
4565 # Find the DOM node for this header
4566 $noOffset = ( $isTemplate || $sectionIndex === false );
4567 while ( $node && !$noOffset ) {
4568 if ( $node->getName() === 'h' ) {
4569 $bits = $node->splitHeading();
4570 if ( $bits['i'] == $sectionIndex ) {
4571 break;
4572 }
4573 }
4574 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4575 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4576 $node = $node->getNextSibling();
4577 }
4578 $tocraw[] = array(
4579 'toclevel' => $toclevel,
4580 'level' => $level,
4581 'line' => $tocline,
4582 'number' => $numbering,
4583 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4584 'fromtitle' => $titleText,
4585 'byteoffset' => ( $noOffset ? null : $byteOffset ),
4586 'anchor' => $anchor,
4587 );
4588
4589 # give headline the correct <h#> tag
4590 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4591 // Output edit section links as markers with styles that can be customized by skins
4592 if ( $isTemplate ) {
4593 # Put a T flag in the section identifier, to indicate to extractSections()
4594 # that sections inside <includeonly> should be counted.
4595 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4596 } else {
4597 $editlinkArgs = array(
4598 $this->mTitle->getPrefixedText(),
4599 $sectionIndex,
4600 $headlineHint
4601 );
4602 }
4603 // We use a bit of pesudo-xml for editsection markers. The
4604 // language converter is run later on. Using a UNIQ style marker
4605 // leads to the converter screwing up the tokens when it
4606 // converts stuff. And trying to insert strip tags fails too. At
4607 // this point all real inputted tags have already been escaped,
4608 // so we don't have to worry about a user trying to input one of
4609 // these markers directly. We use a page and section attribute
4610 // to stop the language converter from converting these
4611 // important bits of data, but put the headline hint inside a
4612 // content block because the language converter is supposed to
4613 // be able to convert that piece of data.
4614 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4615 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4616 if ( isset( $editlinkArgs[2] ) ) {
4617 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4618 } else {
4619 $editlink .= '/>';
4620 }
4621 } else {
4622 $editlink = '';
4623 }
4624 $head[$headlineCount] = Linker::makeHeadline( $level,
4625 $matches['attrib'][$headlineCount], $anchor, $headline,
4626 $editlink, $legacyAnchor );
4627
4628 $headlineCount++;
4629 }
4630
4631 $this->setOutputType( $oldType );
4632
4633 # Never ever show TOC if no headers
4634 if ( $numVisible < 1 ) {
4635 $enoughToc = false;
4636 }
4637
4638 if ( $enoughToc ) {
4639 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4640 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4641 }
4642 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4643 $this->mOutput->setTOCHTML( $toc );
4644 $toc = self::TOC_START . $toc . self::TOC_END;
4645 $this->mOutput->addModules( 'mediawiki.toc' );
4646 }
4647
4648 if ( $isMain ) {
4649 $this->mOutput->setSections( $tocraw );
4650 }
4651
4652 # split up and insert constructed headlines
4653 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4654 $i = 0;
4655
4656 // build an array of document sections
4657 $sections = array();
4658 foreach ( $blocks as $block ) {
4659 // $head is zero-based, sections aren't.
4660 if ( empty( $head[$i - 1] ) ) {
4661 $sections[$i] = $block;
4662 } else {
4663 $sections[$i] = $head[$i - 1] . $block;
4664 }
4665
4666 /**
4667 * Send a hook, one per section.
4668 * The idea here is to be able to make section-level DIVs, but to do so in a
4669 * lower-impact, more correct way than r50769
4670 *
4671 * $this : caller
4672 * $section : the section number
4673 * &$sectionContent : ref to the content of the section
4674 * $showEditLinks : boolean describing whether this section has an edit link
4675 */
4676 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4677
4678 $i++;
4679 }
4680
4681 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4682 // append the TOC at the beginning
4683 // Top anchor now in skin
4684 $sections[0] = $sections[0] . $toc . "\n";
4685 }
4686
4687 $full .= join( '', $sections );
4688
4689 if ( $this->mForceTocPosition ) {
4690 return str_replace( '<!--MWTOC-->', $toc, $full );
4691 } else {
4692 return $full;
4693 }
4694 }
4695
4696 /**
4697 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4698 * conversion, substitting signatures, {{subst:}} templates, etc.
4699 *
4700 * @param string $text The text to transform
4701 * @param Title $title The Title object for the current article
4702 * @param User $user The User object describing the current user
4703 * @param ParserOptions $options Parsing options
4704 * @param bool $clearState Whether to clear the parser state first
4705 * @return string The altered wiki markup
4706 */
4707 public function preSaveTransform( $text, Title $title, User $user,
4708 ParserOptions $options, $clearState = true
4709 ) {
4710 if ( $clearState ) {
4711 $magicScopeVariable = $this->lock();
4712 }
4713 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4714 $this->setUser( $user );
4715
4716 $pairs = array(
4717 "\r\n" => "\n",
4718 );
4719 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4720 if ( $options->getPreSaveTransform() ) {
4721 $text = $this->pstPass2( $text, $user );
4722 }
4723 $text = $this->mStripState->unstripBoth( $text );
4724
4725 $this->setUser( null ); #Reset
4726
4727 return $text;
4728 }
4729
4730 /**
4731 * Pre-save transform helper function
4732 *
4733 * @param string $text
4734 * @param User $user
4735 *
4736 * @return string
4737 */
4738 private function pstPass2( $text, $user ) {
4739 global $wgContLang;
4740
4741 # Note: This is the timestamp saved as hardcoded wikitext to
4742 # the database, we use $wgContLang here in order to give
4743 # everyone the same signature and use the default one rather
4744 # than the one selected in each user's preferences.
4745 # (see also bug 12815)
4746 $ts = $this->mOptions->getTimestamp();
4747 $timestamp = MWTimestamp::getLocalInstance( $ts );
4748 $ts = $timestamp->format( 'YmdHis' );
4749 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4750
4751 # Allow translation of timezones through wiki. format() can return
4752 # whatever crap the system uses, localised or not, so we cannot
4753 # ship premade translations.
4754 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4755 $msg = wfMessage( $key )->inContentLanguage();
4756 if ( $msg->exists() ) {
4757 $tzMsg = $msg->text();
4758 }
4759
4760 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4761
4762 # Variable replacement
4763 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4764 $text = $this->replaceVariables( $text );
4765
4766 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4767 # which may corrupt this parser instance via its wfMessage()->text() call-
4768
4769 # Signatures
4770 $sigText = $this->getUserSig( $user );
4771 $text = strtr( $text, array(
4772 '~~~~~' => $d,
4773 '~~~~' => "$sigText $d",
4774 '~~~' => $sigText
4775 ) );
4776
4777 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4778 $tc = '[' . Title::legalChars() . ']';
4779 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4780
4781 // [[ns:page (context)|]]
4782 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4783 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4784 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4785 // [[ns:page (context), context|]] (using either single or double-width comma)
4786 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4787 // [[|page]] (reverse pipe trick: add context from page title)
4788 $p2 = "/\[\[\\|($tc+)]]/";
4789
4790 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4791 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4792 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4793 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4794
4795 $t = $this->mTitle->getText();
4796 $m = array();
4797 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4798 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4799 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4800 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4801 } else {
4802 # if there's no context, don't bother duplicating the title
4803 $text = preg_replace( $p2, '[[\\1]]', $text );
4804 }
4805
4806 # Trim trailing whitespace
4807 $text = rtrim( $text );
4808
4809 return $text;
4810 }
4811
4812 /**
4813 * Fetch the user's signature text, if any, and normalize to
4814 * validated, ready-to-insert wikitext.
4815 * If you have pre-fetched the nickname or the fancySig option, you can
4816 * specify them here to save a database query.
4817 * Do not reuse this parser instance after calling getUserSig(),
4818 * as it may have changed if it's the $wgParser.
4819 *
4820 * @param User $user
4821 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4822 * @param bool|null $fancySig whether the nicknname is the complete signature
4823 * or null to use default value
4824 * @return string
4825 */
4826 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4827 global $wgMaxSigChars;
4828
4829 $username = $user->getName();
4830
4831 # If not given, retrieve from the user object.
4832 if ( $nickname === false ) {
4833 $nickname = $user->getOption( 'nickname' );
4834 }
4835
4836 if ( is_null( $fancySig ) ) {
4837 $fancySig = $user->getBoolOption( 'fancysig' );
4838 }
4839
4840 $nickname = $nickname == null ? $username : $nickname;
4841
4842 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4843 $nickname = $username;
4844 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4845 } elseif ( $fancySig !== false ) {
4846 # Sig. might contain markup; validate this
4847 if ( $this->validateSig( $nickname ) !== false ) {
4848 # Validated; clean up (if needed) and return it
4849 return $this->cleanSig( $nickname, true );
4850 } else {
4851 # Failed to validate; fall back to the default
4852 $nickname = $username;
4853 wfDebug( __METHOD__ . ": $username has bad XML tags in signature.\n" );
4854 }
4855 }
4856
4857 # Make sure nickname doesnt get a sig in a sig
4858 $nickname = self::cleanSigInSig( $nickname );
4859
4860 # If we're still here, make it a link to the user page
4861 $userText = wfEscapeWikiText( $username );
4862 $nickText = wfEscapeWikiText( $nickname );
4863 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4864
4865 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4866 ->title( $this->getTitle() )->text();
4867 }
4868
4869 /**
4870 * Check that the user's signature contains no bad XML
4871 *
4872 * @param string $text
4873 * @return string|bool An expanded string, or false if invalid.
4874 */
4875 function validateSig( $text ) {
4876 return Xml::isWellFormedXmlFragment( $text ) ? $text : false;
4877 }
4878
4879 /**
4880 * Clean up signature text
4881 *
4882 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4883 * 2) Substitute all transclusions
4884 *
4885 * @param string $text
4886 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4887 * @return string Signature text
4888 */
4889 public function cleanSig( $text, $parsing = false ) {
4890 if ( !$parsing ) {
4891 global $wgTitle;
4892 $magicScopeVariable = $this->lock();
4893 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4894 }
4895
4896 # Option to disable this feature
4897 if ( !$this->mOptions->getCleanSignatures() ) {
4898 return $text;
4899 }
4900
4901 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4902 # => Move this logic to braceSubstitution()
4903 $substWord = MagicWord::get( 'subst' );
4904 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4905 $substText = '{{' . $substWord->getSynonym( 0 );
4906
4907 $text = preg_replace( $substRegex, $substText, $text );
4908 $text = self::cleanSigInSig( $text );
4909 $dom = $this->preprocessToDom( $text );
4910 $frame = $this->getPreprocessor()->newFrame();
4911 $text = $frame->expand( $dom );
4912
4913 if ( !$parsing ) {
4914 $text = $this->mStripState->unstripBoth( $text );
4915 }
4916
4917 return $text;
4918 }
4919
4920 /**
4921 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4922 *
4923 * @param string $text
4924 * @return string Signature text with /~{3,5}/ removed
4925 */
4926 public static function cleanSigInSig( $text ) {
4927 $text = preg_replace( '/~{3,5}/', '', $text );
4928 return $text;
4929 }
4930
4931 /**
4932 * Set up some variables which are usually set up in parse()
4933 * so that an external function can call some class members with confidence
4934 *
4935 * @param Title|null $title
4936 * @param ParserOptions $options
4937 * @param int $outputType
4938 * @param bool $clearState
4939 */
4940 public function startExternalParse( Title $title = null, ParserOptions $options,
4941 $outputType, $clearState = true
4942 ) {
4943 $this->startParse( $title, $options, $outputType, $clearState );
4944 }
4945
4946 /**
4947 * @param Title|null $title
4948 * @param ParserOptions $options
4949 * @param int $outputType
4950 * @param bool $clearState
4951 */
4952 private function startParse( Title $title = null, ParserOptions $options,
4953 $outputType, $clearState = true
4954 ) {
4955 $this->setTitle( $title );
4956 $this->mOptions = $options;
4957 $this->setOutputType( $outputType );
4958 if ( $clearState ) {
4959 $this->clearState();
4960 }
4961 }
4962
4963 /**
4964 * Wrapper for preprocess()
4965 *
4966 * @param string $text The text to preprocess
4967 * @param ParserOptions $options Options
4968 * @param Title|null $title Title object or null to use $wgTitle
4969 * @return string
4970 */
4971 public function transformMsg( $text, $options, $title = null ) {
4972 static $executing = false;
4973
4974 # Guard against infinite recursion
4975 if ( $executing ) {
4976 return $text;
4977 }
4978 $executing = true;
4979
4980 wfProfileIn( __METHOD__ );
4981 if ( !$title ) {
4982 global $wgTitle;
4983 $title = $wgTitle;
4984 }
4985
4986 $text = $this->preprocess( $text, $title, $options );
4987
4988 $executing = false;
4989 wfProfileOut( __METHOD__ );
4990 return $text;
4991 }
4992
4993 /**
4994 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4995 * The callback should have the following form:
4996 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4997 *
4998 * Transform and return $text. Use $parser for any required context, e.g. use
4999 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5000 *
5001 * Hooks may return extended information by returning an array, of which the
5002 * first numbered element (index 0) must be the return string, and all other
5003 * entries are extracted into local variables within an internal function
5004 * in the Parser class.
5005 *
5006 * This interface (introduced r61913) appears to be undocumented, but
5007 * 'markerName' is used by some core tag hooks to override which strip
5008 * array their results are placed in. **Use great caution if attempting
5009 * this interface, as it is not documented and injudicious use could smash
5010 * private variables.**
5011 *
5012 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5013 * @param mixed $callback The callback function (and object) to use for the tag
5014 * @throws MWException
5015 * @return mixed|null The old value of the mTagHooks array associated with the hook
5016 */
5017 public function setHook( $tag, $callback ) {
5018 $tag = strtolower( $tag );
5019 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5020 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5021 }
5022 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
5023 $this->mTagHooks[$tag] = $callback;
5024 if ( !in_array( $tag, $this->mStripList ) ) {
5025 $this->mStripList[] = $tag;
5026 }
5027
5028 return $oldVal;
5029 }
5030
5031 /**
5032 * As setHook(), but letting the contents be parsed.
5033 *
5034 * Transparent tag hooks are like regular XML-style tag hooks, except they
5035 * operate late in the transformation sequence, on HTML instead of wikitext.
5036 *
5037 * This is probably obsoleted by things dealing with parser frames?
5038 * The only extension currently using it is geoserver.
5039 *
5040 * @since 1.10
5041 * @todo better document or deprecate this
5042 *
5043 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5044 * @param mixed $callback The callback function (and object) to use for the tag
5045 * @throws MWException
5046 * @return mixed|null The old value of the mTagHooks array associated with the hook
5047 */
5048 function setTransparentTagHook( $tag, $callback ) {
5049 $tag = strtolower( $tag );
5050 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5051 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5052 }
5053 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
5054 $this->mTransparentTagHooks[$tag] = $callback;
5055
5056 return $oldVal;
5057 }
5058
5059 /**
5060 * Remove all tag hooks
5061 */
5062 function clearTagHooks() {
5063 $this->mTagHooks = array();
5064 $this->mFunctionTagHooks = array();
5065 $this->mStripList = $this->mDefaultStripList;
5066 }
5067
5068 /**
5069 * Create a function, e.g. {{sum:1|2|3}}
5070 * The callback function should have the form:
5071 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5072 *
5073 * Or with SFH_OBJECT_ARGS:
5074 * function myParserFunction( $parser, $frame, $args ) { ... }
5075 *
5076 * The callback may either return the text result of the function, or an array with the text
5077 * in element 0, and a number of flags in the other elements. The names of the flags are
5078 * specified in the keys. Valid flags are:
5079 * found The text returned is valid, stop processing the template. This
5080 * is on by default.
5081 * nowiki Wiki markup in the return value should be escaped
5082 * isHTML The returned text is HTML, armour it against wikitext transformation
5083 *
5084 * @param string $id The magic word ID
5085 * @param mixed $callback The callback function (and object) to use
5086 * @param int $flags A combination of the following flags:
5087 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5088 *
5089 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5090 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5091 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5092 * the arguments, and to control the way they are expanded.
5093 *
5094 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5095 * arguments, for instance:
5096 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5097 *
5098 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5099 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5100 * working if/when this is changed.
5101 *
5102 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5103 * expansion.
5104 *
5105 * Please read the documentation in includes/parser/Preprocessor.php for more information
5106 * about the methods available in PPFrame and PPNode.
5107 *
5108 * @throws MWException
5109 * @return string|callable The old callback function for this name, if any
5110 */
5111 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5112 global $wgContLang;
5113
5114 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
5115 $this->mFunctionHooks[$id] = array( $callback, $flags );
5116
5117 # Add to function cache
5118 $mw = MagicWord::get( $id );
5119 if ( !$mw ) {
5120 throw new MWException( __METHOD__ . '() expecting a magic word identifier.' );
5121 }
5122
5123 $synonyms = $mw->getSynonyms();
5124 $sensitive = intval( $mw->isCaseSensitive() );
5125
5126 foreach ( $synonyms as $syn ) {
5127 # Case
5128 if ( !$sensitive ) {
5129 $syn = $wgContLang->lc( $syn );
5130 }
5131 # Add leading hash
5132 if ( !( $flags & SFH_NO_HASH ) ) {
5133 $syn = '#' . $syn;
5134 }
5135 # Remove trailing colon
5136 if ( substr( $syn, -1, 1 ) === ':' ) {
5137 $syn = substr( $syn, 0, -1 );
5138 }
5139 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
5140 }
5141 return $oldVal;
5142 }
5143
5144 /**
5145 * Get all registered function hook identifiers
5146 *
5147 * @return array
5148 */
5149 function getFunctionHooks() {
5150 return array_keys( $this->mFunctionHooks );
5151 }
5152
5153 /**
5154 * Create a tag function, e.g. "<test>some stuff</test>".
5155 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5156 * Unlike parser functions, their content is not preprocessed.
5157 * @param string $tag
5158 * @param callable $callback
5159 * @param int $flags
5160 * @throws MWException
5161 * @return null
5162 */
5163 function setFunctionTagHook( $tag, $callback, $flags ) {
5164 $tag = strtolower( $tag );
5165 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5166 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5167 }
5168 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
5169 $this->mFunctionTagHooks[$tag] : null;
5170 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
5171
5172 if ( !in_array( $tag, $this->mStripList ) ) {
5173 $this->mStripList[] = $tag;
5174 }
5175
5176 return $old;
5177 }
5178
5179 /**
5180 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5181 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5182 * Placeholders created in Skin::makeLinkObj()
5183 *
5184 * @param string $text
5185 * @param int $options
5186 *
5187 * @return array Array of link CSS classes, indexed by PDBK.
5188 */
5189 function replaceLinkHolders( &$text, $options = 0 ) {
5190 return $this->mLinkHolders->replace( $text );
5191 }
5192
5193 /**
5194 * Replace "<!--LINK-->" link placeholders with plain text of links
5195 * (not HTML-formatted).
5196 *
5197 * @param string $text
5198 * @return string
5199 */
5200 function replaceLinkHoldersText( $text ) {
5201 return $this->mLinkHolders->replaceText( $text );
5202 }
5203
5204 /**
5205 * Renders an image gallery from a text with one line per image.
5206 * text labels may be given by using |-style alternative text. E.g.
5207 * Image:one.jpg|The number "1"
5208 * Image:tree.jpg|A tree
5209 * given as text will return the HTML of a gallery with two images,
5210 * labeled 'The number "1"' and
5211 * 'A tree'.
5212 *
5213 * @param string $text
5214 * @param array $params
5215 * @return string HTML
5216 */
5217 function renderImageGallery( $text, $params ) {
5218 wfProfileIn( __METHOD__ );
5219
5220 $mode = false;
5221 if ( isset( $params['mode'] ) ) {
5222 $mode = $params['mode'];
5223 }
5224
5225 try {
5226 $ig = ImageGalleryBase::factory( $mode );
5227 } catch ( MWException $e ) {
5228 // If invalid type set, fallback to default.
5229 $ig = ImageGalleryBase::factory( false );
5230 }
5231
5232 $ig->setContextTitle( $this->mTitle );
5233 $ig->setShowBytes( false );
5234 $ig->setShowFilename( false );
5235 $ig->setParser( $this );
5236 $ig->setHideBadImages();
5237 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
5238
5239 if ( isset( $params['showfilename'] ) ) {
5240 $ig->setShowFilename( true );
5241 } else {
5242 $ig->setShowFilename( false );
5243 }
5244 if ( isset( $params['caption'] ) ) {
5245 $caption = $params['caption'];
5246 $caption = htmlspecialchars( $caption );
5247 $caption = $this->replaceInternalLinks( $caption );
5248 $ig->setCaptionHtml( $caption );
5249 }
5250 if ( isset( $params['perrow'] ) ) {
5251 $ig->setPerRow( $params['perrow'] );
5252 }
5253 if ( isset( $params['widths'] ) ) {
5254 $ig->setWidths( $params['widths'] );
5255 }
5256 if ( isset( $params['heights'] ) ) {
5257 $ig->setHeights( $params['heights'] );
5258 }
5259 $ig->setAdditionalOptions( $params );
5260
5261 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5262
5263 $lines = StringUtils::explode( "\n", $text );
5264 foreach ( $lines as $line ) {
5265 # match lines like these:
5266 # Image:someimage.jpg|This is some image
5267 $matches = array();
5268 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5269 # Skip empty lines
5270 if ( count( $matches ) == 0 ) {
5271 continue;
5272 }
5273
5274 if ( strpos( $matches[0], '%' ) !== false ) {
5275 $matches[1] = rawurldecode( $matches[1] );
5276 }
5277 $title = Title::newFromText( $matches[1], NS_FILE );
5278 if ( is_null( $title ) ) {
5279 # Bogus title. Ignore these so we don't bomb out later.
5280 continue;
5281 }
5282
5283 # We need to get what handler the file uses, to figure out parameters.
5284 # Note, a hook can overide the file name, and chose an entirely different
5285 # file (which potentially could be of a different type and have different handler).
5286 $options = array();
5287 $descQuery = false;
5288 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5289 array( $this, $title, &$options, &$descQuery ) );
5290 # Don't register it now, as ImageGallery does that later.
5291 $file = $this->fetchFileNoRegister( $title, $options );
5292 $handler = $file ? $file->getHandler() : false;
5293
5294 wfProfileIn( __METHOD__ . '-getMagicWord' );
5295 $paramMap = array(
5296 'img_alt' => 'gallery-internal-alt',
5297 'img_link' => 'gallery-internal-link',
5298 );
5299 if ( $handler ) {
5300 $paramMap = $paramMap + $handler->getParamMap();
5301 // We don't want people to specify per-image widths.
5302 // Additionally the width parameter would need special casing anyhow.
5303 unset( $paramMap['img_width'] );
5304 }
5305
5306 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5307 wfProfileOut( __METHOD__ . '-getMagicWord' );
5308
5309 $label = '';
5310 $alt = '';
5311 $link = '';
5312 $handlerOptions = array();
5313 if ( isset( $matches[3] ) ) {
5314 // look for an |alt= definition while trying not to break existing
5315 // captions with multiple pipes (|) in it, until a more sensible grammar
5316 // is defined for images in galleries
5317
5318 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5319 // splitting on '|' is a bit odd, and different from makeImage.
5320 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5321 $parameterMatches = StringUtils::explode( '|', $matches[3] );
5322
5323 foreach ( $parameterMatches as $parameterMatch ) {
5324 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5325 if ( $magicName ) {
5326 $paramName = $paramMap[$magicName];
5327
5328 switch ( $paramName ) {
5329 case 'gallery-internal-alt':
5330 $alt = $this->stripAltText( $match, false );
5331 break;
5332 case 'gallery-internal-link':
5333 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5334 $chars = self::EXT_LINK_URL_CLASS;
5335 $prots = $this->mUrlProtocols;
5336 //check to see if link matches an absolute url, if not then it must be a wiki link.
5337 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5338 $link = $linkValue;
5339 } else {
5340 $localLinkTitle = Title::newFromText( $linkValue );
5341 if ( $localLinkTitle !== null ) {
5342 $link = $localLinkTitle->getLinkURL();
5343 }
5344 }
5345 break;
5346 default:
5347 // Must be a handler specific parameter.
5348 if ( $handler->validateParam( $paramName, $match ) ) {
5349 $handlerOptions[$paramName] = $match;
5350 } else {
5351 // Guess not. Append it to the caption.
5352 wfDebug( "$parameterMatch failed parameter validation\n" );
5353 $label .= '|' . $parameterMatch;
5354 }
5355 }
5356
5357 } else {
5358 // concatenate all other pipes
5359 $label .= '|' . $parameterMatch;
5360 }
5361 }
5362 // remove the first pipe
5363 $label = substr( $label, 1 );
5364 }
5365
5366 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5367 }
5368 $html = $ig->toHTML();
5369 wfProfileOut( __METHOD__ );
5370 return $html;
5371 }
5372
5373 /**
5374 * @param string $handler
5375 * @return array
5376 */
5377 function getImageParams( $handler ) {
5378 if ( $handler ) {
5379 $handlerClass = get_class( $handler );
5380 } else {
5381 $handlerClass = '';
5382 }
5383 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5384 # Initialise static lists
5385 static $internalParamNames = array(
5386 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5387 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5388 'bottom', 'text-bottom' ),
5389 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5390 'upright', 'border', 'link', 'alt', 'class' ),
5391 );
5392 static $internalParamMap;
5393 if ( !$internalParamMap ) {
5394 $internalParamMap = array();
5395 foreach ( $internalParamNames as $type => $names ) {
5396 foreach ( $names as $name ) {
5397 $magicName = str_replace( '-', '_', "img_$name" );
5398 $internalParamMap[$magicName] = array( $type, $name );
5399 }
5400 }
5401 }
5402
5403 # Add handler params
5404 $paramMap = $internalParamMap;
5405 if ( $handler ) {
5406 $handlerParamMap = $handler->getParamMap();
5407 foreach ( $handlerParamMap as $magic => $paramName ) {
5408 $paramMap[$magic] = array( 'handler', $paramName );
5409 }
5410 }
5411 $this->mImageParams[$handlerClass] = $paramMap;
5412 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5413 }
5414 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
5415 }
5416
5417 /**
5418 * Parse image options text and use it to make an image
5419 *
5420 * @param Title $title
5421 * @param string $options
5422 * @param LinkHolderArray|bool $holders
5423 * @return string HTML
5424 */
5425 function makeImage( $title, $options, $holders = false ) {
5426 # Check if the options text is of the form "options|alt text"
5427 # Options are:
5428 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5429 # * left no resizing, just left align. label is used for alt= only
5430 # * right same, but right aligned
5431 # * none same, but not aligned
5432 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5433 # * center center the image
5434 # * frame Keep original image size, no magnify-button.
5435 # * framed Same as "frame"
5436 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5437 # * upright reduce width for upright images, rounded to full __0 px
5438 # * border draw a 1px border around the image
5439 # * alt Text for HTML alt attribute (defaults to empty)
5440 # * class Set a class for img node
5441 # * link Set the target of the image link. Can be external, interwiki, or local
5442 # vertical-align values (no % or length right now):
5443 # * baseline
5444 # * sub
5445 # * super
5446 # * top
5447 # * text-top
5448 # * middle
5449 # * bottom
5450 # * text-bottom
5451
5452 $parts = StringUtils::explode( "|", $options );
5453
5454 # Give extensions a chance to select the file revision for us
5455 $options = array();
5456 $descQuery = false;
5457 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5458 array( $this, $title, &$options, &$descQuery ) );
5459 # Fetch and register the file (file title may be different via hooks)
5460 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5461
5462 # Get parameter map
5463 $handler = $file ? $file->getHandler() : false;
5464
5465 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5466
5467 if ( !$file ) {
5468 $this->addTrackingCategory( 'broken-file-category' );
5469 }
5470
5471 # Process the input parameters
5472 $caption = '';
5473 $params = array( 'frame' => array(), 'handler' => array(),
5474 'horizAlign' => array(), 'vertAlign' => array() );
5475 $seenformat = false;
5476 foreach ( $parts as $part ) {
5477 $part = trim( $part );
5478 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5479 $validated = false;
5480 if ( isset( $paramMap[$magicName] ) ) {
5481 list( $type, $paramName ) = $paramMap[$magicName];
5482
5483 # Special case; width and height come in one variable together
5484 if ( $type === 'handler' && $paramName === 'width' ) {
5485 $parsedWidthParam = $this->parseWidthParam( $value );
5486 if ( isset( $parsedWidthParam['width'] ) ) {
5487 $width = $parsedWidthParam['width'];
5488 if ( $handler->validateParam( 'width', $width ) ) {
5489 $params[$type]['width'] = $width;
5490 $validated = true;
5491 }
5492 }
5493 if ( isset( $parsedWidthParam['height'] ) ) {
5494 $height = $parsedWidthParam['height'];
5495 if ( $handler->validateParam( 'height', $height ) ) {
5496 $params[$type]['height'] = $height;
5497 $validated = true;
5498 }
5499 }
5500 # else no validation -- bug 13436
5501 } else {
5502 if ( $type === 'handler' ) {
5503 # Validate handler parameter
5504 $validated = $handler->validateParam( $paramName, $value );
5505 } else {
5506 # Validate internal parameters
5507 switch ( $paramName ) {
5508 case 'manualthumb':
5509 case 'alt':
5510 case 'class':
5511 # @todo FIXME: Possibly check validity here for
5512 # manualthumb? downstream behavior seems odd with
5513 # missing manual thumbs.
5514 $validated = true;
5515 $value = $this->stripAltText( $value, $holders );
5516 break;
5517 case 'link':
5518 $chars = self::EXT_LINK_URL_CLASS;
5519 $prots = $this->mUrlProtocols;
5520 if ( $value === '' ) {
5521 $paramName = 'no-link';
5522 $value = true;
5523 $validated = true;
5524 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5525 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5526 $paramName = 'link-url';
5527 $this->mOutput->addExternalLink( $value );
5528 if ( $this->mOptions->getExternalLinkTarget() ) {
5529 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5530 }
5531 $validated = true;
5532 }
5533 } else {
5534 $linkTitle = Title::newFromText( $value );
5535 if ( $linkTitle ) {
5536 $paramName = 'link-title';
5537 $value = $linkTitle;
5538 $this->mOutput->addLink( $linkTitle );
5539 $validated = true;
5540 }
5541 }
5542 break;
5543 case 'frameless':
5544 case 'framed':
5545 case 'thumbnail':
5546 // use first appearing option, discard others.
5547 $validated = ! $seenformat;
5548 $seenformat = true;
5549 break;
5550 default:
5551 # Most other things appear to be empty or numeric...
5552 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5553 }
5554 }
5555
5556 if ( $validated ) {
5557 $params[$type][$paramName] = $value;
5558 }
5559 }
5560 }
5561 if ( !$validated ) {
5562 $caption = $part;
5563 }
5564 }
5565
5566 # Process alignment parameters
5567 if ( $params['horizAlign'] ) {
5568 $params['frame']['align'] = key( $params['horizAlign'] );
5569 }
5570 if ( $params['vertAlign'] ) {
5571 $params['frame']['valign'] = key( $params['vertAlign'] );
5572 }
5573
5574 $params['frame']['caption'] = $caption;
5575
5576 # Will the image be presented in a frame, with the caption below?
5577 $imageIsFramed = isset( $params['frame']['frame'] )
5578 || isset( $params['frame']['framed'] )
5579 || isset( $params['frame']['thumbnail'] )
5580 || isset( $params['frame']['manualthumb'] );
5581
5582 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5583 # came to also set the caption, ordinary text after the image -- which
5584 # makes no sense, because that just repeats the text multiple times in
5585 # screen readers. It *also* came to set the title attribute.
5586 #
5587 # Now that we have an alt attribute, we should not set the alt text to
5588 # equal the caption: that's worse than useless, it just repeats the
5589 # text. This is the framed/thumbnail case. If there's no caption, we
5590 # use the unnamed parameter for alt text as well, just for the time be-
5591 # ing, if the unnamed param is set and the alt param is not.
5592 #
5593 # For the future, we need to figure out if we want to tweak this more,
5594 # e.g., introducing a title= parameter for the title; ignoring the un-
5595 # named parameter entirely for images without a caption; adding an ex-
5596 # plicit caption= parameter and preserving the old magic unnamed para-
5597 # meter for BC; ...
5598 if ( $imageIsFramed ) { # Framed image
5599 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5600 # No caption or alt text, add the filename as the alt text so
5601 # that screen readers at least get some description of the image
5602 $params['frame']['alt'] = $title->getText();
5603 }
5604 # Do not set $params['frame']['title'] because tooltips don't make sense
5605 # for framed images
5606 } else { # Inline image
5607 if ( !isset( $params['frame']['alt'] ) ) {
5608 # No alt text, use the "caption" for the alt text
5609 if ( $caption !== '' ) {
5610 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5611 } else {
5612 # No caption, fall back to using the filename for the
5613 # alt text
5614 $params['frame']['alt'] = $title->getText();
5615 }
5616 }
5617 # Use the "caption" for the tooltip text
5618 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5619 }
5620
5621 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5622
5623 # Linker does the rest
5624 $time = isset( $options['time'] ) ? $options['time'] : false;
5625 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5626 $time, $descQuery, $this->mOptions->getThumbSize() );
5627
5628 # Give the handler a chance to modify the parser object
5629 if ( $handler ) {
5630 $handler->parserTransformHook( $this, $file );
5631 }
5632
5633 return $ret;
5634 }
5635
5636 /**
5637 * @param string $caption
5638 * @param LinkHolderArray|bool $holders
5639 * @return mixed|string
5640 */
5641 protected function stripAltText( $caption, $holders ) {
5642 # Strip bad stuff out of the title (tooltip). We can't just use
5643 # replaceLinkHoldersText() here, because if this function is called
5644 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5645 if ( $holders ) {
5646 $tooltip = $holders->replaceText( $caption );
5647 } else {
5648 $tooltip = $this->replaceLinkHoldersText( $caption );
5649 }
5650
5651 # make sure there are no placeholders in thumbnail attributes
5652 # that are later expanded to html- so expand them now and
5653 # remove the tags
5654 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5655 $tooltip = Sanitizer::stripAllTags( $tooltip );
5656
5657 return $tooltip;
5658 }
5659
5660 /**
5661 * Set a flag in the output object indicating that the content is dynamic and
5662 * shouldn't be cached.
5663 */
5664 function disableCache() {
5665 wfDebug( "Parser output marked as uncacheable.\n" );
5666 if ( !$this->mOutput ) {
5667 throw new MWException( __METHOD__ .
5668 " can only be called when actually parsing something" );
5669 }
5670 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5671 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5672 }
5673
5674 /**
5675 * Callback from the Sanitizer for expanding items found in HTML attribute
5676 * values, so they can be safely tested and escaped.
5677 *
5678 * @param string $text
5679 * @param bool|PPFrame $frame
5680 * @return string
5681 */
5682 function attributeStripCallback( &$text, $frame = false ) {
5683 $text = $this->replaceVariables( $text, $frame );
5684 $text = $this->mStripState->unstripBoth( $text );
5685 return $text;
5686 }
5687
5688 /**
5689 * Accessor
5690 *
5691 * @return array
5692 */
5693 function getTags() {
5694 return array_merge(
5695 array_keys( $this->mTransparentTagHooks ),
5696 array_keys( $this->mTagHooks ),
5697 array_keys( $this->mFunctionTagHooks )
5698 );
5699 }
5700
5701 /**
5702 * Replace transparent tags in $text with the values given by the callbacks.
5703 *
5704 * Transparent tag hooks are like regular XML-style tag hooks, except they
5705 * operate late in the transformation sequence, on HTML instead of wikitext.
5706 *
5707 * @param string $text
5708 *
5709 * @return string
5710 */
5711 function replaceTransparentTags( $text ) {
5712 $matches = array();
5713 $elements = array_keys( $this->mTransparentTagHooks );
5714 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5715 $replacements = array();
5716
5717 foreach ( $matches as $marker => $data ) {
5718 list( $element, $content, $params, $tag ) = $data;
5719 $tagName = strtolower( $element );
5720 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5721 $output = call_user_func_array(
5722 $this->mTransparentTagHooks[$tagName],
5723 array( $content, $params, $this )
5724 );
5725 } else {
5726 $output = $tag;
5727 }
5728 $replacements[$marker] = $output;
5729 }
5730 return strtr( $text, $replacements );
5731 }
5732
5733 /**
5734 * Break wikitext input into sections, and either pull or replace
5735 * some particular section's text.
5736 *
5737 * External callers should use the getSection and replaceSection methods.
5738 *
5739 * @param string $text Page wikitext
5740 * @param string|number $sectionId A section identifier string of the form:
5741 * "<flag1> - <flag2> - ... - <section number>"
5742 *
5743 * Currently the only recognised flag is "T", which means the target section number
5744 * was derived during a template inclusion parse, in other words this is a template
5745 * section edit link. If no flags are given, it was an ordinary section edit link.
5746 * This flag is required to avoid a section numbering mismatch when a section is
5747 * enclosed by "<includeonly>" (bug 6563).
5748 *
5749 * The section number 0 pulls the text before the first heading; other numbers will
5750 * pull the given section along with its lower-level subsections. If the section is
5751 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5752 *
5753 * Section 0 is always considered to exist, even if it only contains the empty
5754 * string. If $text is the empty string and section 0 is replaced, $newText is
5755 * returned.
5756 *
5757 * @param string $mode One of "get" or "replace"
5758 * @param string $newText Replacement text for section data.
5759 * @return string For "get", the extracted section text.
5760 * for "replace", the whole page with the section replaced.
5761 */
5762 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5763 global $wgTitle; # not generally used but removes an ugly failure mode
5764
5765 $magicScopeVariable = $this->lock();
5766 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5767 $outText = '';
5768 $frame = $this->getPreprocessor()->newFrame();
5769
5770 # Process section extraction flags
5771 $flags = 0;
5772 $sectionParts = explode( '-', $sectionId );
5773 $sectionIndex = array_pop( $sectionParts );
5774 foreach ( $sectionParts as $part ) {
5775 if ( $part === 'T' ) {
5776 $flags |= self::PTD_FOR_INCLUSION;
5777 }
5778 }
5779
5780 # Check for empty input
5781 if ( strval( $text ) === '' ) {
5782 # Only sections 0 and T-0 exist in an empty document
5783 if ( $sectionIndex == 0 ) {
5784 if ( $mode === 'get' ) {
5785 return '';
5786 } else {
5787 return $newText;
5788 }
5789 } else {
5790 if ( $mode === 'get' ) {
5791 return $newText;
5792 } else {
5793 return $text;
5794 }
5795 }
5796 }
5797
5798 # Preprocess the text
5799 $root = $this->preprocessToDom( $text, $flags );
5800
5801 # <h> nodes indicate section breaks
5802 # They can only occur at the top level, so we can find them by iterating the root's children
5803 $node = $root->getFirstChild();
5804
5805 # Find the target section
5806 if ( $sectionIndex == 0 ) {
5807 # Section zero doesn't nest, level=big
5808 $targetLevel = 1000;
5809 } else {
5810 while ( $node ) {
5811 if ( $node->getName() === 'h' ) {
5812 $bits = $node->splitHeading();
5813 if ( $bits['i'] == $sectionIndex ) {
5814 $targetLevel = $bits['level'];
5815 break;
5816 }
5817 }
5818 if ( $mode === 'replace' ) {
5819 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5820 }
5821 $node = $node->getNextSibling();
5822 }
5823 }
5824
5825 if ( !$node ) {
5826 # Not found
5827 if ( $mode === 'get' ) {
5828 return $newText;
5829 } else {
5830 return $text;
5831 }
5832 }
5833
5834 # Find the end of the section, including nested sections
5835 do {
5836 if ( $node->getName() === 'h' ) {
5837 $bits = $node->splitHeading();
5838 $curLevel = $bits['level'];
5839 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5840 break;
5841 }
5842 }
5843 if ( $mode === 'get' ) {
5844 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5845 }
5846 $node = $node->getNextSibling();
5847 } while ( $node );
5848
5849 # Write out the remainder (in replace mode only)
5850 if ( $mode === 'replace' ) {
5851 # Output the replacement text
5852 # Add two newlines on -- trailing whitespace in $newText is conventionally
5853 # stripped by the editor, so we need both newlines to restore the paragraph gap
5854 # Only add trailing whitespace if there is newText
5855 if ( $newText != "" ) {
5856 $outText .= $newText . "\n\n";
5857 }
5858
5859 while ( $node ) {
5860 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5861 $node = $node->getNextSibling();
5862 }
5863 }
5864
5865 if ( is_string( $outText ) ) {
5866 # Re-insert stripped tags
5867 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5868 }
5869
5870 return $outText;
5871 }
5872
5873 /**
5874 * This function returns the text of a section, specified by a number ($section).
5875 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5876 * the first section before any such heading (section 0).
5877 *
5878 * If a section contains subsections, these are also returned.
5879 *
5880 * @param string $text Text to look in
5881 * @param string|number $sectionId Section identifier as a number or string
5882 * (e.g. 0, 1 or 'T-1').
5883 * @param string $defaultText Default to return if section is not found
5884 *
5885 * @return string Text of the requested section
5886 */
5887 public function getSection( $text, $sectionId, $defaultText = '' ) {
5888 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5889 }
5890
5891 /**
5892 * This function returns $oldtext after the content of the section
5893 * specified by $section has been replaced with $text. If the target
5894 * section does not exist, $oldtext is returned unchanged.
5895 *
5896 * @param string $oldText Former text of the article
5897 * @param string|number $sectionId Section identifier as a number or string
5898 * (e.g. 0, 1 or 'T-1').
5899 * @param string $newText Replacing text
5900 *
5901 * @return string Modified text
5902 */
5903 public function replaceSection( $oldText, $sectionId, $newText ) {
5904 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5905 }
5906
5907 /**
5908 * Get the ID of the revision we are parsing
5909 *
5910 * @return int|null
5911 */
5912 function getRevisionId() {
5913 return $this->mRevisionId;
5914 }
5915
5916 /**
5917 * Get the revision object for $this->mRevisionId
5918 *
5919 * @return Revision|null Either a Revision object or null
5920 * @since 1.23 (public since 1.23)
5921 */
5922 public function getRevisionObject() {
5923 if ( !is_null( $this->mRevisionObject ) ) {
5924 return $this->mRevisionObject;
5925 }
5926 if ( is_null( $this->mRevisionId ) ) {
5927 return null;
5928 }
5929
5930 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
5931 return $this->mRevisionObject;
5932 }
5933
5934 /**
5935 * Get the timestamp associated with the current revision, adjusted for
5936 * the default server-local timestamp
5937 * @return string
5938 */
5939 function getRevisionTimestamp() {
5940 if ( is_null( $this->mRevisionTimestamp ) ) {
5941 wfProfileIn( __METHOD__ );
5942
5943 global $wgContLang;
5944
5945 $revObject = $this->getRevisionObject();
5946 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5947
5948 # The cryptic '' timezone parameter tells to use the site-default
5949 # timezone offset instead of the user settings.
5950 #
5951 # Since this value will be saved into the parser cache, served
5952 # to other users, and potentially even used inside links and such,
5953 # it needs to be consistent for all visitors.
5954 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5955
5956 wfProfileOut( __METHOD__ );
5957 }
5958 return $this->mRevisionTimestamp;
5959 }
5960
5961 /**
5962 * Get the name of the user that edited the last revision
5963 *
5964 * @return string User name
5965 */
5966 function getRevisionUser() {
5967 if ( is_null( $this->mRevisionUser ) ) {
5968 $revObject = $this->getRevisionObject();
5969
5970 # if this template is subst: the revision id will be blank,
5971 # so just use the current user's name
5972 if ( $revObject ) {
5973 $this->mRevisionUser = $revObject->getUserText();
5974 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5975 $this->mRevisionUser = $this->getUser()->getName();
5976 }
5977 }
5978 return $this->mRevisionUser;
5979 }
5980
5981 /**
5982 * Get the size of the revision
5983 *
5984 * @return int|null Revision size
5985 */
5986 function getRevisionSize() {
5987 if ( is_null( $this->mRevisionSize ) ) {
5988 $revObject = $this->getRevisionObject();
5989
5990 # if this variable is subst: the revision id will be blank,
5991 # so just use the parser input size, because the own substituation
5992 # will change the size.
5993 if ( $revObject ) {
5994 $this->mRevisionSize = $revObject->getSize();
5995 } elseif ( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5996 $this->mRevisionSize = $this->mInputSize;
5997 }
5998 }
5999 return $this->mRevisionSize;
6000 }
6001
6002 /**
6003 * Mutator for $mDefaultSort
6004 *
6005 * @param string $sort New value
6006 */
6007 public function setDefaultSort( $sort ) {
6008 $this->mDefaultSort = $sort;
6009 $this->mOutput->setProperty( 'defaultsort', $sort );
6010 }
6011
6012 /**
6013 * Accessor for $mDefaultSort
6014 * Will use the empty string if none is set.
6015 *
6016 * This value is treated as a prefix, so the
6017 * empty string is equivalent to sorting by
6018 * page name.
6019 *
6020 * @return string
6021 */
6022 public function getDefaultSort() {
6023 if ( $this->mDefaultSort !== false ) {
6024 return $this->mDefaultSort;
6025 } else {
6026 return '';
6027 }
6028 }
6029
6030 /**
6031 * Accessor for $mDefaultSort
6032 * Unlike getDefaultSort(), will return false if none is set
6033 *
6034 * @return string|bool
6035 */
6036 public function getCustomDefaultSort() {
6037 return $this->mDefaultSort;
6038 }
6039
6040 /**
6041 * Try to guess the section anchor name based on a wikitext fragment
6042 * presumably extracted from a heading, for example "Header" from
6043 * "== Header ==".
6044 *
6045 * @param string $text
6046 *
6047 * @return string
6048 */
6049 public function guessSectionNameFromWikiText( $text ) {
6050 # Strip out wikitext links(they break the anchor)
6051 $text = $this->stripSectionName( $text );
6052 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
6053 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
6054 }
6055
6056 /**
6057 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6058 * instead. For use in redirects, since IE6 interprets Redirect: headers
6059 * as something other than UTF-8 (apparently?), resulting in breakage.
6060 *
6061 * @param string $text The section name
6062 * @return string An anchor
6063 */
6064 public function guessLegacySectionNameFromWikiText( $text ) {
6065 # Strip out wikitext links(they break the anchor)
6066 $text = $this->stripSectionName( $text );
6067 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
6068 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
6069 }
6070
6071 /**
6072 * Strips a text string of wikitext for use in a section anchor
6073 *
6074 * Accepts a text string and then removes all wikitext from the
6075 * string and leaves only the resultant text (i.e. the result of
6076 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6077 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6078 * to create valid section anchors by mimicing the output of the
6079 * parser when headings are parsed.
6080 *
6081 * @param string $text Text string to be stripped of wikitext
6082 * for use in a Section anchor
6083 * @return string Filtered text string
6084 */
6085 public function stripSectionName( $text ) {
6086 # Strip internal link markup
6087 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6088 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6089
6090 # Strip external link markup
6091 # @todo FIXME: Not tolerant to blank link text
6092 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6093 # on how many empty links there are on the page - need to figure that out.
6094 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6095
6096 # Parse wikitext quotes (italics & bold)
6097 $text = $this->doQuotes( $text );
6098
6099 # Strip HTML tags
6100 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
6101 return $text;
6102 }
6103
6104 /**
6105 * strip/replaceVariables/unstrip for preprocessor regression testing
6106 *
6107 * @param string $text
6108 * @param Title $title
6109 * @param ParserOptions $options
6110 * @param int $outputType
6111 *
6112 * @return string
6113 */
6114 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
6115 $magicScopeVariable = $this->lock();
6116 $this->startParse( $title, $options, $outputType, true );
6117
6118 $text = $this->replaceVariables( $text );
6119 $text = $this->mStripState->unstripBoth( $text );
6120 $text = Sanitizer::removeHTMLtags( $text );
6121 return $text;
6122 }
6123
6124 /**
6125 * @param string $text
6126 * @param Title $title
6127 * @param ParserOptions $options
6128 * @return string
6129 */
6130 function testPst( $text, Title $title, ParserOptions $options ) {
6131 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6132 }
6133
6134 /**
6135 * @param string $text
6136 * @param Title $title
6137 * @param ParserOptions $options
6138 * @return string
6139 */
6140 function testPreprocess( $text, Title $title, ParserOptions $options ) {
6141 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
6142 }
6143
6144 /**
6145 * Call a callback function on all regions of the given text that are not
6146 * inside strip markers, and replace those regions with the return value
6147 * of the callback. For example, with input:
6148 *
6149 * aaa<MARKER>bbb
6150 *
6151 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6152 * two strings will be replaced with the value returned by the callback in
6153 * each case.
6154 *
6155 * @param string $s
6156 * @param callable $callback
6157 *
6158 * @return string
6159 */
6160 function markerSkipCallback( $s, $callback ) {
6161 $i = 0;
6162 $out = '';
6163 while ( $i < strlen( $s ) ) {
6164 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
6165 if ( $markerStart === false ) {
6166 $out .= call_user_func( $callback, substr( $s, $i ) );
6167 break;
6168 } else {
6169 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6170 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
6171 if ( $markerEnd === false ) {
6172 $out .= substr( $s, $markerStart );
6173 break;
6174 } else {
6175 $markerEnd += strlen( self::MARKER_SUFFIX );
6176 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6177 $i = $markerEnd;
6178 }
6179 }
6180 }
6181 return $out;
6182 }
6183
6184 /**
6185 * Remove any strip markers found in the given text.
6186 *
6187 * @param string $text Input string
6188 * @return string
6189 */
6190 function killMarkers( $text ) {
6191 return $this->mStripState->killMarkers( $text );
6192 }
6193
6194 /**
6195 * Save the parser state required to convert the given half-parsed text to
6196 * HTML. "Half-parsed" in this context means the output of
6197 * recursiveTagParse() or internalParse(). This output has strip markers
6198 * from replaceVariables (extensionSubstitution() etc.), and link
6199 * placeholders from replaceLinkHolders().
6200 *
6201 * Returns an array which can be serialized and stored persistently. This
6202 * array can later be loaded into another parser instance with
6203 * unserializeHalfParsedText(). The text can then be safely incorporated into
6204 * the return value of a parser hook.
6205 *
6206 * @param string $text
6207 *
6208 * @return array
6209 */
6210 function serializeHalfParsedText( $text ) {
6211 wfProfileIn( __METHOD__ );
6212 $data = array(
6213 'text' => $text,
6214 'version' => self::HALF_PARSED_VERSION,
6215 'stripState' => $this->mStripState->getSubState( $text ),
6216 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
6217 );
6218 wfProfileOut( __METHOD__ );
6219 return $data;
6220 }
6221
6222 /**
6223 * Load the parser state given in the $data array, which is assumed to
6224 * have been generated by serializeHalfParsedText(). The text contents is
6225 * extracted from the array, and its markers are transformed into markers
6226 * appropriate for the current Parser instance. This transformed text is
6227 * returned, and can be safely included in the return value of a parser
6228 * hook.
6229 *
6230 * If the $data array has been stored persistently, the caller should first
6231 * check whether it is still valid, by calling isValidHalfParsedText().
6232 *
6233 * @param array $data Serialized data
6234 * @throws MWException
6235 * @return string
6236 */
6237 function unserializeHalfParsedText( $data ) {
6238 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
6239 throw new MWException( __METHOD__ . ': invalid version' );
6240 }
6241
6242 # First, extract the strip state.
6243 $texts = array( $data['text'] );
6244 $texts = $this->mStripState->merge( $data['stripState'], $texts );
6245
6246 # Now renumber links
6247 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
6248
6249 # Should be good to go.
6250 return $texts[0];
6251 }
6252
6253 /**
6254 * Returns true if the given array, presumed to be generated by
6255 * serializeHalfParsedText(), is compatible with the current version of the
6256 * parser.
6257 *
6258 * @param array $data
6259 *
6260 * @return bool
6261 */
6262 function isValidHalfParsedText( $data ) {
6263 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
6264 }
6265
6266 /**
6267 * Parsed a width param of imagelink like 300px or 200x300px
6268 *
6269 * @param string $value
6270 *
6271 * @return array
6272 * @since 1.20
6273 */
6274 public function parseWidthParam( $value ) {
6275 $parsedWidthParam = array();
6276 if ( $value === '' ) {
6277 return $parsedWidthParam;
6278 }
6279 $m = array();
6280 # (bug 13500) In both cases (width/height and width only),
6281 # permit trailing "px" for backward compatibility.
6282 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6283 $width = intval( $m[1] );
6284 $height = intval( $m[2] );
6285 $parsedWidthParam['width'] = $width;
6286 $parsedWidthParam['height'] = $height;
6287 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6288 $width = intval( $value );
6289 $parsedWidthParam['width'] = $width;
6290 }
6291 return $parsedWidthParam;
6292 }
6293
6294 /**
6295 * Lock the current instance of the parser.
6296 *
6297 * This is meant to stop someone from calling the parser
6298 * recursively and messing up all the strip state.
6299 *
6300 * @throws MWException If parser is in a parse
6301 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6302 */
6303 protected function lock() {
6304 if ( $this->mInParse ) {
6305 throw new MWException( "Parser state cleared while parsing. "
6306 . "Did you call Parser::parse recursively?" );
6307 }
6308 $this->mInParse = true;
6309
6310 $that = $this;
6311 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6312 $that->mInParse = false;
6313 } );
6314
6315 return $recursiveCheck;
6316 }
6317
6318 /**
6319 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6320 *
6321 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6322 * or if there is more than one <p/> tag in the input HTML.
6323 *
6324 * @param string $html
6325 * @return string
6326 * @since 1.24
6327 */
6328 public static function stripOuterParagraph( $html ) {
6329 $m = array();
6330 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6331 if ( strpos( $m[1], '</p>' ) === false ) {
6332 $html = $m[1];
6333 }
6334 }
6335
6336 return $html;
6337 }
6338 }