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