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