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