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