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