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