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