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