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