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