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