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