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