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