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