(bug 15555) misspelled replace_variables() function in doc of Parser::preprocessToDom...
[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 $text = '[' . ++$this->mAutonumber . ']';
1380 $linktype = 'autonumber';
1381 } else {
1382 # Otherwise just use the URL
1383 $text = htmlspecialchars( $url );
1384 $linktype = 'free';
1385 }
1386 } else {
1387 # Have link text, e.g. [http://domain.tld/some.link text]s
1388 # Check for trail
1389 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1390 }
1391
1392 $text = $wgContLang->markNoConversion($text);
1393
1394 $url = Sanitizer::cleanUrl( $url );
1395
1396 # Use the encoded URL
1397 # This means that users can paste URLs directly into the text
1398 # Funny characters like &ouml; aren't valid in URLs anyway
1399 # This was changed in August 2004
1400 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle->getNamespace() ) . $dtrail . $trail;
1401
1402 # Register link in the output object.
1403 # Replace unnecessary URL escape codes with the referenced character
1404 # This prevents spammers from hiding links from the filters
1405 $pasteurized = self::replaceUnusualEscapes( $url );
1406 $this->mOutput->addExternalLink( $pasteurized );
1407 }
1408
1409 wfProfileOut( __METHOD__ );
1410 return $s;
1411 }
1412
1413 /**
1414 * Replace unusual URL escape codes with their equivalent characters
1415 * @param string
1416 * @return string
1417 * @static
1418 * @todo This can merge genuinely required bits in the path or query string,
1419 * breaking legit URLs. A proper fix would treat the various parts of
1420 * the URL differently; as a workaround, just use the output for
1421 * statistical records, not for actual linking/output.
1422 */
1423 static function replaceUnusualEscapes( $url ) {
1424 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1425 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1426 }
1427
1428 /**
1429 * Callback function used in replaceUnusualEscapes().
1430 * Replaces unusual URL escape codes with their equivalent character
1431 * @static
1432 * @private
1433 */
1434 private static function replaceUnusualEscapesCallback( $matches ) {
1435 $char = urldecode( $matches[0] );
1436 $ord = ord( $char );
1437 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1438 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1439 // No, shouldn't be escaped
1440 return $char;
1441 } else {
1442 // Yes, leave it escaped
1443 return $matches[0];
1444 }
1445 }
1446
1447 /**
1448 * make an image if it's allowed, either through the global
1449 * option, through the exception, or through the on-wiki whitelist
1450 * @private
1451 */
1452 function maybeMakeExternalImage( $url ) {
1453 $sk = $this->mOptions->getSkin();
1454 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1455 $imagesexception = !empty($imagesfrom);
1456 $text = false;
1457 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1458 if( $imagesexception && is_array( $imagesfrom ) ) {
1459 $imagematch = false;
1460 foreach( $imagesfrom as $match ) {
1461 if( strpos( $url, $match ) === 0 ) {
1462 $imagematch = true;
1463 break;
1464 }
1465 }
1466 } elseif( $imagesexception ) {
1467 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1468 } else {
1469 $imagematch = false;
1470 }
1471 if ( $this->mOptions->getAllowExternalImages()
1472 || ( $imagesexception && $imagematch ) ) {
1473 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1474 # Image found
1475 $text = $sk->makeExternalImage( $url );
1476 }
1477 }
1478 if( !$text && $this->mOptions->getEnableImageWhitelist()
1479 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1480 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1481 foreach( $whitelist as $entry ) {
1482 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1483 if( strpos( $entry, '#' ) === 0 || $entry === '' )
1484 continue;
1485 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1486 # Image matches a whitelist entry
1487 $text = $sk->makeExternalImage( $url );
1488 break;
1489 }
1490 }
1491 }
1492 return $text;
1493 }
1494
1495 /**
1496 * Process [[ ]] wikilinks
1497 * @return processed text
1498 *
1499 * @private
1500 */
1501 function replaceInternalLinks( $s ) {
1502 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1503 return $s;
1504 }
1505
1506 /**
1507 * Process [[ ]] wikilinks (RIL)
1508 * @return LinkHolderArray
1509 *
1510 * @private
1511 */
1512 function replaceInternalLinks2( &$s ) {
1513 global $wgContLang;
1514
1515 wfProfileIn( __METHOD__ );
1516
1517 wfProfileIn( __METHOD__.'-setup' );
1518 static $tc = FALSE, $e1, $e1_img;
1519 # the % is needed to support urlencoded titles as well
1520 if ( !$tc ) {
1521 $tc = Title::legalChars() . '#%';
1522 # Match a link having the form [[namespace:link|alternate]]trail
1523 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1524 # Match cases where there is no "]]", which might still be images
1525 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1526 }
1527
1528 $sk = $this->mOptions->getSkin();
1529 $holders = new LinkHolderArray( $this );
1530
1531 #split the entire text string on occurences of [[
1532 $a = StringUtils::explode( '[[', ' ' . $s );
1533 #get the first element (all text up to first [[), and remove the space we added
1534 $s = $a->current();
1535 $a->next();
1536 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1537 $s = substr( $s, 1 );
1538
1539 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1540 $e2 = null;
1541 if ( $useLinkPrefixExtension ) {
1542 # Match the end of a line for a word that's not followed by whitespace,
1543 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1544 $e2 = wfMsgForContent( 'linkprefix' );
1545 }
1546
1547 if( is_null( $this->mTitle ) ) {
1548 wfProfileOut( __METHOD__.'-setup' );
1549 wfProfileOut( __METHOD__ );
1550 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1551 }
1552 $nottalk = !$this->mTitle->isTalkPage();
1553
1554 if ( $useLinkPrefixExtension ) {
1555 $m = array();
1556 if ( preg_match( $e2, $s, $m ) ) {
1557 $first_prefix = $m[2];
1558 } else {
1559 $first_prefix = false;
1560 }
1561 } else {
1562 $prefix = '';
1563 }
1564
1565 if($wgContLang->hasVariants()) {
1566 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1567 } else {
1568 $selflink = array($this->mTitle->getPrefixedText());
1569 }
1570 $useSubpages = $this->areSubpagesAllowed();
1571 wfProfileOut( __METHOD__.'-setup' );
1572
1573 # Loop for each link
1574 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1575 # Check for excessive memory usage
1576 if ( $holders->isBig() ) {
1577 # Too big
1578 # Do the existence check, replace the link holders and clear the array
1579 $holders->replace( $s );
1580 $holders->clear();
1581 }
1582
1583 if ( $useLinkPrefixExtension ) {
1584 wfProfileIn( __METHOD__.'-prefixhandling' );
1585 if ( preg_match( $e2, $s, $m ) ) {
1586 $prefix = $m[2];
1587 $s = $m[1];
1588 } else {
1589 $prefix='';
1590 }
1591 # first link
1592 if($first_prefix) {
1593 $prefix = $first_prefix;
1594 $first_prefix = false;
1595 }
1596 wfProfileOut( __METHOD__.'-prefixhandling' );
1597 }
1598
1599 $might_be_img = false;
1600
1601 wfProfileIn( __METHOD__."-e1" );
1602 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1603 $text = $m[2];
1604 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1605 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1606 # the real problem is with the $e1 regex
1607 # See bug 1300.
1608 #
1609 # Still some problems for cases where the ] is meant to be outside punctuation,
1610 # and no image is in sight. See bug 2095.
1611 #
1612 if( $text !== '' &&
1613 substr( $m[3], 0, 1 ) === ']' &&
1614 strpos($text, '[') !== false
1615 )
1616 {
1617 $text .= ']'; # so that replaceExternalLinks($text) works later
1618 $m[3] = substr( $m[3], 1 );
1619 }
1620 # fix up urlencoded title texts
1621 if( strpos( $m[1], '%' ) !== false ) {
1622 # Should anchors '#' also be rejected?
1623 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1624 }
1625 $trail = $m[3];
1626 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1627 $might_be_img = true;
1628 $text = $m[2];
1629 if ( strpos( $m[1], '%' ) !== false ) {
1630 $m[1] = urldecode($m[1]);
1631 }
1632 $trail = "";
1633 } else { # Invalid form; output directly
1634 $s .= $prefix . '[[' . $line ;
1635 wfProfileOut( __METHOD__."-e1" );
1636 continue;
1637 }
1638 wfProfileOut( __METHOD__."-e1" );
1639 wfProfileIn( __METHOD__."-misc" );
1640
1641 # Don't allow internal links to pages containing
1642 # PROTO: where PROTO is a valid URL protocol; these
1643 # should be external links.
1644 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1645 $s .= $prefix . '[[' . $line ;
1646 wfProfileOut( __METHOD__."-misc" );
1647 continue;
1648 }
1649
1650 # Make subpage if necessary
1651 if( $useSubpages ) {
1652 $link = $this->maybeDoSubpageLink( $m[1], $text );
1653 } else {
1654 $link = $m[1];
1655 }
1656
1657 $noforce = (substr($m[1], 0, 1) !== ':');
1658 if (!$noforce) {
1659 # Strip off leading ':'
1660 $link = substr($link, 1);
1661 }
1662
1663 wfProfileOut( __METHOD__."-misc" );
1664 wfProfileIn( __METHOD__."-title" );
1665 $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
1666 if( !$nt ) {
1667 $s .= $prefix . '[[' . $line;
1668 wfProfileOut( __METHOD__."-title" );
1669 continue;
1670 }
1671
1672 $ns = $nt->getNamespace();
1673 $iw = $nt->getInterWiki();
1674 wfProfileOut( __METHOD__."-title" );
1675
1676 if ($might_be_img) { # if this is actually an invalid link
1677 wfProfileIn( __METHOD__."-might_be_img" );
1678 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1679 $found = false;
1680 while ( true ) {
1681 #look at the next 'line' to see if we can close it there
1682 $a->next();
1683 $next_line = $a->current();
1684 if ( $next_line === false || $next_line === null ) {
1685 break;
1686 }
1687 $m = explode( ']]', $next_line, 3 );
1688 if ( count( $m ) == 3 ) {
1689 # the first ]] closes the inner link, the second the image
1690 $found = true;
1691 $text .= "[[{$m[0]}]]{$m[1]}";
1692 $trail = $m[2];
1693 break;
1694 } elseif ( count( $m ) == 2 ) {
1695 #if there's exactly one ]] that's fine, we'll keep looking
1696 $text .= "[[{$m[0]}]]{$m[1]}";
1697 } else {
1698 #if $next_line is invalid too, we need look no further
1699 $text .= '[[' . $next_line;
1700 break;
1701 }
1702 }
1703 if ( !$found ) {
1704 # we couldn't find the end of this imageLink, so output it raw
1705 #but don't ignore what might be perfectly normal links in the text we've examined
1706 $holders->merge( $this->replaceInternalLinks2( $text ) );
1707 $s .= "{$prefix}[[$link|$text";
1708 # note: no $trail, because without an end, there *is* no trail
1709 wfProfileOut( __METHOD__."-might_be_img" );
1710 continue;
1711 }
1712 } else { #it's not an image, so output it raw
1713 $s .= "{$prefix}[[$link|$text";
1714 # note: no $trail, because without an end, there *is* no trail
1715 wfProfileOut( __METHOD__."-might_be_img" );
1716 continue;
1717 }
1718 wfProfileOut( __METHOD__."-might_be_img" );
1719 }
1720
1721 $wasblank = ( '' == $text );
1722 if( $wasblank ) $text = $link;
1723
1724 # Link not escaped by : , create the various objects
1725 if( $noforce ) {
1726
1727 # Interwikis
1728 wfProfileIn( __METHOD__."-interwiki" );
1729 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1730 $this->mOutput->addLanguageLink( $nt->getFullText() );
1731 $s = rtrim($s . $prefix);
1732 $s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
1733 wfProfileOut( __METHOD__."-interwiki" );
1734 continue;
1735 }
1736 wfProfileOut( __METHOD__."-interwiki" );
1737
1738 if ( $ns == NS_IMAGE ) {
1739 wfProfileIn( __METHOD__."-image" );
1740 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1741 # recursively parse links inside the image caption
1742 # actually, this will parse them in any other parameters, too,
1743 # but it might be hard to fix that, and it doesn't matter ATM
1744 $text = $this->replaceExternalLinks($text);
1745 $holders->merge( $this->replaceInternalLinks2( $text ) );
1746
1747 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1748 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1749 }
1750 $this->mOutput->addImage( $nt->getDBkey() );
1751 wfProfileOut( __METHOD__."-image" );
1752 continue;
1753
1754 }
1755
1756 if ( $ns == NS_CATEGORY ) {
1757 wfProfileIn( __METHOD__."-category" );
1758 $s = rtrim($s . "\n"); # bug 87
1759
1760 if ( $wasblank ) {
1761 $sortkey = $this->getDefaultSort();
1762 } else {
1763 $sortkey = $text;
1764 }
1765 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1766 $sortkey = str_replace( "\n", '', $sortkey );
1767 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1768 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1769
1770 /**
1771 * Strip the whitespace Category links produce, see bug 87
1772 * @todo We might want to use trim($tmp, "\n") here.
1773 */
1774 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1775
1776 wfProfileOut( __METHOD__."-category" );
1777 continue;
1778 }
1779 }
1780
1781 # Self-link checking
1782 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL ) {
1783 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1784 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1785 continue;
1786 }
1787 }
1788
1789 # Special and Media are pseudo-namespaces; no pages actually exist in them
1790 if( $ns == NS_MEDIA ) {
1791 # Give extensions a chance to select the file revision for us
1792 $skip = $time = false;
1793 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1794 if ( $skip ) {
1795 $link = $sk->link( $nt );
1796 } else {
1797 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1798 }
1799 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1800 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1801 $this->mOutput->addImage( $nt->getDBkey() );
1802 continue;
1803 } elseif( $ns == NS_SPECIAL ) {
1804 if( SpecialPage::exists( $nt->getDBkey() ) ) {
1805 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1806 } else {
1807 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1808 }
1809 continue;
1810 } elseif( $ns == NS_IMAGE ) {
1811 $img = wfFindFile( $nt );
1812 if( $img ) {
1813 // Force a blue link if the file exists; may be a remote
1814 // upload on the shared repository, and we want to see its
1815 // auto-generated page.
1816 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1817 $this->mOutput->addLink( $nt );
1818 continue;
1819 }
1820 }
1821 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1822 }
1823 wfProfileOut( __METHOD__ );
1824 return $holders;
1825 }
1826
1827 /**
1828 * Make a link placeholder. The text returned can be later resolved to a real link with
1829 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1830 * parsing of interwiki links, and secondly to allow all existence checks and
1831 * article length checks (for stub links) to be bundled into a single query.
1832 *
1833 * @deprecated
1834 */
1835 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1836 return $this->mLinkHolders->makeHolder( $nt, $text, $query, $trail, $prefix );
1837 }
1838
1839 /**
1840 * Render a forced-blue link inline; protect against double expansion of
1841 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1842 * Since this little disaster has to split off the trail text to avoid
1843 * breaking URLs in the following text without breaking trails on the
1844 * wiki links, it's been made into a horrible function.
1845 *
1846 * @param Title $nt
1847 * @param string $text
1848 * @param string $query
1849 * @param string $trail
1850 * @param string $prefix
1851 * @return string HTML-wikitext mix oh yuck
1852 */
1853 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1854 list( $inside, $trail ) = Linker::splitTrail( $trail );
1855 $sk = $this->mOptions->getSkin();
1856 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1857 return $this->armorLinks( $link ) . $trail;
1858 }
1859
1860 /**
1861 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1862 * going to go through further parsing steps before inline URL expansion.
1863 *
1864 * Not needed quite as much as it used to be since free links are a bit
1865 * more sensible these days. But bracketed links are still an issue.
1866 *
1867 * @param string more-or-less HTML
1868 * @return string less-or-more HTML with NOPARSE bits
1869 */
1870 function armorLinks( $text ) {
1871 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1872 "{$this->mUniqPrefix}NOPARSE$1", $text );
1873 }
1874
1875 /**
1876 * Return true if subpage links should be expanded on this page.
1877 * @return bool
1878 */
1879 function areSubpagesAllowed() {
1880 # Some namespaces don't allow subpages
1881 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
1882 }
1883
1884 /**
1885 * Handle link to subpage if necessary
1886 * @param string $target the source of the link
1887 * @param string &$text the link text, modified as necessary
1888 * @return string the full name of the link
1889 * @private
1890 */
1891 function maybeDoSubpageLink($target, &$text) {
1892 # Valid link forms:
1893 # Foobar -- normal
1894 # :Foobar -- override special treatment of prefix (images, language links)
1895 # /Foobar -- convert to CurrentPage/Foobar
1896 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1897 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1898 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1899
1900 wfProfileIn( __METHOD__ );
1901 $ret = $target; # default return value is no change
1902
1903 # Some namespaces don't allow subpages,
1904 # so only perform processing if subpages are allowed
1905 if( $this->areSubpagesAllowed() ) {
1906 $hash = strpos( $target, '#' );
1907 if( $hash !== false ) {
1908 $suffix = substr( $target, $hash );
1909 $target = substr( $target, 0, $hash );
1910 } else {
1911 $suffix = '';
1912 }
1913 # bug 7425
1914 $target = trim( $target );
1915 # Look at the first character
1916 if( $target != '' && $target{0} === '/' ) {
1917 # / at end means we don't want the slash to be shown
1918 $m = array();
1919 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1920 if( $trailingSlashes ) {
1921 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1922 } else {
1923 $noslash = substr( $target, 1 );
1924 }
1925
1926 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1927 if( '' === $text ) {
1928 $text = $target . $suffix;
1929 } # this might be changed for ugliness reasons
1930 } else {
1931 # check for .. subpage backlinks
1932 $dotdotcount = 0;
1933 $nodotdot = $target;
1934 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1935 ++$dotdotcount;
1936 $nodotdot = substr( $nodotdot, 3 );
1937 }
1938 if($dotdotcount > 0) {
1939 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1940 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1941 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1942 # / at the end means don't show full path
1943 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1944 $nodotdot = substr( $nodotdot, 0, -1 );
1945 if( '' === $text ) {
1946 $text = $nodotdot . $suffix;
1947 }
1948 }
1949 $nodotdot = trim( $nodotdot );
1950 if( $nodotdot != '' ) {
1951 $ret .= '/' . $nodotdot;
1952 }
1953 $ret .= $suffix;
1954 }
1955 }
1956 }
1957 }
1958
1959 wfProfileOut( __METHOD__ );
1960 return $ret;
1961 }
1962
1963 /**#@+
1964 * Used by doBlockLevels()
1965 * @private
1966 */
1967 /* private */ function closeParagraph() {
1968 $result = '';
1969 if ( '' != $this->mLastSection ) {
1970 $result = '</' . $this->mLastSection . ">\n";
1971 }
1972 $this->mInPre = false;
1973 $this->mLastSection = '';
1974 return $result;
1975 }
1976 # getCommon() returns the length of the longest common substring
1977 # of both arguments, starting at the beginning of both.
1978 #
1979 /* private */ function getCommon( $st1, $st2 ) {
1980 $fl = strlen( $st1 );
1981 $shorter = strlen( $st2 );
1982 if ( $fl < $shorter ) { $shorter = $fl; }
1983
1984 for ( $i = 0; $i < $shorter; ++$i ) {
1985 if ( $st1{$i} != $st2{$i} ) { break; }
1986 }
1987 return $i;
1988 }
1989 # These next three functions open, continue, and close the list
1990 # element appropriate to the prefix character passed into them.
1991 #
1992 /* private */ function openList( $char ) {
1993 $result = $this->closeParagraph();
1994
1995 if ( '*' === $char ) { $result .= '<ul><li>'; }
1996 else if ( '#' === $char ) { $result .= '<ol><li>'; }
1997 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
1998 else if ( ';' === $char ) {
1999 $result .= '<dl><dt>';
2000 $this->mDTopen = true;
2001 }
2002 else { $result = '<!-- ERR 1 -->'; }
2003
2004 return $result;
2005 }
2006
2007 /* private */ function nextItem( $char ) {
2008 if ( '*' === $char || '#' === $char ) { return '</li><li>'; }
2009 else if ( ':' === $char || ';' === $char ) {
2010 $close = '</dd>';
2011 if ( $this->mDTopen ) { $close = '</dt>'; }
2012 if ( ';' === $char ) {
2013 $this->mDTopen = true;
2014 return $close . '<dt>';
2015 } else {
2016 $this->mDTopen = false;
2017 return $close . '<dd>';
2018 }
2019 }
2020 return '<!-- ERR 2 -->';
2021 }
2022
2023 /* private */ function closeList( $char ) {
2024 if ( '*' === $char ) { $text = '</li></ul>'; }
2025 else if ( '#' === $char ) { $text = '</li></ol>'; }
2026 else if ( ':' === $char ) {
2027 if ( $this->mDTopen ) {
2028 $this->mDTopen = false;
2029 $text = '</dt></dl>';
2030 } else {
2031 $text = '</dd></dl>';
2032 }
2033 }
2034 else { return '<!-- ERR 3 -->'; }
2035 return $text."\n";
2036 }
2037 /**#@-*/
2038
2039 /**
2040 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2041 *
2042 * @private
2043 * @return string the lists rendered as HTML
2044 */
2045 function doBlockLevels( $text, $linestart ) {
2046 wfProfileIn( __METHOD__ );
2047
2048 # Parsing through the text line by line. The main thing
2049 # happening here is handling of block-level elements p, pre,
2050 # and making lists from lines starting with * # : etc.
2051 #
2052 $textLines = StringUtils::explode( "\n", $text );
2053
2054 $lastPrefix = $output = '';
2055 $this->mDTopen = $inBlockElem = false;
2056 $prefixLength = 0;
2057 $paragraphStack = false;
2058
2059 foreach ( $textLines as $oLine ) {
2060 # Fix up $linestart
2061 if ( !$linestart ) {
2062 $output .= $oLine;
2063 $linestart = true;
2064 continue;
2065 }
2066
2067 $lastPrefixLength = strlen( $lastPrefix );
2068 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2069 $preOpenMatch = preg_match('/<pre/i', $oLine );
2070 if ( !$this->mInPre ) {
2071 # Multiple prefixes may abut each other for nested lists.
2072 $prefixLength = strspn( $oLine, '*#:;' );
2073 $prefix = substr( $oLine, 0, $prefixLength );
2074
2075 # eh?
2076 $prefix2 = str_replace( ';', ':', $prefix );
2077 $t = substr( $oLine, $prefixLength );
2078 $this->mInPre = (bool)$preOpenMatch;
2079 } else {
2080 # Don't interpret any other prefixes in preformatted text
2081 $prefixLength = 0;
2082 $prefix = $prefix2 = '';
2083 $t = $oLine;
2084 }
2085
2086 # List generation
2087 if( $prefixLength && $lastPrefix === $prefix2 ) {
2088 # Same as the last item, so no need to deal with nesting or opening stuff
2089 $output .= $this->nextItem( substr( $prefix, -1 ) );
2090 $paragraphStack = false;
2091
2092 if ( substr( $prefix, -1 ) === ';') {
2093 # The one nasty exception: definition lists work like this:
2094 # ; title : definition text
2095 # So we check for : in the remainder text to split up the
2096 # title and definition, without b0rking links.
2097 $term = $t2 = '';
2098 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2099 $t = $t2;
2100 $output .= $term . $this->nextItem( ':' );
2101 }
2102 }
2103 } elseif( $prefixLength || $lastPrefixLength ) {
2104 # Either open or close a level...
2105 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2106 $paragraphStack = false;
2107
2108 while( $commonPrefixLength < $lastPrefixLength ) {
2109 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2110 --$lastPrefixLength;
2111 }
2112 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2113 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2114 }
2115 while ( $prefixLength > $commonPrefixLength ) {
2116 $char = substr( $prefix, $commonPrefixLength, 1 );
2117 $output .= $this->openList( $char );
2118
2119 if ( ';' === $char ) {
2120 # FIXME: This is dupe of code above
2121 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2122 $t = $t2;
2123 $output .= $term . $this->nextItem( ':' );
2124 }
2125 }
2126 ++$commonPrefixLength;
2127 }
2128 $lastPrefix = $prefix2;
2129 }
2130 if( 0 == $prefixLength ) {
2131 wfProfileIn( __METHOD__."-paragraph" );
2132 # No prefix (not in list)--go to paragraph mode
2133 // XXX: use a stack for nestable elements like span, table and div
2134 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2135 $closematch = preg_match(
2136 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2137 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2138 if ( $openmatch or $closematch ) {
2139 $paragraphStack = false;
2140 # TODO bug 5718: paragraph closed
2141 $output .= $this->closeParagraph();
2142 if ( $preOpenMatch and !$preCloseMatch ) {
2143 $this->mInPre = true;
2144 }
2145 if ( $closematch ) {
2146 $inBlockElem = false;
2147 } else {
2148 $inBlockElem = true;
2149 }
2150 } else if ( !$inBlockElem && !$this->mInPre ) {
2151 if ( ' ' == $t{0} and ( $this->mLastSection === 'pre' or trim($t) != '' ) ) {
2152 // pre
2153 if ($this->mLastSection !== 'pre') {
2154 $paragraphStack = false;
2155 $output .= $this->closeParagraph().'<pre>';
2156 $this->mLastSection = 'pre';
2157 }
2158 $t = substr( $t, 1 );
2159 } else {
2160 // paragraph
2161 if ( '' == trim($t) ) {
2162 if ( $paragraphStack ) {
2163 $output .= $paragraphStack.'<br />';
2164 $paragraphStack = false;
2165 $this->mLastSection = 'p';
2166 } else {
2167 if ($this->mLastSection !== 'p' ) {
2168 $output .= $this->closeParagraph();
2169 $this->mLastSection = '';
2170 $paragraphStack = '<p>';
2171 } else {
2172 $paragraphStack = '</p><p>';
2173 }
2174 }
2175 } else {
2176 if ( $paragraphStack ) {
2177 $output .= $paragraphStack;
2178 $paragraphStack = false;
2179 $this->mLastSection = 'p';
2180 } else if ($this->mLastSection !== 'p') {
2181 $output .= $this->closeParagraph().'<p>';
2182 $this->mLastSection = 'p';
2183 }
2184 }
2185 }
2186 }
2187 wfProfileOut( __METHOD__."-paragraph" );
2188 }
2189 // somewhere above we forget to get out of pre block (bug 785)
2190 if($preCloseMatch && $this->mInPre) {
2191 $this->mInPre = false;
2192 }
2193 if ($paragraphStack === false) {
2194 $output .= $t."\n";
2195 }
2196 }
2197 while ( $prefixLength ) {
2198 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2199 --$prefixLength;
2200 }
2201 if ( '' != $this->mLastSection ) {
2202 $output .= '</' . $this->mLastSection . '>';
2203 $this->mLastSection = '';
2204 }
2205
2206 wfProfileOut( __METHOD__ );
2207 return $output;
2208 }
2209
2210 /**
2211 * Split up a string on ':', ignoring any occurences inside tags
2212 * to prevent illegal overlapping.
2213 * @param string $str the string to split
2214 * @param string &$before set to everything before the ':'
2215 * @param string &$after set to everything after the ':'
2216 * return string the position of the ':', or false if none found
2217 */
2218 function findColonNoLinks($str, &$before, &$after) {
2219 wfProfileIn( __METHOD__ );
2220
2221 $pos = strpos( $str, ':' );
2222 if( $pos === false ) {
2223 // Nothing to find!
2224 wfProfileOut( __METHOD__ );
2225 return false;
2226 }
2227
2228 $lt = strpos( $str, '<' );
2229 if( $lt === false || $lt > $pos ) {
2230 // Easy; no tag nesting to worry about
2231 $before = substr( $str, 0, $pos );
2232 $after = substr( $str, $pos+1 );
2233 wfProfileOut( __METHOD__ );
2234 return $pos;
2235 }
2236
2237 // Ugly state machine to walk through avoiding tags.
2238 $state = self::COLON_STATE_TEXT;
2239 $stack = 0;
2240 $len = strlen( $str );
2241 for( $i = 0; $i < $len; $i++ ) {
2242 $c = $str{$i};
2243
2244 switch( $state ) {
2245 // (Using the number is a performance hack for common cases)
2246 case 0: // self::COLON_STATE_TEXT:
2247 switch( $c ) {
2248 case "<":
2249 // Could be either a <start> tag or an </end> tag
2250 $state = self::COLON_STATE_TAGSTART;
2251 break;
2252 case ":":
2253 if( $stack == 0 ) {
2254 // We found it!
2255 $before = substr( $str, 0, $i );
2256 $after = substr( $str, $i + 1 );
2257 wfProfileOut( __METHOD__ );
2258 return $i;
2259 }
2260 // Embedded in a tag; don't break it.
2261 break;
2262 default:
2263 // Skip ahead looking for something interesting
2264 $colon = strpos( $str, ':', $i );
2265 if( $colon === false ) {
2266 // Nothing else interesting
2267 wfProfileOut( __METHOD__ );
2268 return false;
2269 }
2270 $lt = strpos( $str, '<', $i );
2271 if( $stack === 0 ) {
2272 if( $lt === false || $colon < $lt ) {
2273 // We found it!
2274 $before = substr( $str, 0, $colon );
2275 $after = substr( $str, $colon + 1 );
2276 wfProfileOut( __METHOD__ );
2277 return $i;
2278 }
2279 }
2280 if( $lt === false ) {
2281 // Nothing else interesting to find; abort!
2282 // We're nested, but there's no close tags left. Abort!
2283 break 2;
2284 }
2285 // Skip ahead to next tag start
2286 $i = $lt;
2287 $state = self::COLON_STATE_TAGSTART;
2288 }
2289 break;
2290 case 1: // self::COLON_STATE_TAG:
2291 // In a <tag>
2292 switch( $c ) {
2293 case ">":
2294 $stack++;
2295 $state = self::COLON_STATE_TEXT;
2296 break;
2297 case "/":
2298 // Slash may be followed by >?
2299 $state = self::COLON_STATE_TAGSLASH;
2300 break;
2301 default:
2302 // ignore
2303 }
2304 break;
2305 case 2: // self::COLON_STATE_TAGSTART:
2306 switch( $c ) {
2307 case "/":
2308 $state = self::COLON_STATE_CLOSETAG;
2309 break;
2310 case "!":
2311 $state = self::COLON_STATE_COMMENT;
2312 break;
2313 case ">":
2314 // Illegal early close? This shouldn't happen D:
2315 $state = self::COLON_STATE_TEXT;
2316 break;
2317 default:
2318 $state = self::COLON_STATE_TAG;
2319 }
2320 break;
2321 case 3: // self::COLON_STATE_CLOSETAG:
2322 // In a </tag>
2323 if( $c === ">" ) {
2324 $stack--;
2325 if( $stack < 0 ) {
2326 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
2327 wfProfileOut( __METHOD__ );
2328 return false;
2329 }
2330 $state = self::COLON_STATE_TEXT;
2331 }
2332 break;
2333 case self::COLON_STATE_TAGSLASH:
2334 if( $c === ">" ) {
2335 // Yes, a self-closed tag <blah/>
2336 $state = self::COLON_STATE_TEXT;
2337 } else {
2338 // Probably we're jumping the gun, and this is an attribute
2339 $state = self::COLON_STATE_TAG;
2340 }
2341 break;
2342 case 5: // self::COLON_STATE_COMMENT:
2343 if( $c === "-" ) {
2344 $state = self::COLON_STATE_COMMENTDASH;
2345 }
2346 break;
2347 case self::COLON_STATE_COMMENTDASH:
2348 if( $c === "-" ) {
2349 $state = self::COLON_STATE_COMMENTDASHDASH;
2350 } else {
2351 $state = self::COLON_STATE_COMMENT;
2352 }
2353 break;
2354 case self::COLON_STATE_COMMENTDASHDASH:
2355 if( $c === ">" ) {
2356 $state = self::COLON_STATE_TEXT;
2357 } else {
2358 $state = self::COLON_STATE_COMMENT;
2359 }
2360 break;
2361 default:
2362 throw new MWException( "State machine error in " . __METHOD__ );
2363 }
2364 }
2365 if( $stack > 0 ) {
2366 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2367 return false;
2368 }
2369 wfProfileOut( __METHOD__ );
2370 return false;
2371 }
2372
2373 /**
2374 * Return value of a magic variable (like PAGENAME)
2375 *
2376 * @private
2377 */
2378 function getVariableValue( $index ) {
2379 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2380
2381 /**
2382 * Some of these require message or data lookups and can be
2383 * expensive to check many times.
2384 */
2385 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2386 if ( isset( $this->mVarCache[$index] ) ) {
2387 return $this->mVarCache[$index];
2388 }
2389 }
2390
2391 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2392 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2393
2394 # Use the time zone
2395 global $wgLocaltimezone;
2396 if ( isset( $wgLocaltimezone ) ) {
2397 $oldtz = getenv( 'TZ' );
2398 putenv( 'TZ='.$wgLocaltimezone );
2399 }
2400
2401 wfSuppressWarnings(); // E_STRICT system time bitching
2402 $localTimestamp = date( 'YmdHis', $ts );
2403 $localMonth = date( 'm', $ts );
2404 $localMonthName = date( 'n', $ts );
2405 $localDay = date( 'j', $ts );
2406 $localDay2 = date( 'd', $ts );
2407 $localDayOfWeek = date( 'w', $ts );
2408 $localWeek = date( 'W', $ts );
2409 $localYear = date( 'Y', $ts );
2410 $localHour = date( 'H', $ts );
2411 if ( isset( $wgLocaltimezone ) ) {
2412 putenv( 'TZ='.$oldtz );
2413 }
2414 wfRestoreWarnings();
2415
2416 switch ( $index ) {
2417 case 'currentmonth':
2418 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2419 case 'currentmonthname':
2420 return $this->mVarCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2421 case 'currentmonthnamegen':
2422 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2423 case 'currentmonthabbrev':
2424 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2425 case 'currentday':
2426 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2427 case 'currentday2':
2428 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2429 case 'localmonth':
2430 return $this->mVarCache[$index] = $wgContLang->formatNum( $localMonth );
2431 case 'localmonthname':
2432 return $this->mVarCache[$index] = $wgContLang->getMonthName( $localMonthName );
2433 case 'localmonthnamegen':
2434 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2435 case 'localmonthabbrev':
2436 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2437 case 'localday':
2438 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay );
2439 case 'localday2':
2440 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay2 );
2441 case 'pagename':
2442 return wfEscapeWikiText( $this->mTitle->getText() );
2443 case 'pagenamee':
2444 return $this->mTitle->getPartialURL();
2445 case 'fullpagename':
2446 return wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2447 case 'fullpagenamee':
2448 return $this->mTitle->getPrefixedURL();
2449 case 'subpagename':
2450 return wfEscapeWikiText( $this->mTitle->getSubpageText() );
2451 case 'subpagenamee':
2452 return $this->mTitle->getSubpageUrlForm();
2453 case 'basepagename':
2454 return wfEscapeWikiText( $this->mTitle->getBaseText() );
2455 case 'basepagenamee':
2456 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2457 case 'talkpagename':
2458 if( $this->mTitle->canTalk() ) {
2459 $talkPage = $this->mTitle->getTalkPage();
2460 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2461 } else {
2462 return '';
2463 }
2464 case 'talkpagenamee':
2465 if( $this->mTitle->canTalk() ) {
2466 $talkPage = $this->mTitle->getTalkPage();
2467 return $talkPage->getPrefixedUrl();
2468 } else {
2469 return '';
2470 }
2471 case 'subjectpagename':
2472 $subjPage = $this->mTitle->getSubjectPage();
2473 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2474 case 'subjectpagenamee':
2475 $subjPage = $this->mTitle->getSubjectPage();
2476 return $subjPage->getPrefixedUrl();
2477 case 'revisionid':
2478 // Let the edit saving system know we should parse the page
2479 // *after* a revision ID has been assigned.
2480 $this->mOutput->setFlag( 'vary-revision' );
2481 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2482 return $this->mRevisionId;
2483 case 'revisionday':
2484 // Let the edit saving system know we should parse the page
2485 // *after* a revision ID has been assigned. This is for null edits.
2486 $this->mOutput->setFlag( 'vary-revision' );
2487 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2488 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2489 case 'revisionday2':
2490 // Let the edit saving system know we should parse the page
2491 // *after* a revision ID has been assigned. This is for null edits.
2492 $this->mOutput->setFlag( 'vary-revision' );
2493 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2494 return substr( $this->getRevisionTimestamp(), 6, 2 );
2495 case 'revisionmonth':
2496 // Let the edit saving system know we should parse the page
2497 // *after* a revision ID has been assigned. This is for null edits.
2498 $this->mOutput->setFlag( 'vary-revision' );
2499 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2500 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2501 case 'revisionyear':
2502 // Let the edit saving system know we should parse the page
2503 // *after* a revision ID has been assigned. This is for null edits.
2504 $this->mOutput->setFlag( 'vary-revision' );
2505 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2506 return substr( $this->getRevisionTimestamp(), 0, 4 );
2507 case 'revisiontimestamp':
2508 // Let the edit saving system know we should parse the page
2509 // *after* a revision ID has been assigned. This is for null edits.
2510 $this->mOutput->setFlag( 'vary-revision' );
2511 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2512 return $this->getRevisionTimestamp();
2513 case 'namespace':
2514 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2515 case 'namespacee':
2516 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2517 case 'talkspace':
2518 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2519 case 'talkspacee':
2520 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2521 case 'subjectspace':
2522 return $this->mTitle->getSubjectNsText();
2523 case 'subjectspacee':
2524 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2525 case 'currentdayname':
2526 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2527 case 'currentyear':
2528 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2529 case 'currenttime':
2530 return $this->mVarCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2531 case 'currenthour':
2532 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2533 case 'currentweek':
2534 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2535 // int to remove the padding
2536 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2537 case 'currentdow':
2538 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2539 case 'localdayname':
2540 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2541 case 'localyear':
2542 return $this->mVarCache[$index] = $wgContLang->formatNum( $localYear, true );
2543 case 'localtime':
2544 return $this->mVarCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2545 case 'localhour':
2546 return $this->mVarCache[$index] = $wgContLang->formatNum( $localHour, true );
2547 case 'localweek':
2548 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2549 // int to remove the padding
2550 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2551 case 'localdow':
2552 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2553 case 'numberofarticles':
2554 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2555 case 'numberoffiles':
2556 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2557 case 'numberofusers':
2558 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2559 case 'numberofpages':
2560 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2561 case 'numberofadmins':
2562 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::numberingroup('sysop') );
2563 case 'numberofedits':
2564 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::edits() );
2565 case 'currenttimestamp':
2566 return $this->mVarCache[$index] = wfTimestamp( TS_MW, $ts );
2567 case 'localtimestamp':
2568 return $this->mVarCache[$index] = $localTimestamp;
2569 case 'currentversion':
2570 return $this->mVarCache[$index] = SpecialVersion::getVersion();
2571 case 'sitename':
2572 return $wgSitename;
2573 case 'server':
2574 return $wgServer;
2575 case 'servername':
2576 return $wgServerName;
2577 case 'scriptpath':
2578 return $wgScriptPath;
2579 case 'directionmark':
2580 return $wgContLang->getDirMark();
2581 case 'contentlanguage':
2582 global $wgContLanguageCode;
2583 return $wgContLanguageCode;
2584 default:
2585 $ret = null;
2586 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret ) ) )
2587 return $ret;
2588 else
2589 return null;
2590 }
2591 }
2592
2593 /**
2594 * initialise the magic variables (like CURRENTMONTHNAME)
2595 *
2596 * @private
2597 */
2598 function initialiseVariables() {
2599 wfProfileIn( __METHOD__ );
2600 $variableIDs = MagicWord::getVariableIDs();
2601
2602 $this->mVariables = new MagicWordArray( $variableIDs );
2603 wfProfileOut( __METHOD__ );
2604 }
2605
2606 /**
2607 * Preprocess some wikitext and return the document tree.
2608 * This is the ghost of replaceVariables().
2609 *
2610 * @param string $text The text to parse
2611 * @param integer flags Bitwise combination of:
2612 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2613 * included. Default is to assume a direct page view.
2614 *
2615 * The generated DOM tree must depend only on the input text and the flags.
2616 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2617 *
2618 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2619 * change in the DOM tree for a given text, must be passed through the section identifier
2620 * in the section edit link and thus back to extractSections().
2621 *
2622 * The output of this function is currently only cached in process memory, but a persistent
2623 * cache may be implemented at a later date which takes further advantage of these strict
2624 * dependency requirements.
2625 *
2626 * @private
2627 */
2628 function preprocessToDom( $text, $flags = 0 ) {
2629 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2630 return $dom;
2631 }
2632
2633 /*
2634 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2635 */
2636 public static function splitWhitespace( $s ) {
2637 $ltrimmed = ltrim( $s );
2638 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2639 $trimmed = rtrim( $ltrimmed );
2640 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2641 if ( $diff > 0 ) {
2642 $w2 = substr( $ltrimmed, -$diff );
2643 } else {
2644 $w2 = '';
2645 }
2646 return array( $w1, $trimmed, $w2 );
2647 }
2648
2649 /**
2650 * Replace magic variables, templates, and template arguments
2651 * with the appropriate text. Templates are substituted recursively,
2652 * taking care to avoid infinite loops.
2653 *
2654 * Note that the substitution depends on value of $mOutputType:
2655 * self::OT_WIKI: only {{subst:}} templates
2656 * self::OT_PREPROCESS: templates but not extension tags
2657 * self::OT_HTML: all templates and extension tags
2658 *
2659 * @param string $tex The text to transform
2660 * @param PPFrame $frame Object describing the arguments passed to the template.
2661 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2662 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2663 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2664 * @private
2665 */
2666 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2667 # Prevent too big inclusions
2668 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2669 return $text;
2670 }
2671
2672 wfProfileIn( __METHOD__ );
2673
2674 if ( $frame === false ) {
2675 $frame = $this->getPreprocessor()->newFrame();
2676 } elseif ( !( $frame instanceof PPFrame ) ) {
2677 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2678 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2679 }
2680
2681 $dom = $this->preprocessToDom( $text );
2682 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2683 $text = $frame->expand( $dom, $flags );
2684
2685 wfProfileOut( __METHOD__ );
2686 return $text;
2687 }
2688
2689 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2690 static function createAssocArgs( $args ) {
2691 $assocArgs = array();
2692 $index = 1;
2693 foreach( $args as $arg ) {
2694 $eqpos = strpos( $arg, '=' );
2695 if ( $eqpos === false ) {
2696 $assocArgs[$index++] = $arg;
2697 } else {
2698 $name = trim( substr( $arg, 0, $eqpos ) );
2699 $value = trim( substr( $arg, $eqpos+1 ) );
2700 if ( $value === false ) {
2701 $value = '';
2702 }
2703 if ( $name !== false ) {
2704 $assocArgs[$name] = $value;
2705 }
2706 }
2707 }
2708
2709 return $assocArgs;
2710 }
2711
2712 /**
2713 * Warn the user when a parser limitation is reached
2714 * Will warn at most once the user per limitation type
2715 *
2716 * @param string $limitationType, should be one of:
2717 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2718 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2719 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2720 * @params int $current, $max When an explicit limit has been
2721 * exceeded, provide the values (optional)
2722 */
2723 function limitationWarn( $limitationType, $current=null, $max=null) {
2724 $msgName = $limitationType . '-warning';
2725 //does no harm if $current and $max are present but are unnecessary for the message
2726 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2727 $this->mOutput->addWarning( $warning );
2728 $cat = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( $limitationType . '-category' ) );
2729 if ( $cat ) {
2730 $this->mOutput->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2731 }
2732 }
2733
2734 /**
2735 * Return the text of a template, after recursively
2736 * replacing any variables or templates within the template.
2737 *
2738 * @param array $piece The parts of the template
2739 * $piece['title']: the title, i.e. the part before the |
2740 * $piece['parts']: the parameter array
2741 * $piece['lineStart']: whether the brace was at the start of a line
2742 * @param PPFrame The current frame, contains template arguments
2743 * @return string the text of the template
2744 * @private
2745 */
2746 function braceSubstitution( $piece, $frame ) {
2747 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2748 wfProfileIn( __METHOD__ );
2749 wfProfileIn( __METHOD__.'-setup' );
2750
2751 # Flags
2752 $found = false; # $text has been filled
2753 $nowiki = false; # wiki markup in $text should be escaped
2754 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2755 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2756 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2757 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2758
2759 # Title object, where $text came from
2760 $title = NULL;
2761
2762 # $part1 is the bit before the first |, and must contain only title characters.
2763 # Various prefixes will be stripped from it later.
2764 $titleWithSpaces = $frame->expand( $piece['title'] );
2765 $part1 = trim( $titleWithSpaces );
2766 $titleText = false;
2767
2768 # Original title text preserved for various purposes
2769 $originalTitle = $part1;
2770
2771 # $args is a list of argument nodes, starting from index 0, not including $part1
2772 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2773 wfProfileOut( __METHOD__.'-setup' );
2774
2775 # SUBST
2776 wfProfileIn( __METHOD__.'-modifiers' );
2777 if ( !$found ) {
2778 $mwSubst = MagicWord::get( 'subst' );
2779 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2780 # One of two possibilities is true:
2781 # 1) Found SUBST but not in the PST phase
2782 # 2) Didn't find SUBST and in the PST phase
2783 # In either case, return without further processing
2784 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2785 $isLocalObj = true;
2786 $found = true;
2787 }
2788 }
2789
2790 # Variables
2791 if ( !$found && $args->getLength() == 0 ) {
2792 $id = $this->mVariables->matchStartToEnd( $part1 );
2793 if ( $id !== false ) {
2794 $text = $this->getVariableValue( $id );
2795 if (MagicWord::getCacheTTL($id)>-1)
2796 $this->mOutput->mContainsOldMagic = true;
2797 $found = true;
2798 }
2799 }
2800
2801 # MSG, MSGNW and RAW
2802 if ( !$found ) {
2803 # Check for MSGNW:
2804 $mwMsgnw = MagicWord::get( 'msgnw' );
2805 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2806 $nowiki = true;
2807 } else {
2808 # Remove obsolete MSG:
2809 $mwMsg = MagicWord::get( 'msg' );
2810 $mwMsg->matchStartAndRemove( $part1 );
2811 }
2812
2813 # Check for RAW:
2814 $mwRaw = MagicWord::get( 'raw' );
2815 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2816 $forceRawInterwiki = true;
2817 }
2818 }
2819 wfProfileOut( __METHOD__.'-modifiers' );
2820
2821 # Parser functions
2822 if ( !$found ) {
2823 wfProfileIn( __METHOD__ . '-pfunc' );
2824
2825 $colonPos = strpos( $part1, ':' );
2826 if ( $colonPos !== false ) {
2827 # Case sensitive functions
2828 $function = substr( $part1, 0, $colonPos );
2829 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2830 $function = $this->mFunctionSynonyms[1][$function];
2831 } else {
2832 # Case insensitive functions
2833 $function = strtolower( $function );
2834 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2835 $function = $this->mFunctionSynonyms[0][$function];
2836 } else {
2837 $function = false;
2838 }
2839 }
2840 if ( $function ) {
2841 list( $callback, $flags ) = $this->mFunctionHooks[$function];
2842 $initialArgs = array( &$this );
2843 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
2844 if ( $flags & SFH_OBJECT_ARGS ) {
2845 # Add a frame parameter, and pass the arguments as an array
2846 $allArgs = $initialArgs;
2847 $allArgs[] = $frame;
2848 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2849 $funcArgs[] = $args->item( $i );
2850 }
2851 $allArgs[] = $funcArgs;
2852 } else {
2853 # Convert arguments to plain text
2854 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2855 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2856 }
2857 $allArgs = array_merge( $initialArgs, $funcArgs );
2858 }
2859
2860 # Workaround for PHP bug 35229 and similar
2861 if ( !is_callable( $callback ) ) {
2862 throw new MWException( "Tag hook for $name is not callable\n" );
2863 }
2864 $result = call_user_func_array( $callback, $allArgs );
2865 $found = true;
2866 $noparse = true;
2867 $preprocessFlags = 0;
2868
2869 if ( is_array( $result ) ) {
2870 if ( isset( $result[0] ) ) {
2871 $text = $result[0];
2872 unset( $result[0] );
2873 }
2874
2875 // Extract flags into the local scope
2876 // This allows callers to set flags such as nowiki, found, etc.
2877 extract( $result );
2878 } else {
2879 $text = $result;
2880 }
2881 if ( !$noparse ) {
2882 $text = $this->preprocessToDom( $text, $preprocessFlags );
2883 $isChildObj = true;
2884 }
2885 }
2886 }
2887 wfProfileOut( __METHOD__ . '-pfunc' );
2888 }
2889
2890 # Finish mangling title and then check for loops.
2891 # Set $title to a Title object and $titleText to the PDBK
2892 if ( !$found ) {
2893 $ns = NS_TEMPLATE;
2894 # Split the title into page and subpage
2895 $subpage = '';
2896 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2897 if ($subpage !== '') {
2898 $ns = $this->mTitle->getNamespace();
2899 }
2900 $title = Title::newFromText( $part1, $ns );
2901 if ( $title ) {
2902 $titleText = $title->getPrefixedText();
2903 # Check for language variants if the template is not found
2904 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2905 $wgContLang->findVariantLink( $part1, $title, true );
2906 }
2907 # Do infinite loop check
2908 if ( !$frame->loopCheck( $title ) ) {
2909 $found = true;
2910 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2911 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
2912 }
2913 # Do recursion depth check
2914 $limit = $this->mOptions->getMaxTemplateDepth();
2915 if ( $frame->depth >= $limit ) {
2916 $found = true;
2917 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2918 }
2919 }
2920 }
2921
2922 # Load from database
2923 if ( !$found && $title ) {
2924 wfProfileIn( __METHOD__ . '-loadtpl' );
2925 if ( !$title->isExternal() ) {
2926 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
2927 $text = SpecialPage::capturePath( $title );
2928 if ( is_string( $text ) ) {
2929 $found = true;
2930 $isHTML = true;
2931 $this->disableCache();
2932 }
2933 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2934 $found = false; //access denied
2935 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
2936 } else {
2937 list( $text, $title ) = $this->getTemplateDom( $title );
2938 if ( $text !== false ) {
2939 $found = true;
2940 $isChildObj = true;
2941 }
2942 }
2943
2944 # If the title is valid but undisplayable, make a link to it
2945 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2946 $text = "[[:$titleText]]";
2947 $found = true;
2948 }
2949 } elseif ( $title->isTrans() ) {
2950 // Interwiki transclusion
2951 if ( $this->ot['html'] && !$forceRawInterwiki ) {
2952 $text = $this->interwikiTransclude( $title, 'render' );
2953 $isHTML = true;
2954 } else {
2955 $text = $this->interwikiTransclude( $title, 'raw' );
2956 // Preprocess it like a template
2957 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
2958 $isChildObj = true;
2959 }
2960 $found = true;
2961 }
2962 wfProfileOut( __METHOD__ . '-loadtpl' );
2963 }
2964
2965 # If we haven't found text to substitute by now, we're done
2966 # Recover the source wikitext and return it
2967 if ( !$found ) {
2968 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2969 wfProfileOut( __METHOD__ );
2970 return array( 'object' => $text );
2971 }
2972
2973 # Expand DOM-style return values in a child frame
2974 if ( $isChildObj ) {
2975 # Clean up argument array
2976 $newFrame = $frame->newChild( $args, $title );
2977
2978 if ( $nowiki ) {
2979 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
2980 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2981 # Expansion is eligible for the empty-frame cache
2982 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
2983 $text = $this->mTplExpandCache[$titleText];
2984 } else {
2985 $text = $newFrame->expand( $text );
2986 $this->mTplExpandCache[$titleText] = $text;
2987 }
2988 } else {
2989 # Uncached expansion
2990 $text = $newFrame->expand( $text );
2991 }
2992 }
2993 if ( $isLocalObj && $nowiki ) {
2994 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
2995 $isLocalObj = false;
2996 }
2997
2998 # Replace raw HTML by a placeholder
2999 # Add a blank line preceding, to prevent it from mucking up
3000 # immediately preceding headings
3001 if ( $isHTML ) {
3002 $text = "\n\n" . $this->insertStripItem( $text );
3003 }
3004 # Escape nowiki-style return values
3005 elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3006 $text = wfEscapeWikiText( $text );
3007 }
3008 # Bug 529: if the template begins with a table or block-level
3009 # element, it should be treated as beginning a new line.
3010 # This behaviour is somewhat controversial.
3011 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3012 $text = "\n" . $text;
3013 }
3014
3015 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3016 # Error, oversize inclusion
3017 $text = "[[$originalTitle]]" .
3018 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3019 $this->limitationWarn( 'post-expand-template-inclusion' );
3020 }
3021
3022 if ( $isLocalObj ) {
3023 $ret = array( 'object' => $text );
3024 } else {
3025 $ret = array( 'text' => $text );
3026 }
3027
3028 wfProfileOut( __METHOD__ );
3029 return $ret;
3030 }
3031
3032 /**
3033 * Get the semi-parsed DOM representation of a template with a given title,
3034 * and its redirect destination title. Cached.
3035 */
3036 function getTemplateDom( $title ) {
3037 $cacheTitle = $title;
3038 $titleText = $title->getPrefixedDBkey();
3039
3040 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3041 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3042 $title = Title::makeTitle( $ns, $dbk );
3043 $titleText = $title->getPrefixedDBkey();
3044 }
3045 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3046 return array( $this->mTplDomCache[$titleText], $title );
3047 }
3048
3049 // Cache miss, go to the database
3050 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3051
3052 if ( $text === false ) {
3053 $this->mTplDomCache[$titleText] = false;
3054 return array( false, $title );
3055 }
3056
3057 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3058 $this->mTplDomCache[ $titleText ] = $dom;
3059
3060 if (! $title->equals($cacheTitle)) {
3061 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3062 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3063 }
3064
3065 return array( $dom, $title );
3066 }
3067
3068 /**
3069 * Fetch the unparsed text of a template and register a reference to it.
3070 */
3071 function fetchTemplateAndTitle( $title ) {
3072 $templateCb = $this->mOptions->getTemplateCallback();
3073 $stuff = call_user_func( $templateCb, $title, $this );
3074 $text = $stuff['text'];
3075 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3076 if ( isset( $stuff['deps'] ) ) {
3077 foreach ( $stuff['deps'] as $dep ) {
3078 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3079 }
3080 }
3081 return array($text,$finalTitle);
3082 }
3083
3084 function fetchTemplate( $title ) {
3085 $rv = $this->fetchTemplateAndTitle($title);
3086 return $rv[0];
3087 }
3088
3089 /**
3090 * Static function to get a template
3091 * Can be overridden via ParserOptions::setTemplateCallback().
3092 */
3093 static function statelessFetchTemplate( $title, $parser=false ) {
3094 $text = $skip = false;
3095 $finalTitle = $title;
3096 $deps = array();
3097
3098 // Loop to fetch the article, with up to 1 redirect
3099 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3100 # Give extensions a chance to select the revision instead
3101 $id = false; // Assume current
3102 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3103
3104 if( $skip ) {
3105 $text = false;
3106 $deps[] = array(
3107 'title' => $title,
3108 'page_id' => $title->getArticleID(),
3109 'rev_id' => null );
3110 break;
3111 }
3112 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3113 $rev_id = $rev ? $rev->getId() : 0;
3114 // If there is no current revision, there is no page
3115 if( $id === false && !$rev ) {
3116 $linkCache = LinkCache::singleton();
3117 $linkCache->addBadLinkObj( $title );
3118 }
3119
3120 $deps[] = array(
3121 'title' => $title,
3122 'page_id' => $title->getArticleID(),
3123 'rev_id' => $rev_id );
3124
3125 if( $rev ) {
3126 $text = $rev->getText();
3127 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3128 global $wgLang;
3129 $message = $wgLang->lcfirst( $title->getText() );
3130 $text = wfMsgForContentNoTrans( $message );
3131 if( wfEmptyMsg( $message, $text ) ) {
3132 $text = false;
3133 break;
3134 }
3135 } else {
3136 break;
3137 }
3138 if ( $text === false ) {
3139 break;
3140 }
3141 // Redirect?
3142 $finalTitle = $title;
3143 $title = Title::newFromRedirect( $text );
3144 }
3145 return array(
3146 'text' => $text,
3147 'finalTitle' => $finalTitle,
3148 'deps' => $deps );
3149 }
3150
3151 /**
3152 * Transclude an interwiki link.
3153 */
3154 function interwikiTransclude( $title, $action ) {
3155 global $wgEnableScaryTranscluding;
3156
3157 if (!$wgEnableScaryTranscluding)
3158 return wfMsg('scarytranscludedisabled');
3159
3160 $url = $title->getFullUrl( "action=$action" );
3161
3162 if (strlen($url) > 255)
3163 return wfMsg('scarytranscludetoolong');
3164 return "<div class=\"mw-iw-transclusion\">\n" . $this->fetchScaryTemplateMaybeFromCache($url) . "</div>\n";
3165 }
3166
3167 function fetchScaryTemplateMaybeFromCache($url) {
3168 global $wgTranscludeCacheExpiry;
3169 $dbr = wfGetDB(DB_SLAVE);
3170 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3171 array('tc_url' => $url));
3172 if ($obj) {
3173 $time = $obj->tc_time;
3174 $text = $obj->tc_contents;
3175 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3176 return $text;
3177 }
3178 }
3179
3180 $text = Http::get($url);
3181 if (!$text)
3182 return wfMsg('scarytranscludefailed', $url);
3183
3184 $dbw = wfGetDB(DB_MASTER);
3185 $dbw->replace('transcache', array('tc_url'), array(
3186 'tc_url' => $url,
3187 'tc_time' => time(),
3188 'tc_contents' => $text));
3189 return $text;
3190 }
3191
3192
3193 /**
3194 * Triple brace replacement -- used for template arguments
3195 * @private
3196 */
3197 function argSubstitution( $piece, $frame ) {
3198 wfProfileIn( __METHOD__ );
3199
3200 $error = false;
3201 $parts = $piece['parts'];
3202 $nameWithSpaces = $frame->expand( $piece['title'] );
3203 $argName = trim( $nameWithSpaces );
3204 $object = false;
3205 $text = $frame->getArgument( $argName );
3206 if ( $text === false && $parts->getLength() > 0
3207 && (
3208 $this->ot['html']
3209 || $this->ot['pre']
3210 || ( $this->ot['wiki'] && $frame->isTemplate() )
3211 )
3212 ) {
3213 # No match in frame, use the supplied default
3214 $object = $parts->item( 0 )->getChildren();
3215 }
3216 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3217 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3218 $this->limitationWarn( 'post-expand-template-argument' );
3219 }
3220
3221 if ( $text === false && $object === false ) {
3222 # No match anywhere
3223 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3224 }
3225 if ( $error !== false ) {
3226 $text .= $error;
3227 }
3228 if ( $object !== false ) {
3229 $ret = array( 'object' => $object );
3230 } else {
3231 $ret = array( 'text' => $text );
3232 }
3233
3234 wfProfileOut( __METHOD__ );
3235 return $ret;
3236 }
3237
3238 /**
3239 * Return the text to be used for a given extension tag.
3240 * This is the ghost of strip().
3241 *
3242 * @param array $params Associative array of parameters:
3243 * name PPNode for the tag name
3244 * attr PPNode for unparsed text where tag attributes are thought to be
3245 * attributes Optional associative array of parsed attributes
3246 * inner Contents of extension element
3247 * noClose Original text did not have a close tag
3248 * @param PPFrame $frame
3249 */
3250 function extensionSubstitution( $params, $frame ) {
3251 global $wgRawHtml, $wgContLang;
3252
3253 $name = $frame->expand( $params['name'] );
3254 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3255 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3256
3257 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++) . self::MARKER_SUFFIX;
3258
3259 if ( $this->ot['html'] ) {
3260 $name = strtolower( $name );
3261
3262 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3263 if ( isset( $params['attributes'] ) ) {
3264 $attributes = $attributes + $params['attributes'];
3265 }
3266 switch ( $name ) {
3267 case 'html':
3268 if( $wgRawHtml ) {
3269 $output = $content;
3270 break;
3271 } else {
3272 throw new MWException( '<html> extension tag encountered unexpectedly' );
3273 }
3274 case 'nowiki':
3275 $output = Xml::escapeTagsOnly( $content );
3276 break;
3277 case 'math':
3278 $output = $wgContLang->armourMath(
3279 MathRenderer::renderMath( $content, $attributes ) );
3280 break;
3281 case 'gallery':
3282 $output = $this->renderImageGallery( $content, $attributes );
3283 break;
3284 default:
3285 if( isset( $this->mTagHooks[$name] ) ) {
3286 # Workaround for PHP bug 35229 and similar
3287 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3288 throw new MWException( "Tag hook for $name is not callable\n" );
3289 }
3290 $output = call_user_func_array( $this->mTagHooks[$name],
3291 array( $content, $attributes, $this ) );
3292 } else {
3293 $output = '<span class="error">Invalid tag extension name: ' .
3294 htmlspecialchars( $name ) . '</span>';
3295 }
3296 }
3297 } else {
3298 if ( is_null( $attrText ) ) {
3299 $attrText = '';
3300 }
3301 if ( isset( $params['attributes'] ) ) {
3302 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3303 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3304 htmlspecialchars( $attrValue ) . '"';
3305 }
3306 }
3307 if ( $content === null ) {
3308 $output = "<$name$attrText/>";
3309 } else {
3310 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3311 $output = "<$name$attrText>$content$close";
3312 }
3313 }
3314
3315 if ( $name === 'html' || $name === 'nowiki' ) {
3316 $this->mStripState->nowiki->setPair( $marker, $output );
3317 } else {
3318 $this->mStripState->general->setPair( $marker, $output );
3319 }
3320 return $marker;
3321 }
3322
3323 /**
3324 * Increment an include size counter
3325 *
3326 * @param string $type The type of expansion
3327 * @param integer $size The size of the text
3328 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3329 */
3330 function incrementIncludeSize( $type, $size ) {
3331 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3332 return false;
3333 } else {
3334 $this->mIncludeSizes[$type] += $size;
3335 return true;
3336 }
3337 }
3338
3339 /**
3340 * Increment the expensive function count
3341 *
3342 * @return boolean False if the limit has been exceeded
3343 */
3344 function incrementExpensiveFunctionCount() {
3345 global $wgExpensiveParserFunctionLimit;
3346 $this->mExpensiveFunctionCount++;
3347 if($this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit) {
3348 return true;
3349 }
3350 return false;
3351 }
3352
3353 /**
3354 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3355 * Fills $this->mDoubleUnderscores, returns the modified text
3356 */
3357 function doDoubleUnderscore( $text ) {
3358 // The position of __TOC__ needs to be recorded
3359 $mw = MagicWord::get( 'toc' );
3360 if( $mw->match( $text ) ) {
3361 $this->mShowToc = true;
3362 $this->mForceTocPosition = true;
3363
3364 // Set a placeholder. At the end we'll fill it in with the TOC.
3365 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3366
3367 // Only keep the first one.
3368 $text = $mw->replace( '', $text );
3369 }
3370
3371 // Now match and remove the rest of them
3372 $mwa = MagicWord::getDoubleUnderscoreArray();
3373 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3374
3375 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3376 $this->mOutput->mNoGallery = true;
3377 }
3378 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3379 $this->mShowToc = false;
3380 }
3381 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3382 $this->mOutput->setProperty( 'hiddencat', 'y' );
3383
3384 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( 'hidden-category-category' ) );
3385 if ( $containerCategory ) {
3386 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3387 } else {
3388 wfDebug( __METHOD__.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3389 }
3390 }
3391 # (bug 8068) Allow control over whether robots index a page.
3392 #
3393 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3394 # is not desirable, the last one on the page should win.
3395 if( isset( $this->mDoubleUnderscores['noindex'] ) ) {
3396 $this->mOutput->setIndexPolicy( 'noindex' );
3397 } elseif( isset( $this->mDoubleUnderscores['index'] ) ) {
3398 $this->mOutput->setIndexPolicy( 'index' );
3399 }
3400
3401 return $text;
3402 }
3403
3404 /**
3405 * This function accomplishes several tasks:
3406 * 1) Auto-number headings if that option is enabled
3407 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3408 * 3) Add a Table of contents on the top for users who have enabled the option
3409 * 4) Auto-anchor headings
3410 *
3411 * It loops through all headlines, collects the necessary data, then splits up the
3412 * string and re-inserts the newly formatted headlines.
3413 *
3414 * @param string $text
3415 * @param boolean $isMain
3416 * @private
3417 */
3418 function formatHeadings( $text, $isMain=true ) {
3419 global $wgMaxTocLevel, $wgContLang;
3420
3421 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3422 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3423 $showEditLink = 0;
3424 } else {
3425 $showEditLink = $this->mOptions->getEditSection();
3426 }
3427
3428 # Inhibit editsection links if requested in the page
3429 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3430 $showEditLink = 0;
3431 }
3432
3433 # Get all headlines for numbering them and adding funky stuff like [edit]
3434 # links - this is for later, but we need the number of headlines right now
3435 $matches = array();
3436 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3437
3438 # if there are fewer than 4 headlines in the article, do not show TOC
3439 # unless it's been explicitly enabled.
3440 $enoughToc = $this->mShowToc &&
3441 (($numMatches >= 4) || $this->mForceTocPosition);
3442
3443 # Allow user to stipulate that a page should have a "new section"
3444 # link added via __NEWSECTIONLINK__
3445 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3446 $this->mOutput->setNewSection( true );
3447 }
3448
3449 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3450 # override above conditions and always show TOC above first header
3451 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3452 $this->mShowToc = true;
3453 $enoughToc = true;
3454 }
3455
3456 # We need this to perform operations on the HTML
3457 $sk = $this->mOptions->getSkin();
3458
3459 # headline counter
3460 $headlineCount = 0;
3461 $numVisible = 0;
3462
3463 # Ugh .. the TOC should have neat indentation levels which can be
3464 # passed to the skin functions. These are determined here
3465 $toc = '';
3466 $full = '';
3467 $head = array();
3468 $sublevelCount = array();
3469 $levelCount = array();
3470 $toclevel = 0;
3471 $level = 0;
3472 $prevlevel = 0;
3473 $toclevel = 0;
3474 $prevtoclevel = 0;
3475 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3476 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3477 $tocraw = array();
3478
3479 foreach( $matches[3] as $headline ) {
3480 $isTemplate = false;
3481 $titleText = false;
3482 $sectionIndex = false;
3483 $numbering = '';
3484 $markerMatches = array();
3485 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3486 $serial = $markerMatches[1];
3487 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3488 $isTemplate = ($titleText != $baseTitleText);
3489 $headline = preg_replace("/^$markerRegex/", "", $headline);
3490 }
3491
3492 if( $toclevel ) {
3493 $prevlevel = $level;
3494 $prevtoclevel = $toclevel;
3495 }
3496 $level = $matches[1][$headlineCount];
3497
3498 if( $doNumberHeadings || $enoughToc ) {
3499
3500 if ( $level > $prevlevel ) {
3501 # Increase TOC level
3502 $toclevel++;
3503 $sublevelCount[$toclevel] = 0;
3504 if( $toclevel<$wgMaxTocLevel ) {
3505 $prevtoclevel = $toclevel;
3506 $toc .= $sk->tocIndent();
3507 $numVisible++;
3508 }
3509 }
3510 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3511 # Decrease TOC level, find level to jump to
3512
3513 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3514 # Can only go down to level 1
3515 $toclevel = 1;
3516 } else {
3517 for ($i = $toclevel; $i > 0; $i--) {
3518 if ( $levelCount[$i] == $level ) {
3519 # Found last matching level
3520 $toclevel = $i;
3521 break;
3522 }
3523 elseif ( $levelCount[$i] < $level ) {
3524 # Found first matching level below current level
3525 $toclevel = $i + 1;
3526 break;
3527 }
3528 }
3529 }
3530 if( $toclevel<$wgMaxTocLevel ) {
3531 if($prevtoclevel < $wgMaxTocLevel) {
3532 # Unindent only if the previous toc level was shown :p
3533 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3534 $prevtoclevel = $toclevel;
3535 } else {
3536 $toc .= $sk->tocLineEnd();
3537 }
3538 }
3539 }
3540 else {
3541 # No change in level, end TOC line
3542 if( $toclevel<$wgMaxTocLevel ) {
3543 $toc .= $sk->tocLineEnd();
3544 }
3545 }
3546
3547 $levelCount[$toclevel] = $level;
3548
3549 # count number of headlines for each level
3550 @$sublevelCount[$toclevel]++;
3551 $dot = 0;
3552 for( $i = 1; $i <= $toclevel; $i++ ) {
3553 if( !empty( $sublevelCount[$i] ) ) {
3554 if( $dot ) {
3555 $numbering .= '.';
3556 }
3557 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3558 $dot = 1;
3559 }
3560 }
3561 }
3562
3563 # The safe header is a version of the header text safe to use for links
3564 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3565 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3566
3567 # Remove link placeholders by the link text.
3568 # <!--LINK number-->
3569 # turns into
3570 # link text with suffix
3571 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3572
3573 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3574 $tocline = preg_replace(
3575 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3576 array( '', '<$1>'),
3577 $safeHeadline
3578 );
3579 $tocline = trim( $tocline );
3580
3581 # For the anchor, strip out HTML-y stuff period
3582 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3583 $safeHeadline = trim( $safeHeadline );
3584
3585 # Save headline for section edit hint before it's escaped
3586 $headlineHint = $safeHeadline;
3587 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3588 # HTML names must be case-insensitively unique (bug 10721)
3589 $arrayKey = strtolower( $safeHeadline );
3590
3591 # count how many in assoc. array so we can track dupes in anchors
3592 isset( $refers[$arrayKey] ) ? $refers[$arrayKey]++ : $refers[$arrayKey] = 1;
3593 $refcount[$headlineCount] = $refers[$arrayKey];
3594
3595 # Don't number the heading if it is the only one (looks silly)
3596 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3597 # the two are different if the line contains a link
3598 $headline=$numbering . ' ' . $headline;
3599 }
3600
3601 # Create the anchor for linking from the TOC to the section
3602 $anchor = $safeHeadline;
3603 if($refcount[$headlineCount] > 1 ) {
3604 $anchor .= '_' . $refcount[$headlineCount];
3605 }
3606 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3607 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3608 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3609 }
3610 # give headline the correct <h#> tag
3611 if( $showEditLink && $sectionIndex !== false ) {
3612 if( $isTemplate ) {
3613 # Put a T flag in the section identifier, to indicate to extractSections()
3614 # that sections inside <includeonly> should be counted.
3615 $editlink = $sk->doEditSectionLink(Title::newFromText( $titleText ), "T-$sectionIndex");
3616 } else {
3617 $editlink = $sk->doEditSectionLink($this->mTitle, $sectionIndex, $headlineHint);
3618 }
3619 } else {
3620 $editlink = '';
3621 }
3622 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3623
3624 $headlineCount++;
3625 }
3626
3627 $this->mOutput->setSections( $tocraw );
3628
3629 # Never ever show TOC if no headers
3630 if( $numVisible < 1 ) {
3631 $enoughToc = false;
3632 }
3633
3634 if( $enoughToc ) {
3635 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3636 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3637 }
3638 $toc = $sk->tocList( $toc );
3639 }
3640
3641 # split up and insert constructed headlines
3642
3643 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3644 $i = 0;
3645
3646 foreach( $blocks as $block ) {
3647 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3648 # This is the [edit] link that appears for the top block of text when
3649 # section editing is enabled
3650
3651 # Disabled because it broke block formatting
3652 # For example, a bullet point in the top line
3653 # $full .= $sk->editSectionLink(0);
3654 }
3655 $full .= $block;
3656 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3657 # Top anchor now in skin
3658 $full = $full.$toc;
3659 }
3660
3661 if( !empty( $head[$i] ) ) {
3662 $full .= $head[$i];
3663 }
3664 $i++;
3665 }
3666 if( $this->mForceTocPosition ) {
3667 return str_replace( '<!--MWTOC-->', $toc, $full );
3668 } else {
3669 return $full;
3670 }
3671 }
3672
3673 /**
3674 * Transform wiki markup when saving a page by doing \r\n -> \n
3675 * conversion, substitting signatures, {{subst:}} templates, etc.
3676 *
3677 * @param string $text the text to transform
3678 * @param Title &$title the Title object for the current article
3679 * @param User &$user the User object describing the current user
3680 * @param ParserOptions $options parsing options
3681 * @param bool $clearState whether to clear the parser state first
3682 * @return string the altered wiki markup
3683 * @public
3684 */
3685 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3686 $this->mOptions = $options;
3687 $this->setTitle( $title );
3688 $this->setOutputType( self::OT_WIKI );
3689
3690 if ( $clearState ) {
3691 $this->clearState();
3692 }
3693
3694 $pairs = array(
3695 "\r\n" => "\n",
3696 );
3697 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3698 $text = $this->pstPass2( $text, $user );
3699 $text = $this->mStripState->unstripBoth( $text );
3700 return $text;
3701 }
3702
3703 /**
3704 * Pre-save transform helper function
3705 * @private
3706 */
3707 function pstPass2( $text, $user ) {
3708 global $wgContLang, $wgLocaltimezone;
3709
3710 /* Note: This is the timestamp saved as hardcoded wikitext to
3711 * the database, we use $wgContLang here in order to give
3712 * everyone the same signature and use the default one rather
3713 * than the one selected in each user's preferences.
3714 *
3715 * (see also bug 12815)
3716 */
3717 $ts = $this->mOptions->getTimestamp();
3718 $tz = wfMsgForContent( 'timezone-utc' );
3719 if ( isset( $wgLocaltimezone ) ) {
3720 $unixts = wfTimestamp( TS_UNIX, $ts );
3721 $oldtz = getenv( 'TZ' );
3722 putenv( 'TZ='.$wgLocaltimezone );
3723 $ts = date( 'YmdHis', $unixts );
3724 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3725 putenv( 'TZ='.$oldtz );
3726 }
3727
3728 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3729
3730 # Variable replacement
3731 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3732 $text = $this->replaceVariables( $text );
3733
3734 # Signatures
3735 $sigText = $this->getUserSig( $user );
3736 $text = strtr( $text, array(
3737 '~~~~~' => $d,
3738 '~~~~' => "$sigText $d",
3739 '~~~' => $sigText
3740 ) );
3741
3742 # Context links: [[|name]] and [[name (context)|]]
3743 #
3744 global $wgLegalTitleChars;
3745 $tc = "[$wgLegalTitleChars]";
3746 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3747
3748 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3749 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3750 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3751 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3752
3753 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3754 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3755 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3756 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3757
3758 $t = $this->mTitle->getText();
3759 $m = array();
3760 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3761 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3762 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3763 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3764 } else {
3765 # if there's no context, don't bother duplicating the title
3766 $text = preg_replace( $p2, '[[\\1]]', $text );
3767 }
3768
3769 # Trim trailing whitespace
3770 $text = rtrim( $text );
3771
3772 return $text;
3773 }
3774
3775 /**
3776 * Fetch the user's signature text, if any, and normalize to
3777 * validated, ready-to-insert wikitext.
3778 *
3779 * @param User $user
3780 * @return string
3781 * @private
3782 */
3783 function getUserSig( &$user ) {
3784 global $wgMaxSigChars;
3785
3786 $username = $user->getName();
3787 $nickname = $user->getOption( 'nickname' );
3788 $nickname = $nickname === '' ? $username : $nickname;
3789
3790 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3791 $nickname = $username;
3792 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
3793 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3794 # Sig. might contain markup; validate this
3795 if( $this->validateSig( $nickname ) !== false ) {
3796 # Validated; clean up (if needed) and return it
3797 return $this->cleanSig( $nickname, true );
3798 } else {
3799 # Failed to validate; fall back to the default
3800 $nickname = $username;
3801 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
3802 }
3803 }
3804
3805 // Make sure nickname doesnt get a sig in a sig
3806 $nickname = $this->cleanSigInSig( $nickname );
3807
3808 # If we're still here, make it a link to the user page
3809 $userText = wfEscapeWikiText( $username );
3810 $nickText = wfEscapeWikiText( $nickname );
3811 if ( $user->isAnon() ) {
3812 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3813 } else {
3814 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3815 }
3816 }
3817
3818 /**
3819 * Check that the user's signature contains no bad XML
3820 *
3821 * @param string $text
3822 * @return mixed An expanded string, or false if invalid.
3823 */
3824 function validateSig( $text ) {
3825 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3826 }
3827
3828 /**
3829 * Clean up signature text
3830 *
3831 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3832 * 2) Substitute all transclusions
3833 *
3834 * @param string $text
3835 * @param $parsing Whether we're cleaning (preferences save) or parsing
3836 * @return string Signature text
3837 */
3838 function cleanSig( $text, $parsing = false ) {
3839 if ( !$parsing ) {
3840 global $wgTitle;
3841 $this->clearState();
3842 $this->setTitle( $wgTitle );
3843 $this->mOptions = new ParserOptions;
3844 $this->setOutputType = self::OT_PREPROCESS;
3845 }
3846
3847 # Option to disable this feature
3848 if ( !$this->mOptions->getCleanSignatures() ) {
3849 return $text;
3850 }
3851
3852 # FIXME: regex doesn't respect extension tags or nowiki
3853 # => Move this logic to braceSubstitution()
3854 $substWord = MagicWord::get( 'subst' );
3855 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3856 $substText = '{{' . $substWord->getSynonym( 0 );
3857
3858 $text = preg_replace( $substRegex, $substText, $text );
3859 $text = $this->cleanSigInSig( $text );
3860 $dom = $this->preprocessToDom( $text );
3861 $frame = $this->getPreprocessor()->newFrame();
3862 $text = $frame->expand( $dom );
3863
3864 if ( !$parsing ) {
3865 $text = $this->mStripState->unstripBoth( $text );
3866 }
3867
3868 return $text;
3869 }
3870
3871 /**
3872 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3873 * @param string $text
3874 * @return string Signature text with /~{3,5}/ removed
3875 */
3876 function cleanSigInSig( $text ) {
3877 $text = preg_replace( '/~{3,5}/', '', $text );
3878 return $text;
3879 }
3880
3881 /**
3882 * Set up some variables which are usually set up in parse()
3883 * so that an external function can call some class members with confidence
3884 * @public
3885 */
3886 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3887 $this->setTitle( $title );
3888 $this->mOptions = $options;
3889 $this->setOutputType( $outputType );
3890 if ( $clearState ) {
3891 $this->clearState();
3892 }
3893 }
3894
3895 /**
3896 * Wrapper for preprocess()
3897 *
3898 * @param string $text the text to preprocess
3899 * @param ParserOptions $options options
3900 * @return string
3901 * @public
3902 */
3903 function transformMsg( $text, $options ) {
3904 global $wgTitle;
3905 static $executing = false;
3906
3907 # Guard against infinite recursion
3908 if ( $executing ) {
3909 return $text;
3910 }
3911 $executing = true;
3912
3913 wfProfileIn(__METHOD__);
3914 $text = $this->preprocess( $text, $wgTitle, $options );
3915
3916 $executing = false;
3917 wfProfileOut(__METHOD__);
3918 return $text;
3919 }
3920
3921 /**
3922 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3923 * The callback should have the following form:
3924 * function myParserHook( $text, $params, &$parser ) { ... }
3925 *
3926 * Transform and return $text. Use $parser for any required context, e.g. use
3927 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3928 *
3929 * @public
3930 *
3931 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3932 * @param mixed $callback The callback function (and object) to use for the tag
3933 *
3934 * @return The old value of the mTagHooks array associated with the hook
3935 */
3936 function setHook( $tag, $callback ) {
3937 $tag = strtolower( $tag );
3938 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
3939 $this->mTagHooks[$tag] = $callback;
3940 if( !in_array( $tag, $this->mStripList ) ) {
3941 $this->mStripList[] = $tag;
3942 }
3943
3944 return $oldVal;
3945 }
3946
3947 function setTransparentTagHook( $tag, $callback ) {
3948 $tag = strtolower( $tag );
3949 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
3950 $this->mTransparentTagHooks[$tag] = $callback;
3951
3952 return $oldVal;
3953 }
3954
3955 /**
3956 * Remove all tag hooks
3957 */
3958 function clearTagHooks() {
3959 $this->mTagHooks = array();
3960 $this->mStripList = $this->mDefaultStripList;
3961 }
3962
3963 /**
3964 * Create a function, e.g. {{sum:1|2|3}}
3965 * The callback function should have the form:
3966 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3967 *
3968 * Or with SFH_OBJECT_ARGS:
3969 * function myParserFunction( $parser, $frame, $args ) { ... }
3970 *
3971 * The callback may either return the text result of the function, or an array with the text
3972 * in element 0, and a number of flags in the other elements. The names of the flags are
3973 * specified in the keys. Valid flags are:
3974 * found The text returned is valid, stop processing the template. This
3975 * is on by default.
3976 * nowiki Wiki markup in the return value should be escaped
3977 * isHTML The returned text is HTML, armour it against wikitext transformation
3978 *
3979 * @public
3980 *
3981 * @param string $id The magic word ID
3982 * @param mixed $callback The callback function (and object) to use
3983 * @param integer $flags a combination of the following flags:
3984 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
3985 *
3986 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
3987 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
3988 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
3989 * the arguments, and to control the way they are expanded.
3990 *
3991 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
3992 * arguments, for instance:
3993 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
3994 *
3995 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
3996 * future versions. Please call $frame->expand() on it anyway so that your code keeps
3997 * working if/when this is changed.
3998 *
3999 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4000 * expansion.
4001 *
4002 * Please read the documentation in includes/parser/Preprocessor.php for more information
4003 * about the methods available in PPFrame and PPNode.
4004 *
4005 * @return The old callback function for this name, if any
4006 */
4007 function setFunctionHook( $id, $callback, $flags = 0 ) {
4008 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4009 $this->mFunctionHooks[$id] = array( $callback, $flags );
4010
4011 # Add to function cache
4012 $mw = MagicWord::get( $id );
4013 if( !$mw )
4014 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4015
4016 $synonyms = $mw->getSynonyms();
4017 $sensitive = intval( $mw->isCaseSensitive() );
4018
4019 foreach ( $synonyms as $syn ) {
4020 # Case
4021 if ( !$sensitive ) {
4022 $syn = strtolower( $syn );
4023 }
4024 # Add leading hash
4025 if ( !( $flags & SFH_NO_HASH ) ) {
4026 $syn = '#' . $syn;
4027 }
4028 # Remove trailing colon
4029 if ( substr( $syn, -1, 1 ) === ':' ) {
4030 $syn = substr( $syn, 0, -1 );
4031 }
4032 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4033 }
4034 return $oldVal;
4035 }
4036
4037 /**
4038 * Get all registered function hook identifiers
4039 *
4040 * @return array
4041 */
4042 function getFunctionHooks() {
4043 return array_keys( $this->mFunctionHooks );
4044 }
4045
4046 /**
4047 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4048 * Placeholders created in Skin::makeLinkObj()
4049 * Returns an array of link CSS classes, indexed by PDBK.
4050 */
4051 function replaceLinkHolders( &$text, $options = 0 ) {
4052 return $this->mLinkHolders->replace( $text );
4053 }
4054
4055 /**
4056 * Replace <!--LINK--> link placeholders with plain text of links
4057 * (not HTML-formatted).
4058 * @param string $text
4059 * @return string
4060 */
4061 function replaceLinkHoldersText( $text ) {
4062 return $this->mLinkHolders->replaceText( $text );
4063 }
4064
4065 /**
4066 * Tag hook handler for 'pre'.
4067 */
4068 function renderPreTag( $text, $attribs ) {
4069 // Backwards-compatibility hack
4070 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4071
4072 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4073 return wfOpenElement( 'pre', $attribs ) .
4074 Xml::escapeTagsOnly( $content ) .
4075 '</pre>';
4076 }
4077
4078 /**
4079 * Renders an image gallery from a text with one line per image.
4080 * text labels may be given by using |-style alternative text. E.g.
4081 * Image:one.jpg|The number "1"
4082 * Image:tree.jpg|A tree
4083 * given as text will return the HTML of a gallery with two images,
4084 * labeled 'The number "1"' and
4085 * 'A tree'.
4086 */
4087 function renderImageGallery( $text, $params ) {
4088 $ig = new ImageGallery();
4089 $ig->setContextTitle( $this->mTitle );
4090 $ig->setShowBytes( false );
4091 $ig->setShowFilename( false );
4092 $ig->setParser( $this );
4093 $ig->setHideBadImages();
4094 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4095 $ig->useSkin( $this->mOptions->getSkin() );
4096 $ig->mRevisionId = $this->mRevisionId;
4097
4098 if( isset( $params['caption'] ) ) {
4099 $caption = $params['caption'];
4100 $caption = htmlspecialchars( $caption );
4101 $caption = $this->replaceInternalLinks( $caption );
4102 $ig->setCaptionHtml( $caption );
4103 }
4104 if( isset( $params['perrow'] ) ) {
4105 $ig->setPerRow( $params['perrow'] );
4106 }
4107 if( isset( $params['widths'] ) ) {
4108 $ig->setWidths( $params['widths'] );
4109 }
4110 if( isset( $params['heights'] ) ) {
4111 $ig->setHeights( $params['heights'] );
4112 }
4113
4114 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4115
4116 $lines = StringUtils::explode( "\n", $text );
4117 foreach ( $lines as $line ) {
4118 # match lines like these:
4119 # Image:someimage.jpg|This is some image
4120 $matches = array();
4121 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4122 # Skip empty lines
4123 if ( count( $matches ) == 0 ) {
4124 continue;
4125 }
4126
4127 if ( strpos( $matches[0], '%' ) !== false )
4128 $matches[1] = urldecode( $matches[1] );
4129 $tp = Title::newFromText( $matches[1]/*, NS_IMAGE*/ );
4130 $nt =& $tp;
4131 if( is_null( $nt ) ) {
4132 # Bogus title. Ignore these so we don't bomb out later.
4133 continue;
4134 }
4135 if ( isset( $matches[3] ) ) {
4136 $label = $matches[3];
4137 } else {
4138 $label = '';
4139 }
4140
4141 $html = $this->recursiveTagParse( trim( $label ) );
4142
4143 $ig->add( $nt, $html );
4144
4145 # Only add real images (bug #5586)
4146 if ( $nt->getNamespace() == NS_IMAGE ) {
4147 $this->mOutput->addImage( $nt->getDBkey() );
4148 }
4149 }
4150 return $ig->toHTML();
4151 }
4152
4153 function getImageParams( $handler ) {
4154 if ( $handler ) {
4155 $handlerClass = get_class( $handler );
4156 } else {
4157 $handlerClass = '';
4158 }
4159 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4160 // Initialise static lists
4161 static $internalParamNames = array(
4162 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4163 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4164 'bottom', 'text-bottom' ),
4165 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4166 'upright', 'border' ),
4167 );
4168 static $internalParamMap;
4169 if ( !$internalParamMap ) {
4170 $internalParamMap = array();
4171 foreach ( $internalParamNames as $type => $names ) {
4172 foreach ( $names as $name ) {
4173 $magicName = str_replace( '-', '_', "img_$name" );
4174 $internalParamMap[$magicName] = array( $type, $name );
4175 }
4176 }
4177 }
4178
4179 // Add handler params
4180 $paramMap = $internalParamMap;
4181 if ( $handler ) {
4182 $handlerParamMap = $handler->getParamMap();
4183 foreach ( $handlerParamMap as $magic => $paramName ) {
4184 $paramMap[$magic] = array( 'handler', $paramName );
4185 }
4186 }
4187 $this->mImageParams[$handlerClass] = $paramMap;
4188 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4189 }
4190 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4191 }
4192
4193 /**
4194 * Parse image options text and use it to make an image
4195 * @param Title $title
4196 * @param string $options
4197 * @param LinkHolderArray $holders
4198 */
4199 function makeImage( $title, $options, $holders = false ) {
4200 # Check if the options text is of the form "options|alt text"
4201 # Options are:
4202 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4203 # * left no resizing, just left align. label is used for alt= only
4204 # * right same, but right aligned
4205 # * none same, but not aligned
4206 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4207 # * center center the image
4208 # * framed Keep original image size, no magnify-button.
4209 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4210 # * upright reduce width for upright images, rounded to full __0 px
4211 # * border draw a 1px border around the image
4212 # vertical-align values (no % or length right now):
4213 # * baseline
4214 # * sub
4215 # * super
4216 # * top
4217 # * text-top
4218 # * middle
4219 # * bottom
4220 # * text-bottom
4221
4222 $parts = StringUtils::explode( "|", $options );
4223 $sk = $this->mOptions->getSkin();
4224
4225 # Give extensions a chance to select the file revision for us
4226 $skip = $time = $descQuery = false;
4227 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4228
4229 if ( $skip ) {
4230 return $sk->link( $title );
4231 }
4232
4233 # Get parameter map
4234 $file = wfFindFile( $title, $time );
4235 $handler = $file ? $file->getHandler() : false;
4236
4237 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4238
4239 # Process the input parameters
4240 $caption = '';
4241 $params = array( 'frame' => array(), 'handler' => array(),
4242 'horizAlign' => array(), 'vertAlign' => array() );
4243 foreach( $parts as $part ) {
4244 $part = trim( $part );
4245 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4246 $validated = false;
4247 if( isset( $paramMap[$magicName] ) ) {
4248 list( $type, $paramName ) = $paramMap[$magicName];
4249
4250 // Special case; width and height come in one variable together
4251 if( $type === 'handler' && $paramName === 'width' ) {
4252 $m = array();
4253 # (bug 13500) In both cases (width/height and width only),
4254 # permit trailing "px" for backward compatibility.
4255 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4256 $width = intval( $m[1] );
4257 $height = intval( $m[2] );
4258 if ( $handler->validateParam( 'width', $width ) ) {
4259 $params[$type]['width'] = $width;
4260 $validated = true;
4261 }
4262 if ( $handler->validateParam( 'height', $height ) ) {
4263 $params[$type]['height'] = $height;
4264 $validated = true;
4265 }
4266 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4267 $width = intval( $value );
4268 if ( $handler->validateParam( 'width', $width ) ) {
4269 $params[$type]['width'] = $width;
4270 $validated = true;
4271 }
4272 } // else no validation -- bug 13436
4273 } else {
4274 if ( $type === 'handler' ) {
4275 # Validate handler parameter
4276 $validated = $handler->validateParam( $paramName, $value );
4277 } else {
4278 # Validate internal parameters
4279 switch( $paramName ) {
4280 case "manualthumb":
4281 /// @fixme - possibly check validity here?
4282 /// downstream behavior seems odd with missing manual thumbs.
4283 $validated = true;
4284 break;
4285 default:
4286 // Most other things appear to be empty or numeric...
4287 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4288 }
4289 }
4290
4291 if ( $validated ) {
4292 $params[$type][$paramName] = $value;
4293 }
4294 }
4295 }
4296 if ( !$validated ) {
4297 $caption = $part;
4298 }
4299 }
4300
4301 # Process alignment parameters
4302 if ( $params['horizAlign'] ) {
4303 $params['frame']['align'] = key( $params['horizAlign'] );
4304 }
4305 if ( $params['vertAlign'] ) {
4306 $params['frame']['valign'] = key( $params['vertAlign'] );
4307 }
4308
4309 # Strip bad stuff out of the alt text
4310 # We can't just use replaceLinkHoldersText() here, because if this function
4311 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4312 if ( $holders ) {
4313 $alt = $holders->replaceText( $caption );
4314 } else {
4315 $alt = $this->replaceLinkHoldersText( $caption );
4316 }
4317
4318 # make sure there are no placeholders in thumbnail attributes
4319 # that are later expanded to html- so expand them now and
4320 # remove the tags
4321 $alt = $this->mStripState->unstripBoth( $alt );
4322 $alt = Sanitizer::stripAllTags( $alt );
4323
4324 $params['frame']['alt'] = $alt;
4325 $params['frame']['caption'] = $caption;
4326
4327 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4328
4329 # Linker does the rest
4330 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4331
4332 # Give the handler a chance to modify the parser object
4333 if ( $handler ) {
4334 $handler->parserTransformHook( $this, $file );
4335 }
4336
4337 return $ret;
4338 }
4339
4340 /**
4341 * Set a flag in the output object indicating that the content is dynamic and
4342 * shouldn't be cached.
4343 */
4344 function disableCache() {
4345 wfDebug( "Parser output marked as uncacheable.\n" );
4346 $this->mOutput->mCacheTime = -1;
4347 }
4348
4349 /**#@+
4350 * Callback from the Sanitizer for expanding items found in HTML attribute
4351 * values, so they can be safely tested and escaped.
4352 * @param string $text
4353 * @param PPFrame $frame
4354 * @return string
4355 * @private
4356 */
4357 function attributeStripCallback( &$text, $frame = false ) {
4358 $text = $this->replaceVariables( $text, $frame );
4359 $text = $this->mStripState->unstripBoth( $text );
4360 return $text;
4361 }
4362
4363 /**#@-*/
4364
4365 /**#@+
4366 * Accessor/mutator
4367 */
4368 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4369 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4370 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4371 /**#@-*/
4372
4373 /**#@+
4374 * Accessor
4375 */
4376 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4377 /**#@-*/
4378
4379
4380 /**
4381 * Break wikitext input into sections, and either pull or replace
4382 * some particular section's text.
4383 *
4384 * External callers should use the getSection and replaceSection methods.
4385 *
4386 * @param string $text Page wikitext
4387 * @param string $section A section identifier string of the form:
4388 * <flag1> - <flag2> - ... - <section number>
4389 *
4390 * Currently the only recognised flag is "T", which means the target section number
4391 * was derived during a template inclusion parse, in other words this is a template
4392 * section edit link. If no flags are given, it was an ordinary section edit link.
4393 * This flag is required to avoid a section numbering mismatch when a section is
4394 * enclosed by <includeonly> (bug 6563).
4395 *
4396 * The section number 0 pulls the text before the first heading; other numbers will
4397 * pull the given section along with its lower-level subsections. If the section is
4398 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4399 *
4400 * @param string $mode One of "get" or "replace"
4401 * @param string $newText Replacement text for section data.
4402 * @return string for "get", the extracted section text.
4403 * for "replace", the whole page with the section replaced.
4404 */
4405 private function extractSections( $text, $section, $mode, $newText='' ) {
4406 global $wgTitle;
4407 $this->clearState();
4408 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4409 $this->mOptions = new ParserOptions;
4410 $this->setOutputType( self::OT_WIKI );
4411 $outText = '';
4412 $frame = $this->getPreprocessor()->newFrame();
4413
4414 // Process section extraction flags
4415 $flags = 0;
4416 $sectionParts = explode( '-', $section );
4417 $sectionIndex = array_pop( $sectionParts );
4418 foreach ( $sectionParts as $part ) {
4419 if ( $part === 'T' ) {
4420 $flags |= self::PTD_FOR_INCLUSION;
4421 }
4422 }
4423 // Preprocess the text
4424 $root = $this->preprocessToDom( $text, $flags );
4425
4426 // <h> nodes indicate section breaks
4427 // They can only occur at the top level, so we can find them by iterating the root's children
4428 $node = $root->getFirstChild();
4429
4430 // Find the target section
4431 if ( $sectionIndex == 0 ) {
4432 // Section zero doesn't nest, level=big
4433 $targetLevel = 1000;
4434 } else {
4435 while ( $node ) {
4436 if ( $node->getName() === 'h' ) {
4437 $bits = $node->splitHeading();
4438 if ( $bits['i'] == $sectionIndex ) {
4439 $targetLevel = $bits['level'];
4440 break;
4441 }
4442 }
4443 if ( $mode === 'replace' ) {
4444 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4445 }
4446 $node = $node->getNextSibling();
4447 }
4448 }
4449
4450 if ( !$node ) {
4451 // Not found
4452 if ( $mode === 'get' ) {
4453 return $newText;
4454 } else {
4455 return $text;
4456 }
4457 }
4458
4459 // Find the end of the section, including nested sections
4460 do {
4461 if ( $node->getName() === 'h' ) {
4462 $bits = $node->splitHeading();
4463 $curLevel = $bits['level'];
4464 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4465 break;
4466 }
4467 }
4468 if ( $mode === 'get' ) {
4469 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4470 }
4471 $node = $node->getNextSibling();
4472 } while ( $node );
4473
4474 // Write out the remainder (in replace mode only)
4475 if ( $mode === 'replace' ) {
4476 // Output the replacement text
4477 // Add two newlines on -- trailing whitespace in $newText is conventionally
4478 // stripped by the editor, so we need both newlines to restore the paragraph gap
4479 $outText .= $newText . "\n\n";
4480 while ( $node ) {
4481 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4482 $node = $node->getNextSibling();
4483 }
4484 }
4485
4486 if ( is_string( $outText ) ) {
4487 // Re-insert stripped tags
4488 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4489 }
4490
4491 return $outText;
4492 }
4493
4494 /**
4495 * This function returns the text of a section, specified by a number ($section).
4496 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4497 * the first section before any such heading (section 0).
4498 *
4499 * If a section contains subsections, these are also returned.
4500 *
4501 * @param string $text text to look in
4502 * @param string $section section identifier
4503 * @param string $deftext default to return if section is not found
4504 * @return string text of the requested section
4505 */
4506 public function getSection( $text, $section, $deftext='' ) {
4507 return $this->extractSections( $text, $section, "get", $deftext );
4508 }
4509
4510 public function replaceSection( $oldtext, $section, $text ) {
4511 return $this->extractSections( $oldtext, $section, "replace", $text );
4512 }
4513
4514 /**
4515 * Get the timestamp associated with the current revision, adjusted for
4516 * the default server-local timestamp
4517 */
4518 function getRevisionTimestamp() {
4519 if ( is_null( $this->mRevisionTimestamp ) ) {
4520 wfProfileIn( __METHOD__ );
4521 global $wgContLang;
4522 $dbr = wfGetDB( DB_SLAVE );
4523 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4524 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4525
4526 // Normalize timestamp to internal MW format for timezone processing.
4527 // This has the added side-effect of replacing a null value with
4528 // the current time, which gives us more sensible behavior for
4529 // previews.
4530 $timestamp = wfTimestamp( TS_MW, $timestamp );
4531
4532 // The cryptic '' timezone parameter tells to use the site-default
4533 // timezone offset instead of the user settings.
4534 //
4535 // Since this value will be saved into the parser cache, served
4536 // to other users, and potentially even used inside links and such,
4537 // it needs to be consistent for all visitors.
4538 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4539
4540 wfProfileOut( __METHOD__ );
4541 }
4542 return $this->mRevisionTimestamp;
4543 }
4544
4545 /**
4546 * Mutator for $mDefaultSort
4547 *
4548 * @param $sort New value
4549 */
4550 public function setDefaultSort( $sort ) {
4551 $this->mDefaultSort = $sort;
4552 }
4553
4554 /**
4555 * Accessor for $mDefaultSort
4556 * Will use the title/prefixed title if none is set
4557 *
4558 * @return string
4559 */
4560 public function getDefaultSort() {
4561 global $wgCategoryPrefixedDefaultSortkey;
4562 if( $this->mDefaultSort !== false ) {
4563 return $this->mDefaultSort;
4564 } elseif ($this->mTitle->getNamespace() == NS_CATEGORY ||
4565 !$wgCategoryPrefixedDefaultSortkey) {
4566 return $this->mTitle->getText();
4567 } else {
4568 return $this->mTitle->getPrefixedText();
4569 }
4570 }
4571
4572 /**
4573 * Try to guess the section anchor name based on a wikitext fragment
4574 * presumably extracted from a heading, for example "Header" from
4575 * "== Header ==".
4576 */
4577 public function guessSectionNameFromWikiText( $text ) {
4578 # Strip out wikitext links(they break the anchor)
4579 $text = $this->stripSectionName( $text );
4580 $headline = Sanitizer::decodeCharReferences( $text );
4581 # strip out HTML
4582 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
4583 $headline = trim( $headline );
4584 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4585 $replacearray = array(
4586 '%3A' => ':',
4587 '%' => '.'
4588 );
4589 return str_replace(
4590 array_keys( $replacearray ),
4591 array_values( $replacearray ),
4592 $sectionanchor );
4593 }
4594
4595 /**
4596 * Strips a text string of wikitext for use in a section anchor
4597 *
4598 * Accepts a text string and then removes all wikitext from the
4599 * string and leaves only the resultant text (i.e. the result of
4600 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4601 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4602 * to create valid section anchors by mimicing the output of the
4603 * parser when headings are parsed.
4604 *
4605 * @param $text string Text string to be stripped of wikitext
4606 * for use in a Section anchor
4607 * @return Filtered text string
4608 */
4609 public function stripSectionName( $text ) {
4610 # Strip internal link markup
4611 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4612 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4613
4614 # Strip external link markup (FIXME: Not Tolerant to blank link text
4615 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4616 # on how many empty links there are on the page - need to figure that out.
4617 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4618
4619 # Parse wikitext quotes (italics & bold)
4620 $text = $this->doQuotes($text);
4621
4622 # Strip HTML tags
4623 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
4624 return $text;
4625 }
4626
4627 function srvus( $text ) {
4628 return $this->testSrvus( $text, $this->mOutputType );
4629 }
4630
4631 /**
4632 * strip/replaceVariables/unstrip for preprocessor regression testing
4633 */
4634 function testSrvus( $text, $title, $options, $outputType = self::OT_HTML ) {
4635 $this->clearState();
4636 if ( ! ( $title instanceof Title ) ) {
4637 $title = Title::newFromText( $title );
4638 }
4639 $this->mTitle = $title;
4640 $this->mOptions = $options;
4641 $this->setOutputType( $outputType );
4642 $text = $this->replaceVariables( $text );
4643 $text = $this->mStripState->unstripBoth( $text );
4644 $text = Sanitizer::removeHTMLtags( $text );
4645 return $text;
4646 }
4647
4648 function testPst( $text, $title, $options ) {
4649 global $wgUser;
4650 if ( ! ( $title instanceof Title ) ) {
4651 $title = Title::newFromText( $title );
4652 }
4653 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4654 }
4655
4656 function testPreprocess( $text, $title, $options ) {
4657 if ( ! ( $title instanceof Title ) ) {
4658 $title = Title::newFromText( $title );
4659 }
4660 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
4661 }
4662
4663 function markerSkipCallback( $s, $callback ) {
4664 $i = 0;
4665 $out = '';
4666 while ( $i < strlen( $s ) ) {
4667 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
4668 if ( $markerStart === false ) {
4669 $out .= call_user_func( $callback, substr( $s, $i ) );
4670 break;
4671 } else {
4672 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4673 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
4674 if ( $markerEnd === false ) {
4675 $out .= substr( $s, $markerStart );
4676 break;
4677 } else {
4678 $markerEnd += strlen( self::MARKER_SUFFIX );
4679 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4680 $i = $markerEnd;
4681 }
4682 }
4683 }
4684 return $out;
4685 }
4686 }
4687
4688 /**
4689 * @todo document, briefly.
4690 * @ingroup Parser
4691 */
4692 class StripState {
4693 var $general, $nowiki;
4694
4695 function __construct() {
4696 $this->general = new ReplacementArray;
4697 $this->nowiki = new ReplacementArray;
4698 }
4699
4700 function unstripGeneral( $text ) {
4701 wfProfileIn( __METHOD__ );
4702 do {
4703 $oldText = $text;
4704 $text = $this->general->replace( $text );
4705 } while ( $text !== $oldText );
4706 wfProfileOut( __METHOD__ );
4707 return $text;
4708 }
4709
4710 function unstripNoWiki( $text ) {
4711 wfProfileIn( __METHOD__ );
4712 do {
4713 $oldText = $text;
4714 $text = $this->nowiki->replace( $text );
4715 } while ( $text !== $oldText );
4716 wfProfileOut( __METHOD__ );
4717 return $text;
4718 }
4719
4720 function unstripBoth( $text ) {
4721 wfProfileIn( __METHOD__ );
4722 do {
4723 $oldText = $text;
4724 $text = $this->general->replace( $text );
4725 $text = $this->nowiki->replace( $text );
4726 } while ( $text !== $oldText );
4727 wfProfileOut( __METHOD__ );
4728 return $text;
4729 }
4730 }
4731
4732 /**
4733 * @todo document, briefly.
4734 * @ingroup Parser
4735 */
4736 class OnlyIncludeReplacer {
4737 var $output = '';
4738
4739 function replace( $matches ) {
4740 if ( substr( $matches[1], -1 ) === "\n" ) {
4741 $this->output .= substr( $matches[1], 0, -1 );
4742 } else {
4743 $this->output .= $matches[1];
4744 }
4745 }
4746 }