* Reorganised the includes directory, creating subdirectories db, parser and specials
[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( htmlspecialchars( $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 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2650 * @private
2651 */
2652 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2653 # Prevent too big inclusions
2654 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2655 return $text;
2656 }
2657
2658 $fname = __METHOD__;
2659 wfProfileIn( $fname );
2660
2661 if ( $frame === false ) {
2662 $frame = $this->getPreprocessor()->newFrame();
2663 } elseif ( !( $frame instanceof PPFrame ) ) {
2664 throw new MWException( __METHOD__ . ' called using the old argument format' );
2665 }
2666
2667 $dom = $this->preprocessToDom( $text );
2668 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2669 $text = $frame->expand( $dom, $flags );
2670
2671 wfProfileOut( $fname );
2672 return $text;
2673 }
2674
2675 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2676 static function createAssocArgs( $args ) {
2677 $assocArgs = array();
2678 $index = 1;
2679 foreach( $args as $arg ) {
2680 $eqpos = strpos( $arg, '=' );
2681 if ( $eqpos === false ) {
2682 $assocArgs[$index++] = $arg;
2683 } else {
2684 $name = trim( substr( $arg, 0, $eqpos ) );
2685 $value = trim( substr( $arg, $eqpos+1 ) );
2686 if ( $value === false ) {
2687 $value = '';
2688 }
2689 if ( $name !== false ) {
2690 $assocArgs[$name] = $value;
2691 }
2692 }
2693 }
2694
2695 return $assocArgs;
2696 }
2697
2698 /**
2699 * Warn the user when a parser limitation is reached
2700 * Will warn at most once the user per limitation type
2701 *
2702 * @param string $limitationType, should be one of:
2703 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2704 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2705 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2706 * @params int $current, $max When an explicit limit has been
2707 * exceeded, provide the values (optional)
2708 */
2709 function limitationWarn( $limitationType, $current=null, $max=null) {
2710 $msgName = $limitationType . '-warning';
2711 //does no harm if $current and $max are present but are unnecessary for the message
2712 $warning = wfMsg( $msgName, $current, $max);
2713 $this->mOutput->addWarning( $warning );
2714 $cat = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( $limitationType . '-category' ) );
2715 if ( $cat ) {
2716 $this->mOutput->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2717 }
2718 }
2719
2720 /**
2721 * Return the text of a template, after recursively
2722 * replacing any variables or templates within the template.
2723 *
2724 * @param array $piece The parts of the template
2725 * $piece['title']: the title, i.e. the part before the |
2726 * $piece['parts']: the parameter array
2727 * $piece['lineStart']: whether the brace was at the start of a line
2728 * @param PPFrame The current frame, contains template arguments
2729 * @return string the text of the template
2730 * @private
2731 */
2732 function braceSubstitution( $piece, $frame ) {
2733 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2734 $fname = __METHOD__;
2735 wfProfileIn( $fname );
2736 wfProfileIn( __METHOD__.'-setup' );
2737
2738 # Flags
2739 $found = false; # $text has been filled
2740 $nowiki = false; # wiki markup in $text should be escaped
2741 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2742 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2743 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2744 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2745
2746 # Title object, where $text came from
2747 $title = NULL;
2748
2749 # $part1 is the bit before the first |, and must contain only title characters.
2750 # Various prefixes will be stripped from it later.
2751 $titleWithSpaces = $frame->expand( $piece['title'] );
2752 $part1 = trim( $titleWithSpaces );
2753 $titleText = false;
2754
2755 # Original title text preserved for various purposes
2756 $originalTitle = $part1;
2757
2758 # $args is a list of argument nodes, starting from index 0, not including $part1
2759 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2760 wfProfileOut( __METHOD__.'-setup' );
2761
2762 # SUBST
2763 wfProfileIn( __METHOD__.'-modifiers' );
2764 if ( !$found ) {
2765 $mwSubst = MagicWord::get( 'subst' );
2766 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2767 # One of two possibilities is true:
2768 # 1) Found SUBST but not in the PST phase
2769 # 2) Didn't find SUBST and in the PST phase
2770 # In either case, return without further processing
2771 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2772 $isLocalObj = true;
2773 $found = true;
2774 }
2775 }
2776
2777 # Variables
2778 if ( !$found && $args->getLength() == 0 ) {
2779 $id = $this->mVariables->matchStartToEnd( $part1 );
2780 if ( $id !== false ) {
2781 $text = $this->getVariableValue( $id );
2782 if (MagicWord::getCacheTTL($id)>-1)
2783 $this->mOutput->mContainsOldMagic = true;
2784 $found = true;
2785 }
2786 }
2787
2788 # MSG, MSGNW and RAW
2789 if ( !$found ) {
2790 # Check for MSGNW:
2791 $mwMsgnw = MagicWord::get( 'msgnw' );
2792 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2793 $nowiki = true;
2794 } else {
2795 # Remove obsolete MSG:
2796 $mwMsg = MagicWord::get( 'msg' );
2797 $mwMsg->matchStartAndRemove( $part1 );
2798 }
2799
2800 # Check for RAW:
2801 $mwRaw = MagicWord::get( 'raw' );
2802 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2803 $forceRawInterwiki = true;
2804 }
2805 }
2806 wfProfileOut( __METHOD__.'-modifiers' );
2807
2808 # Parser functions
2809 if ( !$found ) {
2810 wfProfileIn( __METHOD__ . '-pfunc' );
2811
2812 $colonPos = strpos( $part1, ':' );
2813 if ( $colonPos !== false ) {
2814 # Case sensitive functions
2815 $function = substr( $part1, 0, $colonPos );
2816 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2817 $function = $this->mFunctionSynonyms[1][$function];
2818 } else {
2819 # Case insensitive functions
2820 $function = strtolower( $function );
2821 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2822 $function = $this->mFunctionSynonyms[0][$function];
2823 } else {
2824 $function = false;
2825 }
2826 }
2827 if ( $function ) {
2828 list( $callback, $flags ) = $this->mFunctionHooks[$function];
2829 $initialArgs = array( &$this );
2830 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
2831 if ( $flags & SFH_OBJECT_ARGS ) {
2832 # Add a frame parameter, and pass the arguments as an array
2833 $allArgs = $initialArgs;
2834 $allArgs[] = $frame;
2835 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2836 $funcArgs[] = $args->item( $i );
2837 }
2838 $allArgs[] = $funcArgs;
2839 } else {
2840 # Convert arguments to plain text
2841 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2842 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2843 }
2844 $allArgs = array_merge( $initialArgs, $funcArgs );
2845 }
2846
2847 # Workaround for PHP bug 35229 and similar
2848 if ( !is_callable( $callback ) ) {
2849 throw new MWException( "Tag hook for $name is not callable\n" );
2850 }
2851 $result = call_user_func_array( $callback, $allArgs );
2852 $found = true;
2853 $noparse = true;
2854 $preprocessFlags = 0;
2855
2856 if ( is_array( $result ) ) {
2857 if ( isset( $result[0] ) ) {
2858 $text = $result[0];
2859 unset( $result[0] );
2860 }
2861
2862 // Extract flags into the local scope
2863 // This allows callers to set flags such as nowiki, found, etc.
2864 extract( $result );
2865 } else {
2866 $text = $result;
2867 }
2868 if ( !$noparse ) {
2869 $text = $this->preprocessToDom( $text, $preprocessFlags );
2870 $isChildObj = true;
2871 }
2872 }
2873 }
2874 wfProfileOut( __METHOD__ . '-pfunc' );
2875 }
2876
2877 # Finish mangling title and then check for loops.
2878 # Set $title to a Title object and $titleText to the PDBK
2879 if ( !$found ) {
2880 $ns = NS_TEMPLATE;
2881 # Split the title into page and subpage
2882 $subpage = '';
2883 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2884 if ($subpage !== '') {
2885 $ns = $this->mTitle->getNamespace();
2886 }
2887 $title = Title::newFromText( $part1, $ns );
2888 if ( $title ) {
2889 $titleText = $title->getPrefixedText();
2890 # Check for language variants if the template is not found
2891 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2892 $wgContLang->findVariantLink($part1, $title);
2893 }
2894 # Do infinite loop check
2895 if ( !$frame->loopCheck( $title ) ) {
2896 $found = true;
2897 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2898 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
2899 }
2900 # Do recursion depth check
2901 $limit = $this->mOptions->getMaxTemplateDepth();
2902 if ( $frame->depth >= $limit ) {
2903 $found = true;
2904 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2905 }
2906 }
2907 }
2908
2909 # Load from database
2910 if ( !$found && $title ) {
2911 wfProfileIn( __METHOD__ . '-loadtpl' );
2912 if ( !$title->isExternal() ) {
2913 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
2914 $text = SpecialPage::capturePath( $title );
2915 if ( is_string( $text ) ) {
2916 $found = true;
2917 $isHTML = true;
2918 $this->disableCache();
2919 }
2920 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2921 $found = false; //access denied
2922 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
2923 } else {
2924 list( $text, $title ) = $this->getTemplateDom( $title );
2925 if ( $text !== false ) {
2926 $found = true;
2927 $isChildObj = true;
2928 }
2929 }
2930
2931 # If the title is valid but undisplayable, make a link to it
2932 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2933 $text = "[[:$titleText]]";
2934 $found = true;
2935 }
2936 } elseif ( $title->isTrans() ) {
2937 // Interwiki transclusion
2938 if ( $this->ot['html'] && !$forceRawInterwiki ) {
2939 $text = $this->interwikiTransclude( $title, 'render' );
2940 $isHTML = true;
2941 } else {
2942 $text = $this->interwikiTransclude( $title, 'raw' );
2943 // Preprocess it like a template
2944 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
2945 $isChildObj = true;
2946 }
2947 $found = true;
2948 }
2949 wfProfileOut( __METHOD__ . '-loadtpl' );
2950 }
2951
2952 # If we haven't found text to substitute by now, we're done
2953 # Recover the source wikitext and return it
2954 if ( !$found ) {
2955 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2956 wfProfileOut( $fname );
2957 return array( 'object' => $text );
2958 }
2959
2960 # Expand DOM-style return values in a child frame
2961 if ( $isChildObj ) {
2962 # Clean up argument array
2963 $newFrame = $frame->newChild( $args, $title );
2964
2965 if ( $nowiki ) {
2966 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
2967 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2968 # Expansion is eligible for the empty-frame cache
2969 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
2970 $text = $this->mTplExpandCache[$titleText];
2971 } else {
2972 $text = $newFrame->expand( $text );
2973 $this->mTplExpandCache[$titleText] = $text;
2974 }
2975 } else {
2976 # Uncached expansion
2977 $text = $newFrame->expand( $text );
2978 }
2979 }
2980 if ( $isLocalObj && $nowiki ) {
2981 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
2982 $isLocalObj = false;
2983 }
2984
2985 # Replace raw HTML by a placeholder
2986 # Add a blank line preceding, to prevent it from mucking up
2987 # immediately preceding headings
2988 if ( $isHTML ) {
2989 $text = "\n\n" . $this->insertStripItem( $text );
2990 }
2991 # Escape nowiki-style return values
2992 elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2993 $text = wfEscapeWikiText( $text );
2994 }
2995 # Bug 529: if the template begins with a table or block-level
2996 # element, it should be treated as beginning a new line.
2997 # This behaviour is somewhat controversial.
2998 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2999 $text = "\n" . $text;
3000 }
3001
3002 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3003 # Error, oversize inclusion
3004 $text = "[[$originalTitle]]" .
3005 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3006 $this->limitationWarn( 'post-expand-template-inclusion' );
3007 }
3008
3009 if ( $isLocalObj ) {
3010 $ret = array( 'object' => $text );
3011 } else {
3012 $ret = array( 'text' => $text );
3013 }
3014
3015 wfProfileOut( $fname );
3016 return $ret;
3017 }
3018
3019 /**
3020 * Get the semi-parsed DOM representation of a template with a given title,
3021 * and its redirect destination title. Cached.
3022 */
3023 function getTemplateDom( $title ) {
3024 $cacheTitle = $title;
3025 $titleText = $title->getPrefixedDBkey();
3026
3027 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3028 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3029 $title = Title::makeTitle( $ns, $dbk );
3030 $titleText = $title->getPrefixedDBkey();
3031 }
3032 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3033 return array( $this->mTplDomCache[$titleText], $title );
3034 }
3035
3036 // Cache miss, go to the database
3037 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3038
3039 if ( $text === false ) {
3040 $this->mTplDomCache[$titleText] = false;
3041 return array( false, $title );
3042 }
3043
3044 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3045 $this->mTplDomCache[ $titleText ] = $dom;
3046
3047 if (! $title->equals($cacheTitle)) {
3048 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3049 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3050 }
3051
3052 return array( $dom, $title );
3053 }
3054
3055 /**
3056 * Fetch the unparsed text of a template and register a reference to it.
3057 */
3058 function fetchTemplateAndTitle( $title ) {
3059 $templateCb = $this->mOptions->getTemplateCallback();
3060 $stuff = call_user_func( $templateCb, $title, $this );
3061 $text = $stuff['text'];
3062 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3063 if ( isset( $stuff['deps'] ) ) {
3064 foreach ( $stuff['deps'] as $dep ) {
3065 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3066 }
3067 }
3068 return array($text,$finalTitle);
3069 }
3070
3071 function fetchTemplate( $title ) {
3072 $rv = $this->fetchTemplateAndTitle($title);
3073 return $rv[0];
3074 }
3075
3076 /**
3077 * Static function to get a template
3078 * Can be overridden via ParserOptions::setTemplateCallback().
3079 */
3080 static function statelessFetchTemplate( $title, $parser=false ) {
3081 $text = $skip = false;
3082 $finalTitle = $title;
3083 $deps = array();
3084
3085 // Loop to fetch the article, with up to 1 redirect
3086 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3087 # Give extensions a chance to select the revision instead
3088 $id = false; // Assume current
3089 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3090
3091 if( $skip ) {
3092 $text = false;
3093 $deps[] = array(
3094 'title' => $title,
3095 'page_id' => $title->getArticleID(),
3096 'rev_id' => null );
3097 break;
3098 }
3099 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3100 $rev_id = $rev ? $rev->getId() : 0;
3101 // If there is no current revision, there is no page
3102 if( $id === false && !$rev ) {
3103 $linkCache = LinkCache::singleton();
3104 $linkCache->addBadLinkObj( $title );
3105 }
3106
3107 $deps[] = array(
3108 'title' => $title,
3109 'page_id' => $title->getArticleID(),
3110 'rev_id' => $rev_id );
3111
3112 if( $rev ) {
3113 $text = $rev->getText();
3114 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3115 global $wgLang;
3116 $message = $wgLang->lcfirst( $title->getText() );
3117 $text = wfMsgForContentNoTrans( $message );
3118 if( wfEmptyMsg( $message, $text ) ) {
3119 $text = false;
3120 break;
3121 }
3122 } else {
3123 break;
3124 }
3125 if ( $text === false ) {
3126 break;
3127 }
3128 // Redirect?
3129 $finalTitle = $title;
3130 $title = Title::newFromRedirect( $text );
3131 }
3132 return array(
3133 'text' => $text,
3134 'finalTitle' => $finalTitle,
3135 'deps' => $deps );
3136 }
3137
3138 /**
3139 * Transclude an interwiki link.
3140 */
3141 function interwikiTransclude( $title, $action ) {
3142 global $wgEnableScaryTranscluding;
3143
3144 if (!$wgEnableScaryTranscluding)
3145 return wfMsg('scarytranscludedisabled');
3146
3147 $url = $title->getFullUrl( "action=$action" );
3148
3149 if (strlen($url) > 255)
3150 return wfMsg('scarytranscludetoolong');
3151 return $this->fetchScaryTemplateMaybeFromCache($url);
3152 }
3153
3154 function fetchScaryTemplateMaybeFromCache($url) {
3155 global $wgTranscludeCacheExpiry;
3156 $dbr = wfGetDB(DB_SLAVE);
3157 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3158 array('tc_url' => $url));
3159 if ($obj) {
3160 $time = $obj->tc_time;
3161 $text = $obj->tc_contents;
3162 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3163 return $text;
3164 }
3165 }
3166
3167 $text = Http::get($url);
3168 if (!$text)
3169 return wfMsg('scarytranscludefailed', $url);
3170
3171 $dbw = wfGetDB(DB_MASTER);
3172 $dbw->replace('transcache', array('tc_url'), array(
3173 'tc_url' => $url,
3174 'tc_time' => time(),
3175 'tc_contents' => $text));
3176 return $text;
3177 }
3178
3179
3180 /**
3181 * Triple brace replacement -- used for template arguments
3182 * @private
3183 */
3184 function argSubstitution( $piece, $frame ) {
3185 wfProfileIn( __METHOD__ );
3186
3187 $error = false;
3188 $parts = $piece['parts'];
3189 $nameWithSpaces = $frame->expand( $piece['title'] );
3190 $argName = trim( $nameWithSpaces );
3191 $object = false;
3192 $text = $frame->getArgument( $argName );
3193 if ( $text === false && $parts->getLength() > 0
3194 && (
3195 $this->ot['html']
3196 || $this->ot['pre']
3197 || ( $this->ot['wiki'] && $frame->isTemplate() )
3198 )
3199 ) {
3200 # No match in frame, use the supplied default
3201 $object = $parts->item( 0 )->getChildren();
3202 }
3203 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3204 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3205 $this->limitationWarn( 'post-expand-template-argument' );
3206 }
3207
3208 if ( $text === false && $object === false ) {
3209 # No match anywhere
3210 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3211 }
3212 if ( $error !== false ) {
3213 $text .= $error;
3214 }
3215 if ( $object !== false ) {
3216 $ret = array( 'object' => $object );
3217 } else {
3218 $ret = array( 'text' => $text );
3219 }
3220
3221 wfProfileOut( __METHOD__ );
3222 return $ret;
3223 }
3224
3225 /**
3226 * Return the text to be used for a given extension tag.
3227 * This is the ghost of strip().
3228 *
3229 * @param array $params Associative array of parameters:
3230 * name PPNode for the tag name
3231 * attr PPNode for unparsed text where tag attributes are thought to be
3232 * attributes Optional associative array of parsed attributes
3233 * inner Contents of extension element
3234 * noClose Original text did not have a close tag
3235 * @param PPFrame $frame
3236 */
3237 function extensionSubstitution( $params, $frame ) {
3238 global $wgRawHtml, $wgContLang;
3239
3240 $name = $frame->expand( $params['name'] );
3241 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3242 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3243
3244 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++) . self::MARKER_SUFFIX;
3245
3246 if ( $this->ot['html'] ) {
3247 $name = strtolower( $name );
3248
3249 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3250 if ( isset( $params['attributes'] ) ) {
3251 $attributes = $attributes + $params['attributes'];
3252 }
3253 switch ( $name ) {
3254 case 'html':
3255 if( $wgRawHtml ) {
3256 $output = $content;
3257 break;
3258 } else {
3259 throw new MWException( '<html> extension tag encountered unexpectedly' );
3260 }
3261 case 'nowiki':
3262 $output = Xml::escapeTagsOnly( $content );
3263 break;
3264 case 'math':
3265 $output = $wgContLang->armourMath(
3266 MathRenderer::renderMath( $content, $attributes ) );
3267 break;
3268 case 'gallery':
3269 $output = $this->renderImageGallery( $content, $attributes );
3270 break;
3271 default:
3272 if( isset( $this->mTagHooks[$name] ) ) {
3273 # Workaround for PHP bug 35229 and similar
3274 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3275 throw new MWException( "Tag hook for $name is not callable\n" );
3276 }
3277 $output = call_user_func_array( $this->mTagHooks[$name],
3278 array( $content, $attributes, $this ) );
3279 } else {
3280 $output = '<span class="error">Invalid tag extension name: ' .
3281 htmlspecialchars( $name ) . '</span>';
3282 }
3283 }
3284 } else {
3285 if ( is_null( $attrText ) ) {
3286 $attrText = '';
3287 }
3288 if ( isset( $params['attributes'] ) ) {
3289 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3290 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3291 htmlspecialchars( $attrValue ) . '"';
3292 }
3293 }
3294 if ( $content === null ) {
3295 $output = "<$name$attrText/>";
3296 } else {
3297 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3298 $output = "<$name$attrText>$content$close";
3299 }
3300 }
3301
3302 if ( $name == 'html' || $name == 'nowiki' ) {
3303 $this->mStripState->nowiki->setPair( $marker, $output );
3304 } else {
3305 $this->mStripState->general->setPair( $marker, $output );
3306 }
3307 return $marker;
3308 }
3309
3310 /**
3311 * Increment an include size counter
3312 *
3313 * @param string $type The type of expansion
3314 * @param integer $size The size of the text
3315 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3316 */
3317 function incrementIncludeSize( $type, $size ) {
3318 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3319 return false;
3320 } else {
3321 $this->mIncludeSizes[$type] += $size;
3322 return true;
3323 }
3324 }
3325
3326 /**
3327 * Increment the expensive function count
3328 *
3329 * @return boolean False if the limit has been exceeded
3330 */
3331 function incrementExpensiveFunctionCount() {
3332 global $wgExpensiveParserFunctionLimit;
3333 $this->mExpensiveFunctionCount++;
3334 if($this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit) {
3335 return true;
3336 }
3337 return false;
3338 }
3339
3340 /**
3341 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3342 * Fills $this->mDoubleUnderscores, returns the modified text
3343 */
3344 function doDoubleUnderscore( $text ) {
3345 // The position of __TOC__ needs to be recorded
3346 $mw = MagicWord::get( 'toc' );
3347 if( $mw->match( $text ) ) {
3348 $this->mShowToc = true;
3349 $this->mForceTocPosition = true;
3350
3351 // Set a placeholder. At the end we'll fill it in with the TOC.
3352 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3353
3354 // Only keep the first one.
3355 $text = $mw->replace( '', $text );
3356 }
3357
3358 // Now match and remove the rest of them
3359 $mwa = MagicWord::getDoubleUnderscoreArray();
3360 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3361
3362 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3363 $this->mOutput->mNoGallery = true;
3364 }
3365 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3366 $this->mShowToc = false;
3367 }
3368 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3369 $this->mOutput->setProperty( 'hiddencat', 'y' );
3370
3371 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( 'hidden-category-category' ) );
3372 if ( $containerCategory ) {
3373 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3374 } else {
3375 wfDebug( __METHOD__.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3376 }
3377 }
3378 return $text;
3379 }
3380
3381 /**
3382 * This function accomplishes several tasks:
3383 * 1) Auto-number headings if that option is enabled
3384 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3385 * 3) Add a Table of contents on the top for users who have enabled the option
3386 * 4) Auto-anchor headings
3387 *
3388 * It loops through all headlines, collects the necessary data, then splits up the
3389 * string and re-inserts the newly formatted headlines.
3390 *
3391 * @param string $text
3392 * @param boolean $isMain
3393 * @private
3394 */
3395 function formatHeadings( $text, $isMain=true ) {
3396 global $wgMaxTocLevel, $wgContLang;
3397
3398 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3399 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3400 $showEditLink = 0;
3401 } else {
3402 $showEditLink = $this->mOptions->getEditSection();
3403 }
3404
3405 # Inhibit editsection links if requested in the page
3406 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3407 $showEditLink = 0;
3408 }
3409
3410 # Get all headlines for numbering them and adding funky stuff like [edit]
3411 # links - this is for later, but we need the number of headlines right now
3412 $matches = array();
3413 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3414
3415 # if there are fewer than 4 headlines in the article, do not show TOC
3416 # unless it's been explicitly enabled.
3417 $enoughToc = $this->mShowToc &&
3418 (($numMatches >= 4) || $this->mForceTocPosition);
3419
3420 # Allow user to stipulate that a page should have a "new section"
3421 # link added via __NEWSECTIONLINK__
3422 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3423 $this->mOutput->setNewSection( true );
3424 }
3425
3426 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3427 # override above conditions and always show TOC above first header
3428 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3429 $this->mShowToc = true;
3430 $enoughToc = true;
3431 }
3432
3433 # We need this to perform operations on the HTML
3434 $sk = $this->mOptions->getSkin();
3435
3436 # headline counter
3437 $headlineCount = 0;
3438 $numVisible = 0;
3439
3440 # Ugh .. the TOC should have neat indentation levels which can be
3441 # passed to the skin functions. These are determined here
3442 $toc = '';
3443 $full = '';
3444 $head = array();
3445 $sublevelCount = array();
3446 $levelCount = array();
3447 $toclevel = 0;
3448 $level = 0;
3449 $prevlevel = 0;
3450 $toclevel = 0;
3451 $prevtoclevel = 0;
3452 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3453 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3454 $tocraw = array();
3455
3456 foreach( $matches[3] as $headline ) {
3457 $isTemplate = false;
3458 $titleText = false;
3459 $sectionIndex = false;
3460 $numbering = '';
3461 $markerMatches = array();
3462 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3463 $serial = $markerMatches[1];
3464 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3465 $isTemplate = ($titleText != $baseTitleText);
3466 $headline = preg_replace("/^$markerRegex/", "", $headline);
3467 }
3468
3469 if( $toclevel ) {
3470 $prevlevel = $level;
3471 $prevtoclevel = $toclevel;
3472 }
3473 $level = $matches[1][$headlineCount];
3474
3475 if( $doNumberHeadings || $enoughToc ) {
3476
3477 if ( $level > $prevlevel ) {
3478 # Increase TOC level
3479 $toclevel++;
3480 $sublevelCount[$toclevel] = 0;
3481 if( $toclevel<$wgMaxTocLevel ) {
3482 $prevtoclevel = $toclevel;
3483 $toc .= $sk->tocIndent();
3484 $numVisible++;
3485 }
3486 }
3487 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3488 # Decrease TOC level, find level to jump to
3489
3490 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3491 # Can only go down to level 1
3492 $toclevel = 1;
3493 } else {
3494 for ($i = $toclevel; $i > 0; $i--) {
3495 if ( $levelCount[$i] == $level ) {
3496 # Found last matching level
3497 $toclevel = $i;
3498 break;
3499 }
3500 elseif ( $levelCount[$i] < $level ) {
3501 # Found first matching level below current level
3502 $toclevel = $i + 1;
3503 break;
3504 }
3505 }
3506 }
3507 if( $toclevel<$wgMaxTocLevel ) {
3508 if($prevtoclevel < $wgMaxTocLevel) {
3509 # Unindent only if the previous toc level was shown :p
3510 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3511 $prevtoclevel = $toclevel;
3512 } else {
3513 $toc .= $sk->tocLineEnd();
3514 }
3515 }
3516 }
3517 else {
3518 # No change in level, end TOC line
3519 if( $toclevel<$wgMaxTocLevel ) {
3520 $toc .= $sk->tocLineEnd();
3521 }
3522 }
3523
3524 $levelCount[$toclevel] = $level;
3525
3526 # count number of headlines for each level
3527 @$sublevelCount[$toclevel]++;
3528 $dot = 0;
3529 for( $i = 1; $i <= $toclevel; $i++ ) {
3530 if( !empty( $sublevelCount[$i] ) ) {
3531 if( $dot ) {
3532 $numbering .= '.';
3533 }
3534 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3535 $dot = 1;
3536 }
3537 }
3538 }
3539
3540 # The safe header is a version of the header text safe to use for links
3541 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3542 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3543
3544 # Remove link placeholders by the link text.
3545 # <!--LINK number-->
3546 # turns into
3547 # link text with suffix
3548 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3549 "\$this->mLinkHolders['texts'][\$1]",
3550 $safeHeadline );
3551 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3552 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3553 $safeHeadline );
3554
3555 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3556 $tocline = preg_replace(
3557 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3558 array( '', '<$1>'),
3559 $safeHeadline
3560 );
3561 $tocline = trim( $tocline );
3562
3563 # For the anchor, strip out HTML-y stuff period
3564 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3565 $safeHeadline = trim( $safeHeadline );
3566
3567 # Save headline for section edit hint before it's escaped
3568 $headlineHint = $safeHeadline;
3569 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3570 # HTML names must be case-insensitively unique (bug 10721)
3571 $arrayKey = strtolower( $safeHeadline );
3572
3573 # count how many in assoc. array so we can track dupes in anchors
3574 isset( $refers[$arrayKey] ) ? $refers[$arrayKey]++ : $refers[$arrayKey] = 1;
3575 $refcount[$headlineCount] = $refers[$arrayKey];
3576
3577 # Don't number the heading if it is the only one (looks silly)
3578 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3579 # the two are different if the line contains a link
3580 $headline=$numbering . ' ' . $headline;
3581 }
3582
3583 # Create the anchor for linking from the TOC to the section
3584 $anchor = $safeHeadline;
3585 if($refcount[$headlineCount] > 1 ) {
3586 $anchor .= '_' . $refcount[$headlineCount];
3587 }
3588 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3589 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3590 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3591 }
3592 # give headline the correct <h#> tag
3593 if( $showEditLink && $sectionIndex !== false ) {
3594 if( $isTemplate ) {
3595 # Put a T flag in the section identifier, to indicate to extractSections()
3596 # that sections inside <includeonly> should be counted.
3597 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
3598 } else {
3599 $editlink = $sk->editSectionLink($this->mTitle, $sectionIndex, $headlineHint);
3600 }
3601 } else {
3602 $editlink = '';
3603 }
3604 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3605
3606 $headlineCount++;
3607 }
3608
3609 $this->mOutput->setSections( $tocraw );
3610
3611 # Never ever show TOC if no headers
3612 if( $numVisible < 1 ) {
3613 $enoughToc = false;
3614 }
3615
3616 if( $enoughToc ) {
3617 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3618 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3619 }
3620 $toc = $sk->tocList( $toc );
3621 }
3622
3623 # split up and insert constructed headlines
3624
3625 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3626 $i = 0;
3627
3628 foreach( $blocks as $block ) {
3629 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3630 # This is the [edit] link that appears for the top block of text when
3631 # section editing is enabled
3632
3633 # Disabled because it broke block formatting
3634 # For example, a bullet point in the top line
3635 # $full .= $sk->editSectionLink(0);
3636 }
3637 $full .= $block;
3638 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3639 # Top anchor now in skin
3640 $full = $full.$toc;
3641 }
3642
3643 if( !empty( $head[$i] ) ) {
3644 $full .= $head[$i];
3645 }
3646 $i++;
3647 }
3648 if( $this->mForceTocPosition ) {
3649 return str_replace( '<!--MWTOC-->', $toc, $full );
3650 } else {
3651 return $full;
3652 }
3653 }
3654
3655 /**
3656 * Transform wiki markup when saving a page by doing \r\n -> \n
3657 * conversion, substitting signatures, {{subst:}} templates, etc.
3658 *
3659 * @param string $text the text to transform
3660 * @param Title &$title the Title object for the current article
3661 * @param User &$user the User object describing the current user
3662 * @param ParserOptions $options parsing options
3663 * @param bool $clearState whether to clear the parser state first
3664 * @return string the altered wiki markup
3665 * @public
3666 */
3667 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3668 $this->mOptions = $options;
3669 $this->setTitle( $title );
3670 $this->setOutputType( self::OT_WIKI );
3671
3672 if ( $clearState ) {
3673 $this->clearState();
3674 }
3675
3676 $pairs = array(
3677 "\r\n" => "\n",
3678 );
3679 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3680 $text = $this->pstPass2( $text, $user );
3681 $text = $this->mStripState->unstripBoth( $text );
3682 return $text;
3683 }
3684
3685 /**
3686 * Pre-save transform helper function
3687 * @private
3688 */
3689 function pstPass2( $text, $user ) {
3690 global $wgContLang, $wgLocaltimezone;
3691
3692 /* Note: This is the timestamp saved as hardcoded wikitext to
3693 * the database, we use $wgContLang here in order to give
3694 * everyone the same signature and use the default one rather
3695 * than the one selected in each user's preferences.
3696 *
3697 * (see also bug 12815)
3698 */
3699 $ts = $this->mOptions->getTimestamp();
3700 $tz = 'UTC';
3701 if ( isset( $wgLocaltimezone ) ) {
3702 $unixts = wfTimestamp( TS_UNIX, $ts );
3703 $oldtz = getenv( 'TZ' );
3704 putenv( 'TZ='.$wgLocaltimezone );
3705 $ts = date( 'YmdHis', $unixts );
3706 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3707 putenv( 'TZ='.$oldtz );
3708 }
3709 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3710
3711 # Variable replacement
3712 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3713 $text = $this->replaceVariables( $text );
3714
3715 # Signatures
3716 $sigText = $this->getUserSig( $user );
3717 $text = strtr( $text, array(
3718 '~~~~~' => $d,
3719 '~~~~' => "$sigText $d",
3720 '~~~' => $sigText
3721 ) );
3722
3723 # Context links: [[|name]] and [[name (context)|]]
3724 #
3725 global $wgLegalTitleChars;
3726 $tc = "[$wgLegalTitleChars]";
3727 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3728
3729 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3730 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3731 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3732
3733 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3734 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3735 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3736
3737 $t = $this->mTitle->getText();
3738 $m = array();
3739 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3740 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3741 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3742 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3743 } else {
3744 # if there's no context, don't bother duplicating the title
3745 $text = preg_replace( $p2, '[[\\1]]', $text );
3746 }
3747
3748 # Trim trailing whitespace
3749 $text = rtrim( $text );
3750
3751 return $text;
3752 }
3753
3754 /**
3755 * Fetch the user's signature text, if any, and normalize to
3756 * validated, ready-to-insert wikitext.
3757 *
3758 * @param User $user
3759 * @return string
3760 * @private
3761 */
3762 function getUserSig( &$user ) {
3763 global $wgMaxSigChars;
3764
3765 $username = $user->getName();
3766 $nickname = $user->getOption( 'nickname' );
3767 $nickname = $nickname === '' ? $username : $nickname;
3768
3769 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3770 $nickname = $username;
3771 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
3772 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3773 # Sig. might contain markup; validate this
3774 if( $this->validateSig( $nickname ) !== false ) {
3775 # Validated; clean up (if needed) and return it
3776 return $this->cleanSig( $nickname, true );
3777 } else {
3778 # Failed to validate; fall back to the default
3779 $nickname = $username;
3780 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3781 }
3782 }
3783
3784 // Make sure nickname doesnt get a sig in a sig
3785 $nickname = $this->cleanSigInSig( $nickname );
3786
3787 # If we're still here, make it a link to the user page
3788 $userText = wfEscapeWikiText( $username );
3789 $nickText = wfEscapeWikiText( $nickname );
3790 if ( $user->isAnon() ) {
3791 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3792 } else {
3793 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3794 }
3795 }
3796
3797 /**
3798 * Check that the user's signature contains no bad XML
3799 *
3800 * @param string $text
3801 * @return mixed An expanded string, or false if invalid.
3802 */
3803 function validateSig( $text ) {
3804 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3805 }
3806
3807 /**
3808 * Clean up signature text
3809 *
3810 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3811 * 2) Substitute all transclusions
3812 *
3813 * @param string $text
3814 * @param $parsing Whether we're cleaning (preferences save) or parsing
3815 * @return string Signature text
3816 */
3817 function cleanSig( $text, $parsing = false ) {
3818 if ( !$parsing ) {
3819 global $wgTitle;
3820 $this->clearState();
3821 $this->setTitle( $wgTitle );
3822 $this->mOptions = new ParserOptions;
3823 $this->setOutputType = self::OT_PREPROCESS;
3824 }
3825
3826 # FIXME: regex doesn't respect extension tags or nowiki
3827 # => Move this logic to braceSubstitution()
3828 $substWord = MagicWord::get( 'subst' );
3829 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3830 $substText = '{{' . $substWord->getSynonym( 0 );
3831
3832 $text = preg_replace( $substRegex, $substText, $text );
3833 $text = $this->cleanSigInSig( $text );
3834 $dom = $this->preprocessToDom( $text );
3835 $frame = $this->getPreprocessor()->newFrame();
3836 $text = $frame->expand( $dom );
3837
3838 if ( !$parsing ) {
3839 $text = $this->mStripState->unstripBoth( $text );
3840 }
3841
3842 return $text;
3843 }
3844
3845 /**
3846 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3847 * @param string $text
3848 * @return string Signature text with /~{3,5}/ removed
3849 */
3850 function cleanSigInSig( $text ) {
3851 $text = preg_replace( '/~{3,5}/', '', $text );
3852 return $text;
3853 }
3854
3855 /**
3856 * Set up some variables which are usually set up in parse()
3857 * so that an external function can call some class members with confidence
3858 * @public
3859 */
3860 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3861 $this->setTitle( $title );
3862 $this->mOptions = $options;
3863 $this->setOutputType( $outputType );
3864 if ( $clearState ) {
3865 $this->clearState();
3866 }
3867 }
3868
3869 /**
3870 * Wrapper for preprocess()
3871 *
3872 * @param string $text the text to preprocess
3873 * @param ParserOptions $options options
3874 * @return string
3875 * @public
3876 */
3877 function transformMsg( $text, $options ) {
3878 global $wgTitle;
3879 static $executing = false;
3880
3881 $fname = "Parser::transformMsg";
3882
3883 # Guard against infinite recursion
3884 if ( $executing ) {
3885 return $text;
3886 }
3887 $executing = true;
3888
3889 wfProfileIn($fname);
3890 $text = $this->preprocess( $text, $wgTitle, $options );
3891
3892 $executing = false;
3893 wfProfileOut($fname);
3894 return $text;
3895 }
3896
3897 /**
3898 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3899 * The callback should have the following form:
3900 * function myParserHook( $text, $params, &$parser ) { ... }
3901 *
3902 * Transform and return $text. Use $parser for any required context, e.g. use
3903 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3904 *
3905 * @public
3906 *
3907 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3908 * @param mixed $callback The callback function (and object) to use for the tag
3909 *
3910 * @return The old value of the mTagHooks array associated with the hook
3911 */
3912 function setHook( $tag, $callback ) {
3913 $tag = strtolower( $tag );
3914 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
3915 $this->mTagHooks[$tag] = $callback;
3916 if( !in_array( $tag, $this->mStripList ) ) {
3917 $this->mStripList[] = $tag;
3918 }
3919
3920 return $oldVal;
3921 }
3922
3923 function setTransparentTagHook( $tag, $callback ) {
3924 $tag = strtolower( $tag );
3925 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
3926 $this->mTransparentTagHooks[$tag] = $callback;
3927
3928 return $oldVal;
3929 }
3930
3931 /**
3932 * Remove all tag hooks
3933 */
3934 function clearTagHooks() {
3935 $this->mTagHooks = array();
3936 $this->mStripList = $this->mDefaultStripList;
3937 }
3938
3939 /**
3940 * Create a function, e.g. {{sum:1|2|3}}
3941 * The callback function should have the form:
3942 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3943 *
3944 * The callback may either return the text result of the function, or an array with the text
3945 * in element 0, and a number of flags in the other elements. The names of the flags are
3946 * specified in the keys. Valid flags are:
3947 * found The text returned is valid, stop processing the template. This
3948 * is on by default.
3949 * nowiki Wiki markup in the return value should be escaped
3950 * isHTML The returned text is HTML, armour it against wikitext transformation
3951 *
3952 * @public
3953 *
3954 * @param string $id The magic word ID
3955 * @param mixed $callback The callback function (and object) to use
3956 * @param integer $flags a combination of the following flags:
3957 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3958 *
3959 * @return The old callback function for this name, if any
3960 */
3961 function setFunctionHook( $id, $callback, $flags = 0 ) {
3962 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
3963 $this->mFunctionHooks[$id] = array( $callback, $flags );
3964
3965 # Add to function cache
3966 $mw = MagicWord::get( $id );
3967 if( !$mw )
3968 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
3969
3970 $synonyms = $mw->getSynonyms();
3971 $sensitive = intval( $mw->isCaseSensitive() );
3972
3973 foreach ( $synonyms as $syn ) {
3974 # Case
3975 if ( !$sensitive ) {
3976 $syn = strtolower( $syn );
3977 }
3978 # Add leading hash
3979 if ( !( $flags & SFH_NO_HASH ) ) {
3980 $syn = '#' . $syn;
3981 }
3982 # Remove trailing colon
3983 if ( substr( $syn, -1, 1 ) == ':' ) {
3984 $syn = substr( $syn, 0, -1 );
3985 }
3986 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
3987 }
3988 return $oldVal;
3989 }
3990
3991 /**
3992 * Get all registered function hook identifiers
3993 *
3994 * @return array
3995 */
3996 function getFunctionHooks() {
3997 return array_keys( $this->mFunctionHooks );
3998 }
3999
4000 /**
4001 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4002 * Placeholders created in Skin::makeLinkObj()
4003 * Returns an array of link CSS classes, indexed by PDBK.
4004 * $options is a bit field, RLH_FOR_UPDATE to select for update
4005 */
4006 function replaceLinkHolders( &$text, $options = 0 ) {
4007 global $wgUser;
4008 global $wgContLang;
4009
4010 $fname = 'Parser::replaceLinkHolders';
4011 wfProfileIn( $fname );
4012
4013 $pdbks = array();
4014 $colours = array();
4015 $linkcolour_ids = array();
4016 $sk = $this->mOptions->getSkin();
4017 $linkCache = LinkCache::singleton();
4018
4019 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
4020 wfProfileIn( $fname.'-check' );
4021 $dbr = wfGetDB( DB_SLAVE );
4022 $page = $dbr->tableName( 'page' );
4023 $threshold = $wgUser->getOption('stubthreshold');
4024
4025 # Sort by namespace
4026 asort( $this->mLinkHolders['namespaces'] );
4027
4028 # Generate query
4029 $query = false;
4030 $current = null;
4031 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4032 # Make title object
4033 $title = $this->mLinkHolders['titles'][$key];
4034
4035 # Skip invalid entries.
4036 # Result will be ugly, but prevents crash.
4037 if ( is_null( $title ) ) {
4038 continue;
4039 }
4040 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4041
4042 # Check if it's a static known link, e.g. interwiki
4043 if ( $title->isAlwaysKnown() ) {
4044 $colours[$pdbk] = '';
4045 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4046 $colours[$pdbk] = '';
4047 $this->mOutput->addLink( $title, $id );
4048 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4049 $colours[$pdbk] = 'new';
4050 } elseif ( $title->getNamespace() == NS_SPECIAL && !SpecialPage::exists( $pdbk ) ) {
4051 $colours[$pdbk] = 'new';
4052 } else {
4053 # Not in the link cache, add it to the query
4054 if ( !isset( $current ) ) {
4055 $current = $ns;
4056 $query = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
4057 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4058 } elseif ( $current != $ns ) {
4059 $current = $ns;
4060 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4061 } else {
4062 $query .= ', ';
4063 }
4064
4065 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
4066 }
4067 }
4068 if ( $query ) {
4069 $query .= '))';
4070 if ( $options & RLH_FOR_UPDATE ) {
4071 $query .= ' FOR UPDATE';
4072 }
4073
4074 $res = $dbr->query( $query, $fname );
4075
4076 # Fetch data and form into an associative array
4077 # non-existent = broken
4078 while ( $s = $dbr->fetchObject($res) ) {
4079 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
4080 $pdbk = $title->getPrefixedDBkey();
4081 $linkCache->addGoodLinkObj( $s->page_id, $title, $s->page_len, $s->page_is_redirect );
4082 $this->mOutput->addLink( $title, $s->page_id );
4083 $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
4084 //add id to the extension todolist
4085 $linkcolour_ids[$s->page_id] = $pdbk;
4086 }
4087 //pass an array of page_ids to an extension
4088 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4089 }
4090 wfProfileOut( $fname.'-check' );
4091
4092 # Do a second query for different language variants of links and categories
4093 if($wgContLang->hasVariants()){
4094 $linkBatch = new LinkBatch();
4095 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4096 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4097 $varCategories = array(); // category replacements oldDBkey => newDBkey
4098
4099 $categories = $this->mOutput->getCategoryLinks();
4100
4101 // Add variants of links to link batch
4102 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4103 $title = $this->mLinkHolders['titles'][$key];
4104 if ( is_null( $title ) )
4105 continue;
4106
4107 $pdbk = $title->getPrefixedDBkey();
4108 $titleText = $title->getText();
4109
4110 // generate all variants of the link title text
4111 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4112
4113 // if link was not found (in first query), add all variants to query
4114 if ( !isset($colours[$pdbk]) ){
4115 foreach($allTextVariants as $textVariant){
4116 if($textVariant != $titleText){
4117 $variantTitle = Title::makeTitle( $ns, $textVariant );
4118 if(is_null($variantTitle)) continue;
4119 $linkBatch->addObj( $variantTitle );
4120 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4121 }
4122 }
4123 }
4124 }
4125
4126 // process categories, check if a category exists in some variant
4127 foreach( $categories as $category ){
4128 $variants = $wgContLang->convertLinkToAllVariants($category);
4129 foreach($variants as $variant){
4130 if($variant != $category){
4131 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
4132 if(is_null($variantTitle)) continue;
4133 $linkBatch->addObj( $variantTitle );
4134 $categoryMap[$variant] = $category;
4135 }
4136 }
4137 }
4138
4139
4140 if(!$linkBatch->isEmpty()){
4141 // construct query
4142 $titleClause = $linkBatch->constructSet('page', $dbr);
4143
4144 $variantQuery = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
4145
4146 $variantQuery .= " FROM $page WHERE $titleClause";
4147 if ( $options & RLH_FOR_UPDATE ) {
4148 $variantQuery .= ' FOR UPDATE';
4149 }
4150
4151 $varRes = $dbr->query( $variantQuery, $fname );
4152
4153 // for each found variants, figure out link holders and replace
4154 while ( $s = $dbr->fetchObject($varRes) ) {
4155
4156 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4157 $varPdbk = $variantTitle->getPrefixedDBkey();
4158 $vardbk = $variantTitle->getDBkey();
4159
4160 $holderKeys = array();
4161 if(isset($variantMap[$varPdbk])){
4162 $holderKeys = $variantMap[$varPdbk];
4163 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle, $s->page_len, $s->page_is_redirect );
4164 $this->mOutput->addLink( $variantTitle, $s->page_id );
4165 }
4166
4167 // loop over link holders
4168 foreach($holderKeys as $key){
4169 $title = $this->mLinkHolders['titles'][$key];
4170 if ( is_null( $title ) ) continue;
4171
4172 $pdbk = $title->getPrefixedDBkey();
4173
4174 if(!isset($colours[$pdbk])){
4175 // found link in some of the variants, replace the link holder data
4176 $this->mLinkHolders['titles'][$key] = $variantTitle;
4177 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4178
4179 // set pdbk and colour
4180 $pdbks[$key] = $varPdbk;
4181 $colours[$varPdbk] = $sk->getLinkColour( $variantTitle, $threshold );
4182 $linkcolour_ids[$s->page_id] = $pdbk;
4183 }
4184 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4185 }
4186
4187 // check if the object is a variant of a category
4188 if(isset($categoryMap[$vardbk])){
4189 $oldkey = $categoryMap[$vardbk];
4190 if($oldkey != $vardbk)
4191 $varCategories[$oldkey]=$vardbk;
4192 }
4193 }
4194
4195 // rebuild the categories in original order (if there are replacements)
4196 if(count($varCategories)>0){
4197 $newCats = array();
4198 $originalCats = $this->mOutput->getCategories();
4199 foreach($originalCats as $cat => $sortkey){
4200 // make the replacement
4201 if( array_key_exists($cat,$varCategories) )
4202 $newCats[$varCategories[$cat]] = $sortkey;
4203 else $newCats[$cat] = $sortkey;
4204 }
4205 $this->mOutput->setCategoryLinks($newCats);
4206 }
4207 }
4208 }
4209
4210 # Construct search and replace arrays
4211 wfProfileIn( $fname.'-construct' );
4212 $replacePairs = array();
4213 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4214 $pdbk = $pdbks[$key];
4215 $searchkey = "<!--LINK $key-->";
4216 $title = $this->mLinkHolders['titles'][$key];
4217 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] == 'new' ) {
4218 $linkCache->addBadLinkObj( $title );
4219 $colours[$pdbk] = 'new';
4220 $this->mOutput->addLink( $title, 0 );
4221 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4222 $this->mLinkHolders['texts'][$key],
4223 $this->mLinkHolders['queries'][$key] );
4224 } else {
4225 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4226 $this->mLinkHolders['texts'][$key],
4227 $this->mLinkHolders['queries'][$key] );
4228 }
4229 }
4230 $replacer = new HashtableReplacer( $replacePairs, 1 );
4231 wfProfileOut( $fname.'-construct' );
4232
4233 # Do the thing
4234 wfProfileIn( $fname.'-replace' );
4235 $text = preg_replace_callback(
4236 '/(<!--LINK .*?-->)/',
4237 $replacer->cb(),
4238 $text);
4239
4240 wfProfileOut( $fname.'-replace' );
4241 }
4242
4243 # Now process interwiki link holders
4244 # This is quite a bit simpler than internal links
4245 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4246 wfProfileIn( $fname.'-interwiki' );
4247 # Make interwiki link HTML
4248 $replacePairs = array();
4249 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4250 $title = $this->mInterwikiLinkHolders['titles'][$key];
4251 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4252 }
4253 $replacer = new HashtableReplacer( $replacePairs, 1 );
4254
4255 $text = preg_replace_callback(
4256 '/<!--IWLINK (.*?)-->/',
4257 $replacer->cb(),
4258 $text );
4259 wfProfileOut( $fname.'-interwiki' );
4260 }
4261
4262 wfProfileOut( $fname );
4263 return $colours;
4264 }
4265
4266 /**
4267 * Replace <!--LINK--> link placeholders with plain text of links
4268 * (not HTML-formatted).
4269 * @param string $text
4270 * @return string
4271 */
4272 function replaceLinkHoldersText( $text ) {
4273 $fname = 'Parser::replaceLinkHoldersText';
4274 wfProfileIn( $fname );
4275
4276 $text = preg_replace_callback(
4277 '/<!--(LINK|IWLINK) (.*?)-->/',
4278 array( &$this, 'replaceLinkHoldersTextCallback' ),
4279 $text );
4280
4281 wfProfileOut( $fname );
4282 return $text;
4283 }
4284
4285 /**
4286 * @param array $matches
4287 * @return string
4288 * @private
4289 */
4290 function replaceLinkHoldersTextCallback( $matches ) {
4291 $type = $matches[1];
4292 $key = $matches[2];
4293 if( $type == 'LINK' ) {
4294 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4295 return $this->mLinkHolders['texts'][$key];
4296 }
4297 } elseif( $type == 'IWLINK' ) {
4298 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4299 return $this->mInterwikiLinkHolders['texts'][$key];
4300 }
4301 }
4302 return $matches[0];
4303 }
4304
4305 /**
4306 * Tag hook handler for 'pre'.
4307 */
4308 function renderPreTag( $text, $attribs ) {
4309 // Backwards-compatibility hack
4310 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4311
4312 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4313 return wfOpenElement( 'pre', $attribs ) .
4314 Xml::escapeTagsOnly( $content ) .
4315 '</pre>';
4316 }
4317
4318 /**
4319 * Renders an image gallery from a text with one line per image.
4320 * text labels may be given by using |-style alternative text. E.g.
4321 * Image:one.jpg|The number "1"
4322 * Image:tree.jpg|A tree
4323 * given as text will return the HTML of a gallery with two images,
4324 * labeled 'The number "1"' and
4325 * 'A tree'.
4326 */
4327 function renderImageGallery( $text, $params ) {
4328 $ig = new ImageGallery();
4329 $ig->setContextTitle( $this->mTitle );
4330 $ig->setShowBytes( false );
4331 $ig->setShowFilename( false );
4332 $ig->setParser( $this );
4333 $ig->setHideBadImages();
4334 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4335 $ig->useSkin( $this->mOptions->getSkin() );
4336 $ig->mRevisionId = $this->mRevisionId;
4337
4338 if( isset( $params['caption'] ) ) {
4339 $caption = $params['caption'];
4340 $caption = htmlspecialchars( $caption );
4341 $caption = $this->replaceInternalLinks( $caption );
4342 $ig->setCaptionHtml( $caption );
4343 }
4344 if( isset( $params['perrow'] ) ) {
4345 $ig->setPerRow( $params['perrow'] );
4346 }
4347 if( isset( $params['widths'] ) ) {
4348 $ig->setWidths( $params['widths'] );
4349 }
4350 if( isset( $params['heights'] ) ) {
4351 $ig->setHeights( $params['heights'] );
4352 }
4353
4354 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4355
4356 $lines = explode( "\n", $text );
4357 foreach ( $lines as $line ) {
4358 # match lines like these:
4359 # Image:someimage.jpg|This is some image
4360 $matches = array();
4361 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4362 # Skip empty lines
4363 if ( count( $matches ) == 0 ) {
4364 continue;
4365 }
4366
4367 if ( strpos( $matches[0], '%' ) !== false )
4368 $matches[1] = urldecode( $matches[1] );
4369 $tp = Title::newFromText( $matches[1] );
4370 $nt =& $tp;
4371 if( is_null( $nt ) ) {
4372 # Bogus title. Ignore these so we don't bomb out later.
4373 continue;
4374 }
4375 if ( isset( $matches[3] ) ) {
4376 $label = $matches[3];
4377 } else {
4378 $label = '';
4379 }
4380
4381 $html = $this->recursiveTagParse( trim( $label ) );
4382
4383 $ig->add( $nt, $html );
4384
4385 # Only add real images (bug #5586)
4386 if ( $nt->getNamespace() == NS_IMAGE ) {
4387 $this->mOutput->addImage( $nt->getDBkey() );
4388 }
4389 }
4390 return $ig->toHTML();
4391 }
4392
4393 function getImageParams( $handler ) {
4394 if ( $handler ) {
4395 $handlerClass = get_class( $handler );
4396 } else {
4397 $handlerClass = '';
4398 }
4399 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4400 // Initialise static lists
4401 static $internalParamNames = array(
4402 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4403 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4404 'bottom', 'text-bottom' ),
4405 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4406 'upright', 'border' ),
4407 );
4408 static $internalParamMap;
4409 if ( !$internalParamMap ) {
4410 $internalParamMap = array();
4411 foreach ( $internalParamNames as $type => $names ) {
4412 foreach ( $names as $name ) {
4413 $magicName = str_replace( '-', '_', "img_$name" );
4414 $internalParamMap[$magicName] = array( $type, $name );
4415 }
4416 }
4417 }
4418
4419 // Add handler params
4420 $paramMap = $internalParamMap;
4421 if ( $handler ) {
4422 $handlerParamMap = $handler->getParamMap();
4423 foreach ( $handlerParamMap as $magic => $paramName ) {
4424 $paramMap[$magic] = array( 'handler', $paramName );
4425 }
4426 }
4427 $this->mImageParams[$handlerClass] = $paramMap;
4428 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4429 }
4430 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4431 }
4432
4433 /**
4434 * Parse image options text and use it to make an image
4435 */
4436 function makeImage( $title, $options ) {
4437 # Check if the options text is of the form "options|alt text"
4438 # Options are:
4439 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4440 # * left no resizing, just left align. label is used for alt= only
4441 # * right same, but right aligned
4442 # * none same, but not aligned
4443 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4444 # * center center the image
4445 # * framed Keep original image size, no magnify-button.
4446 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4447 # * upright reduce width for upright images, rounded to full __0 px
4448 # * border draw a 1px border around the image
4449 # vertical-align values (no % or length right now):
4450 # * baseline
4451 # * sub
4452 # * super
4453 # * top
4454 # * text-top
4455 # * middle
4456 # * bottom
4457 # * text-bottom
4458
4459 $parts = array_map( 'trim', explode( '|', $options) );
4460 $sk = $this->mOptions->getSkin();
4461
4462 # Give extensions a chance to select the file revision for us
4463 $skip = $time = $descQuery = false;
4464 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4465
4466 if ( $skip ) {
4467 return $sk->makeLinkObj( $title );
4468 }
4469
4470 # Get parameter map
4471 $file = wfFindFile( $title, $time );
4472 $handler = $file ? $file->getHandler() : false;
4473
4474 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4475
4476 # Process the input parameters
4477 $caption = '';
4478 $params = array( 'frame' => array(), 'handler' => array(),
4479 'horizAlign' => array(), 'vertAlign' => array() );
4480 foreach( $parts as $part ) {
4481 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4482 $validated = false;
4483 if( isset( $paramMap[$magicName] ) ) {
4484 list( $type, $paramName ) = $paramMap[$magicName];
4485
4486 // Special case; width and height come in one variable together
4487 if( $type == 'handler' && $paramName == 'width' ) {
4488 $m = array();
4489 # (bug 13500) In both cases (width/height and width only),
4490 # permit trailing "px" for backward compatibility.
4491 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4492 $width = intval( $m[1] );
4493 $height = intval( $m[2] );
4494 if ( $handler->validateParam( 'width', $width ) ) {
4495 $params[$type]['width'] = $width;
4496 $validated = true;
4497 }
4498 if ( $handler->validateParam( 'height', $height ) ) {
4499 $params[$type]['height'] = $height;
4500 $validated = true;
4501 }
4502 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4503 $width = intval( $value );
4504 if ( $handler->validateParam( 'width', $width ) ) {
4505 $params[$type]['width'] = $width;
4506 $validated = true;
4507 }
4508 } // else no validation -- bug 13436
4509 } else {
4510 if ( $type == 'handler' ) {
4511 # Validate handler parameter
4512 $validated = $handler->validateParam( $paramName, $value );
4513 } else {
4514 # Validate internal parameters
4515 switch( $paramName ) {
4516 case "manualthumb":
4517 /// @fixme - possibly check validity here?
4518 /// downstream behavior seems odd with missing manual thumbs.
4519 $validated = true;
4520 break;
4521 default:
4522 // Most other things appear to be empty or numeric...
4523 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4524 }
4525 }
4526
4527 if ( $validated ) {
4528 $params[$type][$paramName] = $value;
4529 }
4530 }
4531 }
4532 if ( !$validated ) {
4533 $caption = $part;
4534 }
4535 }
4536
4537 # Process alignment parameters
4538 if ( $params['horizAlign'] ) {
4539 $params['frame']['align'] = key( $params['horizAlign'] );
4540 }
4541 if ( $params['vertAlign'] ) {
4542 $params['frame']['valign'] = key( $params['vertAlign'] );
4543 }
4544
4545 # Strip bad stuff out of the alt text
4546 $alt = $this->replaceLinkHoldersText( $caption );
4547
4548 # make sure there are no placeholders in thumbnail attributes
4549 # that are later expanded to html- so expand them now and
4550 # remove the tags
4551 $alt = $this->mStripState->unstripBoth( $alt );
4552 $alt = Sanitizer::stripAllTags( $alt );
4553
4554 $params['frame']['alt'] = $alt;
4555 $params['frame']['caption'] = $caption;
4556
4557 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4558
4559 # Linker does the rest
4560 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4561
4562 # Give the handler a chance to modify the parser object
4563 if ( $handler ) {
4564 $handler->parserTransformHook( $this, $file );
4565 }
4566
4567 return $ret;
4568 }
4569
4570 /**
4571 * Set a flag in the output object indicating that the content is dynamic and
4572 * shouldn't be cached.
4573 */
4574 function disableCache() {
4575 wfDebug( "Parser output marked as uncacheable.\n" );
4576 $this->mOutput->mCacheTime = -1;
4577 }
4578
4579 /**#@+
4580 * Callback from the Sanitizer for expanding items found in HTML attribute
4581 * values, so they can be safely tested and escaped.
4582 * @param string $text
4583 * @param PPFrame $frame
4584 * @return string
4585 * @private
4586 */
4587 function attributeStripCallback( &$text, $frame = false ) {
4588 $text = $this->replaceVariables( $text, $frame );
4589 $text = $this->mStripState->unstripBoth( $text );
4590 return $text;
4591 }
4592
4593 /**#@-*/
4594
4595 /**#@+
4596 * Accessor/mutator
4597 */
4598 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4599 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4600 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4601 /**#@-*/
4602
4603 /**#@+
4604 * Accessor
4605 */
4606 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4607 /**#@-*/
4608
4609
4610 /**
4611 * Break wikitext input into sections, and either pull or replace
4612 * some particular section's text.
4613 *
4614 * External callers should use the getSection and replaceSection methods.
4615 *
4616 * @param string $text Page wikitext
4617 * @param string $section A section identifier string of the form:
4618 * <flag1> - <flag2> - ... - <section number>
4619 *
4620 * Currently the only recognised flag is "T", which means the target section number
4621 * was derived during a template inclusion parse, in other words this is a template
4622 * section edit link. If no flags are given, it was an ordinary section edit link.
4623 * This flag is required to avoid a section numbering mismatch when a section is
4624 * enclosed by <includeonly> (bug 6563).
4625 *
4626 * The section number 0 pulls the text before the first heading; other numbers will
4627 * pull the given section along with its lower-level subsections. If the section is
4628 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4629 *
4630 * @param string $mode One of "get" or "replace"
4631 * @param string $newText Replacement text for section data.
4632 * @return string for "get", the extracted section text.
4633 * for "replace", the whole page with the section replaced.
4634 */
4635 private function extractSections( $text, $section, $mode, $newText='' ) {
4636 global $wgTitle;
4637 $this->clearState();
4638 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4639 $this->mOptions = new ParserOptions;
4640 $this->setOutputType( self::OT_WIKI );
4641 $outText = '';
4642 $frame = $this->getPreprocessor()->newFrame();
4643
4644 // Process section extraction flags
4645 $flags = 0;
4646 $sectionParts = explode( '-', $section );
4647 $sectionIndex = array_pop( $sectionParts );
4648 foreach ( $sectionParts as $part ) {
4649 if ( $part == 'T' ) {
4650 $flags |= self::PTD_FOR_INCLUSION;
4651 }
4652 }
4653 // Preprocess the text
4654 $root = $this->preprocessToDom( $text, $flags );
4655
4656 // <h> nodes indicate section breaks
4657 // They can only occur at the top level, so we can find them by iterating the root's children
4658 $node = $root->getFirstChild();
4659
4660 // Find the target section
4661 if ( $sectionIndex == 0 ) {
4662 // Section zero doesn't nest, level=big
4663 $targetLevel = 1000;
4664 } else {
4665 while ( $node ) {
4666 if ( $node->getName() == 'h' ) {
4667 $bits = $node->splitHeading();
4668 if ( $bits['i'] == $sectionIndex ) {
4669 $targetLevel = $bits['level'];
4670 break;
4671 }
4672 }
4673 if ( $mode == 'replace' ) {
4674 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4675 }
4676 $node = $node->getNextSibling();
4677 }
4678 }
4679
4680 if ( !$node ) {
4681 // Not found
4682 if ( $mode == 'get' ) {
4683 return $newText;
4684 } else {
4685 return $text;
4686 }
4687 }
4688
4689 // Find the end of the section, including nested sections
4690 do {
4691 if ( $node->getName() == 'h' ) {
4692 $bits = $node->splitHeading();
4693 $curLevel = $bits['level'];
4694 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4695 break;
4696 }
4697 }
4698 if ( $mode == 'get' ) {
4699 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4700 }
4701 $node = $node->getNextSibling();
4702 } while ( $node );
4703
4704 // Write out the remainder (in replace mode only)
4705 if ( $mode == 'replace' ) {
4706 // Output the replacement text
4707 // Add two newlines on -- trailing whitespace in $newText is conventionally
4708 // stripped by the editor, so we need both newlines to restore the paragraph gap
4709 $outText .= $newText . "\n\n";
4710 while ( $node ) {
4711 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4712 $node = $node->getNextSibling();
4713 }
4714 }
4715
4716 if ( is_string( $outText ) ) {
4717 // Re-insert stripped tags
4718 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4719 }
4720
4721 return $outText;
4722 }
4723
4724 /**
4725 * This function returns the text of a section, specified by a number ($section).
4726 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4727 * the first section before any such heading (section 0).
4728 *
4729 * If a section contains subsections, these are also returned.
4730 *
4731 * @param string $text text to look in
4732 * @param string $section section identifier
4733 * @param string $deftext default to return if section is not found
4734 * @return string text of the requested section
4735 */
4736 public function getSection( $text, $section, $deftext='' ) {
4737 return $this->extractSections( $text, $section, "get", $deftext );
4738 }
4739
4740 public function replaceSection( $oldtext, $section, $text ) {
4741 return $this->extractSections( $oldtext, $section, "replace", $text );
4742 }
4743
4744 /**
4745 * Get the timestamp associated with the current revision, adjusted for
4746 * the default server-local timestamp
4747 */
4748 function getRevisionTimestamp() {
4749 if ( is_null( $this->mRevisionTimestamp ) ) {
4750 wfProfileIn( __METHOD__ );
4751 global $wgContLang;
4752 $dbr = wfGetDB( DB_SLAVE );
4753 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4754 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4755
4756 // Normalize timestamp to internal MW format for timezone processing.
4757 // This has the added side-effect of replacing a null value with
4758 // the current time, which gives us more sensible behavior for
4759 // previews.
4760 $timestamp = wfTimestamp( TS_MW, $timestamp );
4761
4762 // The cryptic '' timezone parameter tells to use the site-default
4763 // timezone offset instead of the user settings.
4764 //
4765 // Since this value will be saved into the parser cache, served
4766 // to other users, and potentially even used inside links and such,
4767 // it needs to be consistent for all visitors.
4768 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4769
4770 wfProfileOut( __METHOD__ );
4771 }
4772 return $this->mRevisionTimestamp;
4773 }
4774
4775 /**
4776 * Mutator for $mDefaultSort
4777 *
4778 * @param $sort New value
4779 */
4780 public function setDefaultSort( $sort ) {
4781 $this->mDefaultSort = $sort;
4782 }
4783
4784 /**
4785 * Accessor for $mDefaultSort
4786 * Will use the title/prefixed title if none is set
4787 *
4788 * @return string
4789 */
4790 public function getDefaultSort() {
4791 if( $this->mDefaultSort !== false ) {
4792 return $this->mDefaultSort;
4793 } else {
4794 return $this->mTitle->getNamespace() == NS_CATEGORY
4795 ? $this->mTitle->getText()
4796 : $this->mTitle->getPrefixedText();
4797 }
4798 }
4799
4800 /**
4801 * Try to guess the section anchor name based on a wikitext fragment
4802 * presumably extracted from a heading, for example "Header" from
4803 * "== Header ==".
4804 */
4805 public function guessSectionNameFromWikiText( $text ) {
4806 # Strip out wikitext links(they break the anchor)
4807 $text = $this->stripSectionName( $text );
4808 $headline = Sanitizer::decodeCharReferences( $text );
4809 # strip out HTML
4810 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
4811 $headline = trim( $headline );
4812 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4813 $replacearray = array(
4814 '%3A' => ':',
4815 '%' => '.'
4816 );
4817 return str_replace(
4818 array_keys( $replacearray ),
4819 array_values( $replacearray ),
4820 $sectionanchor );
4821 }
4822
4823 /**
4824 * Strips a text string of wikitext for use in a section anchor
4825 *
4826 * Accepts a text string and then removes all wikitext from the
4827 * string and leaves only the resultant text (i.e. the result of
4828 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4829 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4830 * to create valid section anchors by mimicing the output of the
4831 * parser when headings are parsed.
4832 *
4833 * @param $text string Text string to be stripped of wikitext
4834 * for use in a Section anchor
4835 * @return Filtered text string
4836 */
4837 public function stripSectionName( $text ) {
4838 # Strip internal link markup
4839 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4840 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4841
4842 # Strip external link markup (FIXME: Not Tolerant to blank link text
4843 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4844 # on how many empty links there are on the page - need to figure that out.
4845 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4846
4847 # Parse wikitext quotes (italics & bold)
4848 $text = $this->doQuotes($text);
4849
4850 # Strip HTML tags
4851 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
4852 return $text;
4853 }
4854
4855 function srvus( $text ) {
4856 return $this->testSrvus( $text, $this->mOutputType );
4857 }
4858
4859 /**
4860 * strip/replaceVariables/unstrip for preprocessor regression testing
4861 */
4862 function testSrvus( $text, $title, $options, $outputType = self::OT_HTML ) {
4863 $this->clearState();
4864 if ( ! ( $title instanceof Title ) ) {
4865 $title = Title::newFromText( $title );
4866 }
4867 $this->mTitle = $title;
4868 $this->mOptions = $options;
4869 $this->setOutputType( $outputType );
4870 $text = $this->replaceVariables( $text );
4871 $text = $this->mStripState->unstripBoth( $text );
4872 $text = Sanitizer::removeHTMLtags( $text );
4873 return $text;
4874 }
4875
4876 function testPst( $text, $title, $options ) {
4877 global $wgUser;
4878 if ( ! ( $title instanceof Title ) ) {
4879 $title = Title::newFromText( $title );
4880 }
4881 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4882 }
4883
4884 function testPreprocess( $text, $title, $options ) {
4885 if ( ! ( $title instanceof Title ) ) {
4886 $title = Title::newFromText( $title );
4887 }
4888 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
4889 }
4890
4891 function markerSkipCallback( $s, $callback ) {
4892 $i = 0;
4893 $out = '';
4894 while ( $i < strlen( $s ) ) {
4895 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
4896 if ( $markerStart === false ) {
4897 $out .= call_user_func( $callback, substr( $s, $i ) );
4898 break;
4899 } else {
4900 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4901 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
4902 if ( $markerEnd === false ) {
4903 $out .= substr( $s, $markerStart );
4904 break;
4905 } else {
4906 $markerEnd += strlen( self::MARKER_SUFFIX );
4907 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4908 $i = $markerEnd;
4909 }
4910 }
4911 }
4912 return $out;
4913 }
4914 }
4915
4916 /**
4917 * @todo document, briefly.
4918 * @ingroup Parser
4919 */
4920 class StripState {
4921 var $general, $nowiki;
4922
4923 function __construct() {
4924 $this->general = new ReplacementArray;
4925 $this->nowiki = new ReplacementArray;
4926 }
4927
4928 function unstripGeneral( $text ) {
4929 wfProfileIn( __METHOD__ );
4930 do {
4931 $oldText = $text;
4932 $text = $this->general->replace( $text );
4933 } while ( $text != $oldText );
4934 wfProfileOut( __METHOD__ );
4935 return $text;
4936 }
4937
4938 function unstripNoWiki( $text ) {
4939 wfProfileIn( __METHOD__ );
4940 do {
4941 $oldText = $text;
4942 $text = $this->nowiki->replace( $text );
4943 } while ( $text != $oldText );
4944 wfProfileOut( __METHOD__ );
4945 return $text;
4946 }
4947
4948 function unstripBoth( $text ) {
4949 wfProfileIn( __METHOD__ );
4950 do {
4951 $oldText = $text;
4952 $text = $this->general->replace( $text );
4953 $text = $this->nowiki->replace( $text );
4954 } while ( $text != $oldText );
4955 wfProfileOut( __METHOD__ );
4956 return $text;
4957 }
4958 }
4959
4960 /**
4961 * @todo document, briefly.
4962 * @ingroup Parser
4963 */
4964 class OnlyIncludeReplacer {
4965 var $output = '';
4966
4967 function replace( $matches ) {
4968 if ( substr( $matches[1], -1 ) == "\n" ) {
4969 $this->output .= substr( $matches[1], 0, -1 );
4970 } else {
4971 $this->output .= $matches[1];
4972 }
4973 }
4974 }