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