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