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