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