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