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