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