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