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