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