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