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