ee7383dc2fc58fdb969b6302479aeb85e9d4ec18
[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, $wgEnforceHtmlIds;
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 ( $wgEnforceHtmlIds ) {
3658 $legacyHeadline = false;
3659 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
3660 'noninitial' );
3661 } else {
3662 # For reverse compatibility, provide an id that's
3663 # HTML4-compatible, like we used to.
3664 #
3665 # It may be worth noting, academically, that it's possible for
3666 # the legacy anchor to conflict with a non-legacy headline
3667 # anchor on the page. In this case likely the "correct" thing
3668 # would be to either drop the legacy anchors or make sure
3669 # they're numbered first. However, this would require people
3670 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3671 # manually, so let's not bother worrying about it.
3672 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
3673 'noninitial' );
3674 $safeHeadline = Sanitizer::escapeId( $safeHeadline, 'xml' );
3675
3676 if ( $legacyHeadline == $safeHeadline ) {
3677 # No reason to have both (in fact, we can't)
3678 $legacyHeadline = false;
3679 } elseif ( $legacyHeadline != Sanitizer::escapeId(
3680 $legacyHeadline, 'xml' ) ) {
3681 # The legacy id is invalid XML. We used to allow this, but
3682 # there's no reason to do so anymore. Backward
3683 # compatibility will fail slightly in this case, but it's
3684 # no big deal.
3685 $legacyHeadline = false;
3686 }
3687 }
3688
3689 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3690 # Does this apply to Unicode characters? Because we aren't
3691 # handling those here.
3692 $arrayKey = strtolower( $safeHeadline );
3693 if ( $legacyHeadline === false ) {
3694 $legacyArrayKey = false;
3695 } else {
3696 $legacyArrayKey = strtolower( $legacyHeadline );
3697 }
3698
3699 # count how many in assoc. array so we can track dupes in anchors
3700 if ( isset( $refers[$arrayKey] ) ) {
3701 $refers[$arrayKey]++;
3702 } else {
3703 $refers[$arrayKey] = 1;
3704 }
3705 if ( isset( $refers[$legacyArrayKey] ) ) {
3706 $refers[$legacyArrayKey]++;
3707 } else {
3708 $refers[$legacyArrayKey] = 1;
3709 }
3710
3711 # Don't number the heading if it is the only one (looks silly)
3712 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3713 # the two are different if the line contains a link
3714 $headline=$numbering . ' ' . $headline;
3715 }
3716
3717 # Create the anchor for linking from the TOC to the section
3718 $anchor = $safeHeadline;
3719 $legacyAnchor = $legacyHeadline;
3720 if ( $refers[$arrayKey] > 1 ) {
3721 $anchor .= '_' . $refers[$arrayKey];
3722 }
3723 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3724 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3725 }
3726 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3727 $toc .= $sk->tocLine($anchor, $tocline,
3728 $numbering, $toclevel, ($isTemplate ? false : $sectionIndex));
3729 }
3730
3731 # Add the section to the section tree
3732 # Find the DOM node for this header
3733 while ( $node && !$isTemplate ) {
3734 if ( $node->getName() === 'h' ) {
3735 $bits = $node->splitHeading();
3736 if ( $bits['i'] == $sectionIndex )
3737 break;
3738 }
3739 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
3740 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
3741 $node = $node->getNextSibling();
3742 }
3743 $tocraw[] = array(
3744 'toclevel' => $toclevel,
3745 'level' => $level,
3746 'line' => $tocline,
3747 'number' => $numbering,
3748 'index' => ($isTemplate ? 'T-' : '' ) . $sectionIndex,
3749 'fromtitle' => $titleText,
3750 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
3751 'anchor' => $anchor,
3752 );
3753
3754 # give headline the correct <h#> tag
3755 if( $showEditLink && $sectionIndex !== false ) {
3756 if( $isTemplate ) {
3757 # Put a T flag in the section identifier, to indicate to extractSections()
3758 # that sections inside <includeonly> should be counted.
3759 $editlink = $sk->doEditSectionLink(Title::newFromText( $titleText ), "T-$sectionIndex");
3760 } else {
3761 $editlink = $sk->doEditSectionLink($this->mTitle, $sectionIndex, $headlineHint);
3762 }
3763 } else {
3764 $editlink = '';
3765 }
3766 $head[$headlineCount] = $sk->makeHeadline( $level,
3767 $matches['attrib'][$headlineCount], $anchor, $headline,
3768 $editlink, $legacyAnchor );
3769
3770 $headlineCount++;
3771 }
3772
3773 $this->setOutputType( $oldType );
3774
3775 # Never ever show TOC if no headers
3776 if( $numVisible < 1 ) {
3777 $enoughToc = false;
3778 }
3779
3780 if( $enoughToc ) {
3781 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3782 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3783 }
3784 $toc = $sk->tocList( $toc );
3785 $this->mOutput->setTOCHTML( $toc );
3786 }
3787
3788 if ( $isMain ) {
3789 $this->mOutput->setSections( $tocraw );
3790 }
3791
3792 # split up and insert constructed headlines
3793
3794 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3795 $i = 0;
3796
3797 foreach( $blocks as $block ) {
3798 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3799 # This is the [edit] link that appears for the top block of text when
3800 # section editing is enabled
3801
3802 # Disabled because it broke block formatting
3803 # For example, a bullet point in the top line
3804 # $full .= $sk->editSectionLink(0);
3805 }
3806 $full .= $block;
3807 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3808 # Top anchor now in skin
3809 $full = $full.$toc;
3810 }
3811
3812 if( !empty( $head[$i] ) ) {
3813 $full .= $head[$i];
3814 }
3815 $i++;
3816 }
3817 if( $this->mForceTocPosition ) {
3818 return str_replace( '<!--MWTOC-->', $toc, $full );
3819 } else {
3820 return $full;
3821 }
3822 }
3823
3824 /**
3825 * Merge $tree2 into $tree1 by replacing the section with index
3826 * $section in $tree1 and its descendants with the sections in $tree2.
3827 * Note that in the returned section tree, only the 'index' and
3828 * 'byteoffset' fields are guaranteed to be correct.
3829 * @param $tree1 array Section tree from ParserOutput::getSectons()
3830 * @param $tree2 array Section tree
3831 * @param $section int Section index
3832 * @param $title Title Title both section trees come from
3833 * @param $len2 int Length of the original wikitext for $tree2
3834 * @return array Merged section tree
3835 */
3836 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3837 global $wgContLang;
3838 $newTree = array();
3839 $targetLevel = false;
3840 $merged = false;
3841 $lastLevel = 1;
3842 $nextIndex = 1;
3843 $numbering = array( 0 );
3844 $titletext = $title->getPrefixedDBkey();
3845 foreach ( $tree1 as $s ) {
3846 if ( $targetLevel !== false ) {
3847 if ( $s['level'] <= $targetLevel )
3848 // We've skipped enough
3849 $targetLevel = false;
3850 else
3851 continue;
3852 }
3853 if ( $s['index'] != $section ||
3854 $s['fromtitle'] != $titletext ) {
3855 self::incrementNumbering( $numbering,
3856 $s['toclevel'], $lastLevel );
3857
3858 // Rewrite index, byteoffset and number
3859 if ( $s['fromtitle'] == $titletext ) {
3860 $s['index'] = $nextIndex++;
3861 if ( $merged )
3862 $s['byteoffset'] += $len2;
3863 }
3864 $s['number'] = implode( '.', array_map(
3865 array( $wgContLang, 'formatnum' ),
3866 $numbering ) );
3867 $lastLevel = $s['toclevel'];
3868 $newTree[] = $s;
3869 } else {
3870 // We're at $section
3871 // Insert sections from $tree2 here
3872 foreach ( $tree2 as $s2 ) {
3873 // Rewrite the fields in $s2
3874 // before inserting it
3875 $s2['toclevel'] += $s['toclevel'] - 1;
3876 $s2['level'] += $s['level'] - 1;
3877 $s2['index'] = $nextIndex++;
3878 $s2['byteoffset'] += $s['byteoffset'];
3879
3880 self::incrementNumbering( $numbering,
3881 $s2['toclevel'], $lastLevel );
3882 $s2['number'] = implode( '.', array_map(
3883 array( $wgContLang, 'formatnum' ),
3884 $numbering ) );
3885 $lastLevel = $s2['toclevel'];
3886 $newTree[] = $s2;
3887 }
3888 // Skip all descendants of $section in $tree1
3889 $targetLevel = $s['level'];
3890 $merged = true;
3891 }
3892 }
3893 return $newTree;
3894 }
3895
3896 /**
3897 * Increment a section number. Helper function for mergeSectionTrees()
3898 * @param $number array Array representing a section number
3899 * @param $level int Current TOC level (depth)
3900 * @param $lastLevel int Level of previous TOC entry
3901 */
3902 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3903 if ( $level > $lastLevel )
3904 $number[$level - 1] = 1;
3905 else if ( $level < $lastLevel ) {
3906 foreach ( $number as $key => $unused )
3907 if ( $key >= $level )
3908 unset( $number[$key] );
3909 $number[$level - 1]++;
3910 } else
3911 $number[$level - 1]++;
3912 }
3913
3914 /**
3915 * Transform wiki markup when saving a page by doing \r\n -> \n
3916 * conversion, substitting signatures, {{subst:}} templates, etc.
3917 *
3918 * @param string $text the text to transform
3919 * @param Title &$title the Title object for the current article
3920 * @param User $user the User object describing the current user
3921 * @param ParserOptions $options parsing options
3922 * @param bool $clearState whether to clear the parser state first
3923 * @return string the altered wiki markup
3924 * @public
3925 */
3926 function preSaveTransform( $text, Title $title, $user, $options, $clearState = true ) {
3927 $this->mOptions = $options;
3928 $this->setTitle( $title );
3929 $this->setOutputType( self::OT_WIKI );
3930
3931 if ( $clearState ) {
3932 $this->clearState();
3933 }
3934
3935 $pairs = array(
3936 "\r\n" => "\n",
3937 );
3938 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3939 $text = $this->pstPass2( $text, $user );
3940 $text = $this->mStripState->unstripBoth( $text );
3941 return $text;
3942 }
3943
3944 /**
3945 * Pre-save transform helper function
3946 * @private
3947 */
3948 function pstPass2( $text, $user ) {
3949 global $wgContLang, $wgLocaltimezone;
3950
3951 /* Note: This is the timestamp saved as hardcoded wikitext to
3952 * the database, we use $wgContLang here in order to give
3953 * everyone the same signature and use the default one rather
3954 * than the one selected in each user's preferences.
3955 *
3956 * (see also bug 12815)
3957 */
3958 $ts = $this->mOptions->getTimestamp();
3959 if ( isset( $wgLocaltimezone ) ) {
3960 $tz = $wgLocaltimezone;
3961 } else {
3962 $tz = date_default_timezone_get();
3963 }
3964
3965 $unixts = wfTimestamp( TS_UNIX, $ts );
3966 $oldtz = date_default_timezone_get();
3967 date_default_timezone_set( $tz );
3968 $ts = date( 'YmdHis', $unixts );
3969 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
3970
3971 /* Allow translation of timezones trough wiki. date() can return
3972 * whatever crap the system uses, localised or not, so we cannot
3973 * ship premade translations.
3974 */
3975 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
3976 $value = wfMsgForContent( $key );
3977 if ( !wfEmptyMsg( $key, $value ) ) $tzMsg = $value;
3978
3979 date_default_timezone_set( $oldtz );
3980
3981 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
3982
3983 # Variable replacement
3984 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3985 $text = $this->replaceVariables( $text );
3986
3987 # Signatures
3988 $sigText = $this->getUserSig( $user );
3989 $text = strtr( $text, array(
3990 '~~~~~' => $d,
3991 '~~~~' => "$sigText $d",
3992 '~~~' => $sigText
3993 ) );
3994
3995 # Context links: [[|name]] and [[name (context)|]]
3996 #
3997 global $wgLegalTitleChars;
3998 $tc = "[$wgLegalTitleChars]";
3999 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4000
4001 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4002 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4003 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4004 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4005
4006 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4007 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4008 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4009 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4010
4011 $t = $this->mTitle->getText();
4012 $m = array();
4013 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4014 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4015 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4016 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4017 } else {
4018 # if there's no context, don't bother duplicating the title
4019 $text = preg_replace( $p2, '[[\\1]]', $text );
4020 }
4021
4022 # Trim trailing whitespace
4023 $text = rtrim( $text );
4024
4025 return $text;
4026 }
4027
4028 /**
4029 * Fetch the user's signature text, if any, and normalize to
4030 * validated, ready-to-insert wikitext.
4031 * If you have pre-fetched the nickname or the fancySig option, you can
4032 * specify them here to save a database query.
4033 *
4034 * @param User $user
4035 * @return string
4036 */
4037 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4038 global $wgMaxSigChars;
4039
4040 $username = $user->getName();
4041
4042 // If not given, retrieve from the user object.
4043 if ( $nickname === false )
4044 $nickname = $user->getOption( 'nickname' );
4045
4046 if ( is_null( $fancySig ) )
4047 $fancySig = $user->getBoolOption( 'fancysig' );
4048
4049 $nickname = $nickname == null ? $username : $nickname;
4050
4051 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4052 $nickname = $username;
4053 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4054 } elseif( $fancySig !== false ) {
4055 # Sig. might contain markup; validate this
4056 if( $this->validateSig( $nickname ) !== false ) {
4057 # Validated; clean up (if needed) and return it
4058 return $this->cleanSig( $nickname, true );
4059 } else {
4060 # Failed to validate; fall back to the default
4061 $nickname = $username;
4062 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
4063 }
4064 }
4065
4066 // Make sure nickname doesnt get a sig in a sig
4067 $nickname = $this->cleanSigInSig( $nickname );
4068
4069 # If we're still here, make it a link to the user page
4070 $userText = wfEscapeWikiText( $username );
4071 $nickText = wfEscapeWikiText( $nickname );
4072 if ( $user->isAnon() ) {
4073 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4074 } else {
4075 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4076 }
4077 }
4078
4079 /**
4080 * Check that the user's signature contains no bad XML
4081 *
4082 * @param string $text
4083 * @return mixed An expanded string, or false if invalid.
4084 */
4085 function validateSig( $text ) {
4086 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
4087 }
4088
4089 /**
4090 * Clean up signature text
4091 *
4092 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4093 * 2) Substitute all transclusions
4094 *
4095 * @param string $text
4096 * @param $parsing Whether we're cleaning (preferences save) or parsing
4097 * @return string Signature text
4098 */
4099 function cleanSig( $text, $parsing = false ) {
4100 if ( !$parsing ) {
4101 global $wgTitle;
4102 $this->clearState();
4103 $this->setTitle( $wgTitle );
4104 $this->mOptions = new ParserOptions;
4105 $this->setOutputType = self::OT_PREPROCESS;
4106 }
4107
4108 # Option to disable this feature
4109 if ( !$this->mOptions->getCleanSignatures() ) {
4110 return $text;
4111 }
4112
4113 # FIXME: regex doesn't respect extension tags or nowiki
4114 # => Move this logic to braceSubstitution()
4115 $substWord = MagicWord::get( 'subst' );
4116 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4117 $substText = '{{' . $substWord->getSynonym( 0 );
4118
4119 $text = preg_replace( $substRegex, $substText, $text );
4120 $text = $this->cleanSigInSig( $text );
4121 $dom = $this->preprocessToDom( $text );
4122 $frame = $this->getPreprocessor()->newFrame();
4123 $text = $frame->expand( $dom );
4124
4125 if ( !$parsing ) {
4126 $text = $this->mStripState->unstripBoth( $text );
4127 }
4128
4129 return $text;
4130 }
4131
4132 /**
4133 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4134 * @param string $text
4135 * @return string Signature text with /~{3,5}/ removed
4136 */
4137 function cleanSigInSig( $text ) {
4138 $text = preg_replace( '/~{3,5}/', '', $text );
4139 return $text;
4140 }
4141
4142 /**
4143 * Set up some variables which are usually set up in parse()
4144 * so that an external function can call some class members with confidence
4145 * @public
4146 */
4147 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4148 $this->setTitle( $title );
4149 $this->mOptions = $options;
4150 $this->setOutputType( $outputType );
4151 if ( $clearState ) {
4152 $this->clearState();
4153 }
4154 }
4155
4156 /**
4157 * Wrapper for preprocess()
4158 *
4159 * @param string $text the text to preprocess
4160 * @param ParserOptions $options options
4161 * @return string
4162 * @public
4163 */
4164 function transformMsg( $text, $options ) {
4165 global $wgTitle;
4166 static $executing = false;
4167
4168 # Guard against infinite recursion
4169 if ( $executing ) {
4170 return $text;
4171 }
4172 $executing = true;
4173
4174 wfProfileIn(__METHOD__);
4175 $text = $this->preprocess( $text, $wgTitle, $options );
4176
4177 $executing = false;
4178 wfProfileOut(__METHOD__);
4179 return $text;
4180 }
4181
4182 /**
4183 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4184 * The callback should have the following form:
4185 * function myParserHook( $text, $params, &$parser ) { ... }
4186 *
4187 * Transform and return $text. Use $parser for any required context, e.g. use
4188 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4189 *
4190 * @public
4191 *
4192 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4193 * @param mixed $callback The callback function (and object) to use for the tag
4194 *
4195 * @return The old value of the mTagHooks array associated with the hook
4196 */
4197 function setHook( $tag, $callback ) {
4198 $tag = strtolower( $tag );
4199 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4200 $this->mTagHooks[$tag] = $callback;
4201 if( !in_array( $tag, $this->mStripList ) ) {
4202 $this->mStripList[] = $tag;
4203 }
4204
4205 return $oldVal;
4206 }
4207
4208 function setTransparentTagHook( $tag, $callback ) {
4209 $tag = strtolower( $tag );
4210 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4211 $this->mTransparentTagHooks[$tag] = $callback;
4212
4213 return $oldVal;
4214 }
4215
4216 /**
4217 * Remove all tag hooks
4218 */
4219 function clearTagHooks() {
4220 $this->mTagHooks = array();
4221 $this->mStripList = $this->mDefaultStripList;
4222 }
4223
4224 /**
4225 * Create a function, e.g. {{sum:1|2|3}}
4226 * The callback function should have the form:
4227 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4228 *
4229 * Or with SFH_OBJECT_ARGS:
4230 * function myParserFunction( $parser, $frame, $args ) { ... }
4231 *
4232 * The callback may either return the text result of the function, or an array with the text
4233 * in element 0, and a number of flags in the other elements. The names of the flags are
4234 * specified in the keys. Valid flags are:
4235 * found The text returned is valid, stop processing the template. This
4236 * is on by default.
4237 * nowiki Wiki markup in the return value should be escaped
4238 * isHTML The returned text is HTML, armour it against wikitext transformation
4239 *
4240 * @public
4241 *
4242 * @param string $id The magic word ID
4243 * @param mixed $callback The callback function (and object) to use
4244 * @param integer $flags a combination of the following flags:
4245 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4246 *
4247 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4248 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4249 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4250 * the arguments, and to control the way they are expanded.
4251 *
4252 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4253 * arguments, for instance:
4254 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4255 *
4256 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4257 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4258 * working if/when this is changed.
4259 *
4260 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4261 * expansion.
4262 *
4263 * Please read the documentation in includes/parser/Preprocessor.php for more information
4264 * about the methods available in PPFrame and PPNode.
4265 *
4266 * @return The old callback function for this name, if any
4267 */
4268 function setFunctionHook( $id, $callback, $flags = 0 ) {
4269 global $wgContLang;
4270
4271 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4272 $this->mFunctionHooks[$id] = array( $callback, $flags );
4273
4274 # Add to function cache
4275 $mw = MagicWord::get( $id );
4276 if( !$mw )
4277 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4278
4279 $synonyms = $mw->getSynonyms();
4280 $sensitive = intval( $mw->isCaseSensitive() );
4281
4282 foreach ( $synonyms as $syn ) {
4283 # Case
4284 if ( !$sensitive ) {
4285 $syn = $wgContLang->lc( $syn );
4286 }
4287 # Add leading hash
4288 if ( !( $flags & SFH_NO_HASH ) ) {
4289 $syn = '#' . $syn;
4290 }
4291 # Remove trailing colon
4292 if ( substr( $syn, -1, 1 ) === ':' ) {
4293 $syn = substr( $syn, 0, -1 );
4294 }
4295 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4296 }
4297 return $oldVal;
4298 }
4299
4300 /**
4301 * Get all registered function hook identifiers
4302 *
4303 * @return array
4304 */
4305 function getFunctionHooks() {
4306 return array_keys( $this->mFunctionHooks );
4307 }
4308
4309 /**
4310 * Create a tag function, e.g. <test>some stuff</test>.
4311 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4312 * Unlike parser functions, their content is not preprocessed.
4313 */
4314 function setFunctionTagHook( $tag, $callback, $flags ) {
4315 $tag = strtolower( $tag );
4316 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4317 $this->mFunctionTagHooks[$tag] : null;
4318 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4319
4320 if( !in_array( $tag, $this->mStripList ) ) {
4321 $this->mStripList[] = $tag;
4322 }
4323
4324 return $old;
4325 }
4326
4327 /**
4328 * FIXME: update documentation. makeLinkObj() is deprecated.
4329 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4330 * Placeholders created in Skin::makeLinkObj()
4331 * Returns an array of link CSS classes, indexed by PDBK.
4332 */
4333 function replaceLinkHolders( &$text, $options = 0 ) {
4334 return $this->mLinkHolders->replace( $text );
4335 }
4336
4337 /**
4338 * Replace <!--LINK--> link placeholders with plain text of links
4339 * (not HTML-formatted).
4340 * @param string $text
4341 * @return string
4342 */
4343 function replaceLinkHoldersText( $text ) {
4344 return $this->mLinkHolders->replaceText( $text );
4345 }
4346
4347 /**
4348 * Tag hook handler for 'pre'.
4349 */
4350 function renderPreTag( $text, $attribs ) {
4351 // Backwards-compatibility hack
4352 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4353
4354 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4355 return Xml::openElement( 'pre', $attribs ) .
4356 Xml::escapeTagsOnly( $content ) .
4357 '</pre>';
4358 }
4359
4360 /**
4361 * Tag hook handler for 'a'. Renders a HTML &lt;a&gt; tag, allowing most attributes, filtering href against
4362 * allowed protocols and spam blacklist.
4363 **/
4364 function renderHyperlink( $text, $params, $frame = false ) {
4365 foreach ( $params as $name => $value ) {
4366 $params[ $name ] = $this->replaceVariables( $value, $frame );
4367 }
4368
4369 $whitelist = Sanitizer::attributeWhitelist( 'a' );
4370 $params = Sanitizer::validateAttributes( $params, $whitelist );
4371
4372 $content = $this->recursiveTagParse( trim( $text ), $frame );
4373
4374 if ( isset( $params[ 'href' ] ) ) {
4375 $href = $params[ 'href' ];
4376 $this->mOutput->addExternalLink( $href );
4377 unset( $params[ 'href' ] );
4378 } else {
4379 # Non-link <a> tag
4380 return Xml::openElement( 'a', $params ) . $content . Xml::closeElement( 'a' );
4381 }
4382
4383 $sk = $this->mOptions->getSkin();
4384 $html = $sk->makeExternalLink( $href, $content, false, '', $params );
4385
4386 return $html;
4387 }
4388
4389 /**
4390 * Renders an image gallery from a text with one line per image.
4391 * text labels may be given by using |-style alternative text. E.g.
4392 * Image:one.jpg|The number "1"
4393 * Image:tree.jpg|A tree
4394 * given as text will return the HTML of a gallery with two images,
4395 * labeled 'The number "1"' and
4396 * 'A tree'.
4397 */
4398 function renderImageGallery( $text, $params ) {
4399 $ig = new ImageGallery();
4400 $ig->setContextTitle( $this->mTitle );
4401 $ig->setShowBytes( false );
4402 $ig->setShowFilename( false );
4403 $ig->setParser( $this );
4404 $ig->setHideBadImages();
4405 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4406 $ig->useSkin( $this->mOptions->getSkin() );
4407 $ig->mRevisionId = $this->mRevisionId;
4408
4409 if( isset( $params['caption'] ) ) {
4410 $caption = $params['caption'];
4411 $caption = htmlspecialchars( $caption );
4412 $caption = $this->replaceInternalLinks( $caption );
4413 $ig->setCaptionHtml( $caption );
4414 }
4415 if( isset( $params['perrow'] ) ) {
4416 $ig->setPerRow( $params['perrow'] );
4417 }
4418 if( isset( $params['widths'] ) ) {
4419 $ig->setWidths( $params['widths'] );
4420 }
4421 if( isset( $params['heights'] ) ) {
4422 $ig->setHeights( $params['heights'] );
4423 }
4424
4425 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4426
4427 $lines = StringUtils::explode( "\n", $text );
4428 foreach ( $lines as $line ) {
4429 # match lines like these:
4430 # Image:someimage.jpg|This is some image
4431 $matches = array();
4432 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4433 # Skip empty lines
4434 if ( count( $matches ) == 0 ) {
4435 continue;
4436 }
4437
4438 if ( strpos( $matches[0], '%' ) !== false )
4439 $matches[1] = urldecode( $matches[1] );
4440 $tp = Title::newFromText( $matches[1]/*, NS_FILE*/ );
4441 $nt =& $tp;
4442 if( is_null( $nt ) ) {
4443 # Bogus title. Ignore these so we don't bomb out later.
4444 continue;
4445 }
4446 if ( isset( $matches[3] ) ) {
4447 $label = $matches[3];
4448 } else {
4449 $label = '';
4450 }
4451
4452 $html = $this->recursiveTagParse( trim( $label ) );
4453
4454 $ig->add( $nt, $html );
4455
4456 # Only add real images (bug #5586)
4457 if ( $nt->getNamespace() == NS_FILE ) {
4458 $this->mOutput->addImage( $nt->getDBkey() );
4459 }
4460 }
4461 return $ig->toHTML();
4462 }
4463
4464 function getImageParams( $handler ) {
4465 if ( $handler ) {
4466 $handlerClass = get_class( $handler );
4467 } else {
4468 $handlerClass = '';
4469 }
4470 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4471 // Initialise static lists
4472 static $internalParamNames = array(
4473 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4474 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4475 'bottom', 'text-bottom' ),
4476 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4477 'upright', 'border', 'link', 'alt' ),
4478 );
4479 static $internalParamMap;
4480 if ( !$internalParamMap ) {
4481 $internalParamMap = array();
4482 foreach ( $internalParamNames as $type => $names ) {
4483 foreach ( $names as $name ) {
4484 $magicName = str_replace( '-', '_', "img_$name" );
4485 $internalParamMap[$magicName] = array( $type, $name );
4486 }
4487 }
4488 }
4489
4490 // Add handler params
4491 $paramMap = $internalParamMap;
4492 if ( $handler ) {
4493 $handlerParamMap = $handler->getParamMap();
4494 foreach ( $handlerParamMap as $magic => $paramName ) {
4495 $paramMap[$magic] = array( 'handler', $paramName );
4496 }
4497 }
4498 $this->mImageParams[$handlerClass] = $paramMap;
4499 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4500 }
4501 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4502 }
4503
4504 /**
4505 * Parse image options text and use it to make an image
4506 * @param Title $title
4507 * @param string $options
4508 * @param LinkHolderArray $holders
4509 */
4510 function makeImage( $title, $options, $holders = false ) {
4511 # Check if the options text is of the form "options|alt text"
4512 # Options are:
4513 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4514 # * left no resizing, just left align. label is used for alt= only
4515 # * right same, but right aligned
4516 # * none same, but not aligned
4517 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4518 # * center center the image
4519 # * frame Keep original image size, no magnify-button.
4520 # * framed Same as "frame"
4521 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4522 # * upright reduce width for upright images, rounded to full __0 px
4523 # * border draw a 1px border around the image
4524 # * alt Text for HTML alt attribute (defaults to empty)
4525 # * link Set the target of the image link. Can be external, interwiki, or local
4526 # vertical-align values (no % or length right now):
4527 # * baseline
4528 # * sub
4529 # * super
4530 # * top
4531 # * text-top
4532 # * middle
4533 # * bottom
4534 # * text-bottom
4535
4536 $parts = StringUtils::explode( "|", $options );
4537 $sk = $this->mOptions->getSkin();
4538
4539 # Give extensions a chance to select the file revision for us
4540 $skip = $time = $descQuery = false;
4541 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4542
4543 if ( $skip ) {
4544 return $sk->link( $title );
4545 }
4546
4547 # Get the file
4548 $imagename = $title->getDBkey();
4549 $file = wfFindFile( $title, array( 'time' => $time ) );
4550 # Get parameter map
4551 $handler = $file ? $file->getHandler() : false;
4552
4553 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4554
4555 # Process the input parameters
4556 $caption = '';
4557 $params = array( 'frame' => array(), 'handler' => array(),
4558 'horizAlign' => array(), 'vertAlign' => array() );
4559 foreach( $parts as $part ) {
4560 $part = trim( $part );
4561 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4562 $validated = false;
4563 if( isset( $paramMap[$magicName] ) ) {
4564 list( $type, $paramName ) = $paramMap[$magicName];
4565
4566 // Special case; width and height come in one variable together
4567 if( $type === 'handler' && $paramName === 'width' ) {
4568 $m = array();
4569 # (bug 13500) In both cases (width/height and width only),
4570 # permit trailing "px" for backward compatibility.
4571 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4572 $width = intval( $m[1] );
4573 $height = intval( $m[2] );
4574 if ( $handler->validateParam( 'width', $width ) ) {
4575 $params[$type]['width'] = $width;
4576 $validated = true;
4577 }
4578 if ( $handler->validateParam( 'height', $height ) ) {
4579 $params[$type]['height'] = $height;
4580 $validated = true;
4581 }
4582 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4583 $width = intval( $value );
4584 if ( $handler->validateParam( 'width', $width ) ) {
4585 $params[$type]['width'] = $width;
4586 $validated = true;
4587 }
4588 } // else no validation -- bug 13436
4589 } else {
4590 if ( $type === 'handler' ) {
4591 # Validate handler parameter
4592 $validated = $handler->validateParam( $paramName, $value );
4593 } else {
4594 # Validate internal parameters
4595 switch( $paramName ) {
4596 case 'manualthumb':
4597 case 'alt':
4598 // @todo Fixme: possibly check validity here for
4599 // manualthumb? downstream behavior seems odd with
4600 // missing manual thumbs.
4601 $validated = true;
4602 $value = $this->stripAltText( $value, $holders );
4603 break;
4604 case 'link':
4605 $chars = self::EXT_LINK_URL_CLASS;
4606 $prots = $this->mUrlProtocols;
4607 if ( $value === '' ) {
4608 $paramName = 'no-link';
4609 $value = true;
4610 $validated = true;
4611 } elseif ( preg_match( "/^$prots/", $value ) ) {
4612 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4613 $paramName = 'link-url';
4614 $this->mOutput->addExternalLink( $value );
4615 $validated = true;
4616 }
4617 } else {
4618 $linkTitle = Title::newFromText( $value );
4619 if ( $linkTitle ) {
4620 $paramName = 'link-title';
4621 $value = $linkTitle;
4622 $this->mOutput->addLink( $linkTitle );
4623 $validated = true;
4624 }
4625 }
4626 break;
4627 default:
4628 // Most other things appear to be empty or numeric...
4629 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4630 }
4631 }
4632
4633 if ( $validated ) {
4634 $params[$type][$paramName] = $value;
4635 }
4636 }
4637 }
4638 if ( !$validated ) {
4639 $caption = $part;
4640 }
4641 }
4642
4643 # Process alignment parameters
4644 if ( $params['horizAlign'] ) {
4645 $params['frame']['align'] = key( $params['horizAlign'] );
4646 }
4647 if ( $params['vertAlign'] ) {
4648 $params['frame']['valign'] = key( $params['vertAlign'] );
4649 }
4650
4651 $params['frame']['caption'] = $caption;
4652
4653 # Will the image be presented in a frame, with the caption below?
4654 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4655 isset( $params['frame']['framed'] ) ||
4656 isset( $params['frame']['thumbnail'] ) ||
4657 isset( $params['frame']['manualthumb'] );
4658
4659 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4660 # came to also set the caption, ordinary text after the image -- which
4661 # makes no sense, because that just repeats the text multiple times in
4662 # screen readers. It *also* came to set the title attribute.
4663 #
4664 # Now that we have an alt attribute, we should not set the alt text to
4665 # equal the caption: that's worse than useless, it just repeats the
4666 # text. This is the framed/thumbnail case. If there's no caption, we
4667 # use the unnamed parameter for alt text as well, just for the time be-
4668 # ing, if the unnamed param is set and the alt param is not.
4669 #
4670 # For the future, we need to figure out if we want to tweak this more,
4671 # e.g., introducing a title= parameter for the title; ignoring the un-
4672 # named parameter entirely for images without a caption; adding an ex-
4673 # plicit caption= parameter and preserving the old magic unnamed para-
4674 # meter for BC; ...
4675 if ( $imageIsFramed ) { # Framed image
4676 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4677 # No caption or alt text, add the filename as the alt text so
4678 # that screen readers at least get some description of the image
4679 $params['frame']['alt'] = $title->getText();
4680 }
4681 # Do not set $params['frame']['title'] because tooltips don't make sense
4682 # for framed images
4683 } else { # Inline image
4684 if ( !isset( $params['frame']['alt'] ) ) {
4685 # No alt text, use the "caption" for the alt text
4686 if ( $caption !== '') {
4687 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4688 } else {
4689 # No caption, fall back to using the filename for the
4690 # alt text
4691 $params['frame']['alt'] = $title->getText();
4692 }
4693 }
4694 # Use the "caption" for the tooltip text
4695 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4696 }
4697
4698 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4699
4700 # Linker does the rest
4701 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4702
4703 # Give the handler a chance to modify the parser object
4704 if ( $handler ) {
4705 $handler->parserTransformHook( $this, $file );
4706 }
4707
4708 return $ret;
4709 }
4710
4711 protected function stripAltText( $caption, $holders ) {
4712 # Strip bad stuff out of the title (tooltip). We can't just use
4713 # replaceLinkHoldersText() here, because if this function is called
4714 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4715 if ( $holders ) {
4716 $tooltip = $holders->replaceText( $caption );
4717 } else {
4718 $tooltip = $this->replaceLinkHoldersText( $caption );
4719 }
4720
4721 # make sure there are no placeholders in thumbnail attributes
4722 # that are later expanded to html- so expand them now and
4723 # remove the tags
4724 $tooltip = $this->mStripState->unstripBoth( $tooltip );
4725 $tooltip = Sanitizer::stripAllTags( $tooltip );
4726
4727 return $tooltip;
4728 }
4729
4730 /**
4731 * Set a flag in the output object indicating that the content is dynamic and
4732 * shouldn't be cached.
4733 */
4734 function disableCache() {
4735 wfDebug( "Parser output marked as uncacheable.\n" );
4736 $this->mOutput->mCacheTime = -1;
4737 }
4738
4739 /**#@+
4740 * Callback from the Sanitizer for expanding items found in HTML attribute
4741 * values, so they can be safely tested and escaped.
4742 * @param string $text
4743 * @param PPFrame $frame
4744 * @return string
4745 * @private
4746 */
4747 function attributeStripCallback( &$text, $frame = false ) {
4748 $text = $this->replaceVariables( $text, $frame );
4749 $text = $this->mStripState->unstripBoth( $text );
4750 return $text;
4751 }
4752
4753 /**#@-*/
4754
4755 /**#@+
4756 * Accessor/mutator
4757 */
4758 function Title( $x = null ) { return wfSetVar( $this->mTitle, $x ); }
4759 function Options( $x = null ) { return wfSetVar( $this->mOptions, $x ); }
4760 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType, $x ); }
4761 /**#@-*/
4762
4763 /**#@+
4764 * Accessor
4765 */
4766 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4767 /**#@-*/
4768
4769
4770 /**
4771 * Break wikitext input into sections, and either pull or replace
4772 * some particular section's text.
4773 *
4774 * External callers should use the getSection and replaceSection methods.
4775 *
4776 * @param string $text Page wikitext
4777 * @param string $section A section identifier string of the form:
4778 * <flag1> - <flag2> - ... - <section number>
4779 *
4780 * Currently the only recognised flag is "T", which means the target section number
4781 * was derived during a template inclusion parse, in other words this is a template
4782 * section edit link. If no flags are given, it was an ordinary section edit link.
4783 * This flag is required to avoid a section numbering mismatch when a section is
4784 * enclosed by <includeonly> (bug 6563).
4785 *
4786 * The section number 0 pulls the text before the first heading; other numbers will
4787 * pull the given section along with its lower-level subsections. If the section is
4788 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4789 *
4790 * @param string $mode One of "get" or "replace"
4791 * @param string $newText Replacement text for section data.
4792 * @return string for "get", the extracted section text.
4793 * for "replace", the whole page with the section replaced.
4794 */
4795 private function extractSections( $text, $section, $mode, $newText='' ) {
4796 global $wgTitle;
4797 $this->clearState();
4798 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4799 $this->mOptions = new ParserOptions;
4800 $this->setOutputType( self::OT_WIKI );
4801 $outText = '';
4802 $frame = $this->getPreprocessor()->newFrame();
4803
4804 // Process section extraction flags
4805 $flags = 0;
4806 $sectionParts = explode( '-', $section );
4807 $sectionIndex = array_pop( $sectionParts );
4808 foreach ( $sectionParts as $part ) {
4809 if ( $part === 'T' ) {
4810 $flags |= self::PTD_FOR_INCLUSION;
4811 }
4812 }
4813 // Preprocess the text
4814 $root = $this->preprocessToDom( $text, $flags );
4815
4816 // <h> nodes indicate section breaks
4817 // They can only occur at the top level, so we can find them by iterating the root's children
4818 $node = $root->getFirstChild();
4819
4820 // Find the target section
4821 if ( $sectionIndex == 0 ) {
4822 // Section zero doesn't nest, level=big
4823 $targetLevel = 1000;
4824 } else {
4825 while ( $node ) {
4826 if ( $node->getName() === 'h' ) {
4827 $bits = $node->splitHeading();
4828 if ( $bits['i'] == $sectionIndex ) {
4829 $targetLevel = $bits['level'];
4830 break;
4831 }
4832 }
4833 if ( $mode === 'replace' ) {
4834 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4835 }
4836 $node = $node->getNextSibling();
4837 }
4838 }
4839
4840 if ( !$node ) {
4841 // Not found
4842 if ( $mode === 'get' ) {
4843 return $newText;
4844 } else {
4845 return $text;
4846 }
4847 }
4848
4849 // Find the end of the section, including nested sections
4850 do {
4851 if ( $node->getName() === 'h' ) {
4852 $bits = $node->splitHeading();
4853 $curLevel = $bits['level'];
4854 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4855 break;
4856 }
4857 }
4858 if ( $mode === 'get' ) {
4859 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4860 }
4861 $node = $node->getNextSibling();
4862 } while ( $node );
4863
4864 // Write out the remainder (in replace mode only)
4865 if ( $mode === 'replace' ) {
4866 // Output the replacement text
4867 // Add two newlines on -- trailing whitespace in $newText is conventionally
4868 // stripped by the editor, so we need both newlines to restore the paragraph gap
4869 // Only add trailing whitespace if there is newText
4870 if($newText != "") {
4871 $outText .= $newText . "\n\n";
4872 }
4873
4874 while ( $node ) {
4875 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4876 $node = $node->getNextSibling();
4877 }
4878 }
4879
4880 if ( is_string( $outText ) ) {
4881 // Re-insert stripped tags
4882 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4883 }
4884
4885 return $outText;
4886 }
4887
4888 /**
4889 * This function returns the text of a section, specified by a number ($section).
4890 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4891 * the first section before any such heading (section 0).
4892 *
4893 * If a section contains subsections, these are also returned.
4894 *
4895 * @param string $text text to look in
4896 * @param string $section section identifier
4897 * @param string $deftext default to return if section is not found
4898 * @return string text of the requested section
4899 */
4900 public function getSection( $text, $section, $deftext='' ) {
4901 return $this->extractSections( $text, $section, "get", $deftext );
4902 }
4903
4904 public function replaceSection( $oldtext, $section, $text ) {
4905 return $this->extractSections( $oldtext, $section, "replace", $text );
4906 }
4907
4908 /**
4909 * Get the timestamp associated with the current revision, adjusted for
4910 * the default server-local timestamp
4911 */
4912 function getRevisionTimestamp() {
4913 if ( is_null( $this->mRevisionTimestamp ) ) {
4914 wfProfileIn( __METHOD__ );
4915 global $wgContLang;
4916 $dbr = wfGetDB( DB_SLAVE );
4917 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4918 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4919
4920 // Normalize timestamp to internal MW format for timezone processing.
4921 // This has the added side-effect of replacing a null value with
4922 // the current time, which gives us more sensible behavior for
4923 // previews.
4924 $timestamp = wfTimestamp( TS_MW, $timestamp );
4925
4926 // The cryptic '' timezone parameter tells to use the site-default
4927 // timezone offset instead of the user settings.
4928 //
4929 // Since this value will be saved into the parser cache, served
4930 // to other users, and potentially even used inside links and such,
4931 // it needs to be consistent for all visitors.
4932 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4933
4934 wfProfileOut( __METHOD__ );
4935 }
4936 return $this->mRevisionTimestamp;
4937 }
4938
4939 /**
4940 * Get the name of the user that edited the last revision
4941 */
4942 function getRevisionUser() {
4943 // if this template is subst: the revision id will be blank,
4944 // so just use the current user's name
4945 if( $this->mRevisionId ) {
4946 $revision = Revision::newFromId( $this->mRevisionId );
4947 $revuser = $revision->getUserText();
4948 } else {
4949 global $wgUser;
4950 $revuser = $wgUser->getName();
4951 }
4952 return $revuser;
4953 }
4954
4955 /**
4956 * Mutator for $mDefaultSort
4957 *
4958 * @param $sort New value
4959 */
4960 public function setDefaultSort( $sort ) {
4961 $this->mDefaultSort = $sort;
4962 }
4963
4964 /**
4965 * Accessor for $mDefaultSort
4966 * Will use the title/prefixed title if none is set
4967 *
4968 * @return string
4969 */
4970 public function getDefaultSort() {
4971 global $wgCategoryPrefixedDefaultSortkey;
4972 if( $this->mDefaultSort !== false ) {
4973 return $this->mDefaultSort;
4974 } elseif ($this->mTitle->getNamespace() == NS_CATEGORY ||
4975 !$wgCategoryPrefixedDefaultSortkey) {
4976 return $this->mTitle->getText();
4977 } else {
4978 return $this->mTitle->getPrefixedText();
4979 }
4980 }
4981
4982 /**
4983 * Accessor for $mDefaultSort
4984 * Unlike getDefaultSort(), will return false if none is set
4985 *
4986 * @return string or false
4987 */
4988 public function getCustomDefaultSort() {
4989 return $this->mDefaultSort;
4990 }
4991
4992 /**
4993 * Try to guess the section anchor name based on a wikitext fragment
4994 * presumably extracted from a heading, for example "Header" from
4995 * "== Header ==".
4996 */
4997 public function guessSectionNameFromWikiText( $text ) {
4998 # Strip out wikitext links(they break the anchor)
4999 $text = $this->stripSectionName( $text );
5000 $headline = Sanitizer::decodeCharReferences( $text );
5001 # strip out HTML
5002 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
5003 $headline = trim( $headline );
5004 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5005 $replacearray = array(
5006 '%3A' => ':',
5007 '%' => '.'
5008 );
5009 return str_replace(
5010 array_keys( $replacearray ),
5011 array_values( $replacearray ),
5012 $sectionanchor );
5013 }
5014
5015 /**
5016 * Strips a text string of wikitext for use in a section anchor
5017 *
5018 * Accepts a text string and then removes all wikitext from the
5019 * string and leaves only the resultant text (i.e. the result of
5020 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5021 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5022 * to create valid section anchors by mimicing the output of the
5023 * parser when headings are parsed.
5024 *
5025 * @param $text string Text string to be stripped of wikitext
5026 * for use in a Section anchor
5027 * @return Filtered text string
5028 */
5029 public function stripSectionName( $text ) {
5030 # Strip internal link markup
5031 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5032 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5033
5034 # Strip external link markup (FIXME: Not Tolerant to blank link text
5035 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5036 # on how many empty links there are on the page - need to figure that out.
5037 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5038
5039 # Parse wikitext quotes (italics & bold)
5040 $text = $this->doQuotes($text);
5041
5042 # Strip HTML tags
5043 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5044 return $text;
5045 }
5046
5047 function srvus( $text ) {
5048 return $this->testSrvus( $text, $this->mOutputType );
5049 }
5050
5051 /**
5052 * strip/replaceVariables/unstrip for preprocessor regression testing
5053 */
5054 function testSrvus( $text, $title, $options, $outputType = self::OT_HTML ) {
5055 $this->clearState();
5056 if ( ! ( $title instanceof Title ) ) {
5057 $title = Title::newFromText( $title );
5058 }
5059 $this->mTitle = $title;
5060 $this->mOptions = $options;
5061 $this->setOutputType( $outputType );
5062 $text = $this->replaceVariables( $text );
5063 $text = $this->mStripState->unstripBoth( $text );
5064 $text = Sanitizer::removeHTMLtags( $text );
5065 return $text;
5066 }
5067
5068 function testPst( $text, $title, $options ) {
5069 global $wgUser;
5070 if ( ! ( $title instanceof Title ) ) {
5071 $title = Title::newFromText( $title );
5072 }
5073 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5074 }
5075
5076 function testPreprocess( $text, $title, $options ) {
5077 if ( ! ( $title instanceof Title ) ) {
5078 $title = Title::newFromText( $title );
5079 }
5080 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5081 }
5082
5083 function markerSkipCallback( $s, $callback ) {
5084 $i = 0;
5085 $out = '';
5086 while ( $i < strlen( $s ) ) {
5087 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5088 if ( $markerStart === false ) {
5089 $out .= call_user_func( $callback, substr( $s, $i ) );
5090 break;
5091 } else {
5092 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5093 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5094 if ( $markerEnd === false ) {
5095 $out .= substr( $s, $markerStart );
5096 break;
5097 } else {
5098 $markerEnd += strlen( self::MARKER_SUFFIX );
5099 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5100 $i = $markerEnd;
5101 }
5102 }
5103 }
5104 return $out;
5105 }
5106
5107 function serialiseHalfParsedText( $text ) {
5108 $data = array();
5109 $data['text'] = $text;
5110
5111 // First, find all strip markers, and store their
5112 // data in an array.
5113 $stripState = new StripState;
5114 $pos = 0;
5115 while( ( $start_pos = strpos( $text, $this->mUniqPrefix, $pos ) ) && ( $end_pos = strpos( $text, self::MARKER_SUFFIX, $pos ) ) ) {
5116 $end_pos += strlen( self::MARKER_SUFFIX );
5117 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5118
5119 if ( !empty( $this->mStripState->general->data[$marker] ) ) {
5120 $replaceArray = $stripState->general;
5121 $stripText = $this->mStripState->general->data[$marker];
5122 } elseif ( !empty( $this->mStripState->nowiki->data[$marker] ) ) {
5123 $replaceArray = $stripState->nowiki;
5124 $stripText = $this->mStripState->nowiki->data[$marker];
5125 } else {
5126 throw new MWException( "Hanging strip marker: '$marker'." );
5127 }
5128
5129 $replaceArray->setPair( $marker, $stripText );
5130 $pos = $end_pos;
5131 }
5132 $data['stripstate'] = $stripState;
5133
5134 // Now, find all of our links, and store THEIR
5135 // data in an array! :)
5136 $links = array( 'internal' => array(), 'interwiki' => array() );
5137 $pos = 0;
5138
5139 // Internal links
5140 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5141 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos + strlen( '<!--LINK ' ) ), 2 );
5142
5143 $ns = trim($ns);
5144 if (empty( $links['internal'][$ns] )) {
5145 $links['internal'][$ns] = array();
5146 }
5147
5148 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5149 $links['internal'][$ns][] = $this->mLinkHolders->internals[$ns][$key];
5150 $pos = $start_pos + strlen( "<!--LINK $ns:$key-->" );
5151 }
5152
5153 $pos = 0;
5154
5155 // Interwiki links
5156 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5157 $data = substr( $text, $start_pos );
5158 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5159 $links['interwiki'][] = $this->mLinkHolders->interwiki[$key];
5160 $pos = $start_pos + strlen( "<!--IWLINK $key-->" );
5161 }
5162
5163 $data['linkholder'] = $links;
5164
5165 return $data;
5166 }
5167
5168 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5169 if (!$intPrefix)
5170 $intPrefix = $this->getRandomString();
5171
5172 // First, extract the strip state.
5173 $stripState = $data['stripstate'];
5174 $this->mStripState->general->merge( $stripState->general );
5175 $this->mStripState->nowiki->merge( $stripState->nowiki );
5176
5177 // Now, extract the text, and renumber links
5178 $text = $data['text'];
5179 $links = $data['linkholder'];
5180
5181 // Internal...
5182 foreach( $links['internal'] as $ns => $nsLinks ) {
5183 foreach( $nsLinks as $key => $entry ) {
5184 $newKey = $intPrefix . '-' . $key;
5185 $this->mLinkHolders->internals[$ns][$newKey] = $entry;
5186
5187 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5188 }
5189 }
5190
5191 // Interwiki...
5192 foreach( $links['interwiki'] as $key => $entry ) {
5193 $newKey = "$intPrefix-$key";
5194 $this->mLinkHolders->interwikis[$newKey] = $entry;
5195
5196 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5197 }
5198
5199 // Should be good to go.
5200 return $text;
5201 }
5202 }
5203
5204 /**
5205 * @todo document, briefly.
5206 * @ingroup Parser
5207 */
5208 class StripState {
5209 var $general, $nowiki;
5210
5211 function __construct() {
5212 $this->general = new ReplacementArray;
5213 $this->nowiki = new ReplacementArray;
5214 }
5215
5216 function unstripGeneral( $text ) {
5217 wfProfileIn( __METHOD__ );
5218 do {
5219 $oldText = $text;
5220 $text = $this->general->replace( $text );
5221 } while ( $text !== $oldText );
5222 wfProfileOut( __METHOD__ );
5223 return $text;
5224 }
5225
5226 function unstripNoWiki( $text ) {
5227 wfProfileIn( __METHOD__ );
5228 do {
5229 $oldText = $text;
5230 $text = $this->nowiki->replace( $text );
5231 } while ( $text !== $oldText );
5232 wfProfileOut( __METHOD__ );
5233 return $text;
5234 }
5235
5236 function unstripBoth( $text ) {
5237 wfProfileIn( __METHOD__ );
5238 do {
5239 $oldText = $text;
5240 $text = $this->general->replace( $text );
5241 $text = $this->nowiki->replace( $text );
5242 } while ( $text !== $oldText );
5243 wfProfileOut( __METHOD__ );
5244 return $text;
5245 }
5246 }
5247
5248 /**
5249 * @todo document, briefly.
5250 * @ingroup Parser
5251 */
5252 class OnlyIncludeReplacer {
5253 var $output = '';
5254
5255 function replace( $matches ) {
5256 if ( substr( $matches[1], -1 ) === "\n" ) {
5257 $this->output .= substr( $matches[1], 0, -1 );
5258 } else {
5259 $this->output .= $matches[1];
5260 }
5261 }
5262 }