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