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