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