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