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