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