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