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