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