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