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