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