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