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