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