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