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