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