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