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