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