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