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