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