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