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