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