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