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