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