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