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