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