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