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