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