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