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