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