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