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