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