* (bug 15196) Free external links should be numbered in a localised manner
[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 $langObj = $this->getFunctionLang();
1381 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1382 $linktype = 'autonumber';
1383 } else {
1384 # Otherwise just use the URL
1385 $text = htmlspecialchars( $url );
1386 $linktype = 'free';
1387 }
1388 } else {
1389 # Have link text, e.g. [http://domain.tld/some.link text]s
1390 # Check for trail
1391 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1392 }
1393
1394 $text = $wgContLang->markNoConversion($text);
1395
1396 $url = Sanitizer::cleanUrl( $url );
1397
1398 if ( $this->mOptions->mExternalLinkTarget ) {
1399 $attribs = array( 'target' => $this->mOptions->mExternalLinkTarget );
1400 } else {
1401 $attribs = array();
1402 }
1403
1404 # Use the encoded URL
1405 # This means that users can paste URLs directly into the text
1406 # Funny characters like &ouml; aren't valid in URLs anyway
1407 # This was changed in August 2004
1408 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->getExternalLinkAttribs() )
1409 . $dtrail . $trail;
1410
1411 # Register link in the output object.
1412 # Replace unnecessary URL escape codes with the referenced character
1413 # This prevents spammers from hiding links from the filters
1414 $pasteurized = self::replaceUnusualEscapes( $url );
1415 $this->mOutput->addExternalLink( $pasteurized );
1416 }
1417
1418 wfProfileOut( __METHOD__ );
1419 return $s;
1420 }
1421
1422 function getExternalLinkAttribs() {
1423 $attribs = array();
1424 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1425 $ns = $this->mTitle->getNamespace();
1426 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1427 $attribs['rel'] = 'nofollow';
1428 }
1429 if ( $this->mOptions->getExternalLinkTarget() ) {
1430 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1431 }
1432 return $attribs;
1433 }
1434
1435
1436 /**
1437 * Replace unusual URL escape codes with their equivalent characters
1438 * @param string
1439 * @return string
1440 * @static
1441 * @todo This can merge genuinely required bits in the path or query string,
1442 * breaking legit URLs. A proper fix would treat the various parts of
1443 * the URL differently; as a workaround, just use the output for
1444 * statistical records, not for actual linking/output.
1445 */
1446 static function replaceUnusualEscapes( $url ) {
1447 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1448 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1449 }
1450
1451 /**
1452 * Callback function used in replaceUnusualEscapes().
1453 * Replaces unusual URL escape codes with their equivalent character
1454 * @static
1455 * @private
1456 */
1457 private static function replaceUnusualEscapesCallback( $matches ) {
1458 $char = urldecode( $matches[0] );
1459 $ord = ord( $char );
1460 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1461 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1462 // No, shouldn't be escaped
1463 return $char;
1464 } else {
1465 // Yes, leave it escaped
1466 return $matches[0];
1467 }
1468 }
1469
1470 /**
1471 * make an image if it's allowed, either through the global
1472 * option, through the exception, or through the on-wiki whitelist
1473 * @private
1474 */
1475 function maybeMakeExternalImage( $url ) {
1476 $sk = $this->mOptions->getSkin();
1477 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1478 $imagesexception = !empty($imagesfrom);
1479 $text = false;
1480 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1481 if( $imagesexception && is_array( $imagesfrom ) ) {
1482 $imagematch = false;
1483 foreach( $imagesfrom as $match ) {
1484 if( strpos( $url, $match ) === 0 ) {
1485 $imagematch = true;
1486 break;
1487 }
1488 }
1489 } elseif( $imagesexception ) {
1490 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1491 } else {
1492 $imagematch = false;
1493 }
1494 if ( $this->mOptions->getAllowExternalImages()
1495 || ( $imagesexception && $imagematch ) ) {
1496 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1497 # Image found
1498 $text = $sk->makeExternalImage( $url );
1499 }
1500 }
1501 if( !$text && $this->mOptions->getEnableImageWhitelist()
1502 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1503 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1504 foreach( $whitelist as $entry ) {
1505 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1506 if( strpos( $entry, '#' ) === 0 || $entry === '' )
1507 continue;
1508 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1509 # Image matches a whitelist entry
1510 $text = $sk->makeExternalImage( $url );
1511 break;
1512 }
1513 }
1514 }
1515 return $text;
1516 }
1517
1518 /**
1519 * Process [[ ]] wikilinks
1520 * @return processed text
1521 *
1522 * @private
1523 */
1524 function replaceInternalLinks( $s ) {
1525 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1526 return $s;
1527 }
1528
1529 /**
1530 * Process [[ ]] wikilinks (RIL)
1531 * @return LinkHolderArray
1532 *
1533 * @private
1534 */
1535 function replaceInternalLinks2( &$s ) {
1536 global $wgContLang;
1537
1538 wfProfileIn( __METHOD__ );
1539
1540 wfProfileIn( __METHOD__.'-setup' );
1541 static $tc = FALSE, $e1, $e1_img;
1542 # the % is needed to support urlencoded titles as well
1543 if ( !$tc ) {
1544 $tc = Title::legalChars() . '#%';
1545 # Match a link having the form [[namespace:link|alternate]]trail
1546 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1547 # Match cases where there is no "]]", which might still be images
1548 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1549 }
1550
1551 $sk = $this->mOptions->getSkin();
1552 $holders = new LinkHolderArray( $this );
1553
1554 #split the entire text string on occurences of [[
1555 $a = StringUtils::explode( '[[', ' ' . $s );
1556 #get the first element (all text up to first [[), and remove the space we added
1557 $s = $a->current();
1558 $a->next();
1559 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1560 $s = substr( $s, 1 );
1561
1562 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1563 $e2 = null;
1564 if ( $useLinkPrefixExtension ) {
1565 # Match the end of a line for a word that's not followed by whitespace,
1566 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1567 $e2 = wfMsgForContent( 'linkprefix' );
1568 }
1569
1570 if( is_null( $this->mTitle ) ) {
1571 wfProfileOut( __METHOD__.'-setup' );
1572 wfProfileOut( __METHOD__ );
1573 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1574 }
1575 $nottalk = !$this->mTitle->isTalkPage();
1576
1577 if ( $useLinkPrefixExtension ) {
1578 $m = array();
1579 if ( preg_match( $e2, $s, $m ) ) {
1580 $first_prefix = $m[2];
1581 } else {
1582 $first_prefix = false;
1583 }
1584 } else {
1585 $prefix = '';
1586 }
1587
1588 if($wgContLang->hasVariants()) {
1589 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1590 } else {
1591 $selflink = array($this->mTitle->getPrefixedText());
1592 }
1593 $useSubpages = $this->areSubpagesAllowed();
1594 wfProfileOut( __METHOD__.'-setup' );
1595
1596 # Loop for each link
1597 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1598 # Check for excessive memory usage
1599 if ( $holders->isBig() ) {
1600 # Too big
1601 # Do the existence check, replace the link holders and clear the array
1602 $holders->replace( $s );
1603 $holders->clear();
1604 }
1605
1606 if ( $useLinkPrefixExtension ) {
1607 wfProfileIn( __METHOD__.'-prefixhandling' );
1608 if ( preg_match( $e2, $s, $m ) ) {
1609 $prefix = $m[2];
1610 $s = $m[1];
1611 } else {
1612 $prefix='';
1613 }
1614 # first link
1615 if($first_prefix) {
1616 $prefix = $first_prefix;
1617 $first_prefix = false;
1618 }
1619 wfProfileOut( __METHOD__.'-prefixhandling' );
1620 }
1621
1622 $might_be_img = false;
1623
1624 wfProfileIn( __METHOD__."-e1" );
1625 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1626 $text = $m[2];
1627 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1628 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1629 # the real problem is with the $e1 regex
1630 # See bug 1300.
1631 #
1632 # Still some problems for cases where the ] is meant to be outside punctuation,
1633 # and no image is in sight. See bug 2095.
1634 #
1635 if( $text !== '' &&
1636 substr( $m[3], 0, 1 ) === ']' &&
1637 strpos($text, '[') !== false
1638 )
1639 {
1640 $text .= ']'; # so that replaceExternalLinks($text) works later
1641 $m[3] = substr( $m[3], 1 );
1642 }
1643 # fix up urlencoded title texts
1644 if( strpos( $m[1], '%' ) !== false ) {
1645 # Should anchors '#' also be rejected?
1646 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1647 }
1648 $trail = $m[3];
1649 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1650 $might_be_img = true;
1651 $text = $m[2];
1652 if ( strpos( $m[1], '%' ) !== false ) {
1653 $m[1] = urldecode($m[1]);
1654 }
1655 $trail = "";
1656 } else { # Invalid form; output directly
1657 $s .= $prefix . '[[' . $line ;
1658 wfProfileOut( __METHOD__."-e1" );
1659 continue;
1660 }
1661 wfProfileOut( __METHOD__."-e1" );
1662 wfProfileIn( __METHOD__."-misc" );
1663
1664 # Don't allow internal links to pages containing
1665 # PROTO: where PROTO is a valid URL protocol; these
1666 # should be external links.
1667 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1668 $s .= $prefix . '[[' . $line ;
1669 wfProfileOut( __METHOD__."-misc" );
1670 continue;
1671 }
1672
1673 # Make subpage if necessary
1674 if( $useSubpages ) {
1675 $link = $this->maybeDoSubpageLink( $m[1], $text );
1676 } else {
1677 $link = $m[1];
1678 }
1679
1680 $noforce = (substr($m[1], 0, 1) !== ':');
1681 if (!$noforce) {
1682 # Strip off leading ':'
1683 $link = substr($link, 1);
1684 }
1685
1686 wfProfileOut( __METHOD__."-misc" );
1687 wfProfileIn( __METHOD__."-title" );
1688 $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
1689 if( !$nt ) {
1690 $s .= $prefix . '[[' . $line;
1691 wfProfileOut( __METHOD__."-title" );
1692 continue;
1693 }
1694
1695 $ns = $nt->getNamespace();
1696 $iw = $nt->getInterWiki();
1697 wfProfileOut( __METHOD__."-title" );
1698
1699 if ($might_be_img) { # if this is actually an invalid link
1700 wfProfileIn( __METHOD__."-might_be_img" );
1701 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1702 $found = false;
1703 while ( true ) {
1704 #look at the next 'line' to see if we can close it there
1705 $a->next();
1706 $next_line = $a->current();
1707 if ( $next_line === false || $next_line === null ) {
1708 break;
1709 }
1710 $m = explode( ']]', $next_line, 3 );
1711 if ( count( $m ) == 3 ) {
1712 # the first ]] closes the inner link, the second the image
1713 $found = true;
1714 $text .= "[[{$m[0]}]]{$m[1]}";
1715 $trail = $m[2];
1716 break;
1717 } elseif ( count( $m ) == 2 ) {
1718 #if there's exactly one ]] that's fine, we'll keep looking
1719 $text .= "[[{$m[0]}]]{$m[1]}";
1720 } else {
1721 #if $next_line is invalid too, we need look no further
1722 $text .= '[[' . $next_line;
1723 break;
1724 }
1725 }
1726 if ( !$found ) {
1727 # we couldn't find the end of this imageLink, so output it raw
1728 #but don't ignore what might be perfectly normal links in the text we've examined
1729 $holders->merge( $this->replaceInternalLinks2( $text ) );
1730 $s .= "{$prefix}[[$link|$text";
1731 # note: no $trail, because without an end, there *is* no trail
1732 wfProfileOut( __METHOD__."-might_be_img" );
1733 continue;
1734 }
1735 } else { #it's not an image, so output it raw
1736 $s .= "{$prefix}[[$link|$text";
1737 # note: no $trail, because without an end, there *is* no trail
1738 wfProfileOut( __METHOD__."-might_be_img" );
1739 continue;
1740 }
1741 wfProfileOut( __METHOD__."-might_be_img" );
1742 }
1743
1744 $wasblank = ( '' == $text );
1745 if( $wasblank ) $text = $link;
1746
1747 # Link not escaped by : , create the various objects
1748 if( $noforce ) {
1749
1750 # Interwikis
1751 wfProfileIn( __METHOD__."-interwiki" );
1752 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1753 $this->mOutput->addLanguageLink( $nt->getFullText() );
1754 $s = rtrim($s . $prefix);
1755 $s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
1756 wfProfileOut( __METHOD__."-interwiki" );
1757 continue;
1758 }
1759 wfProfileOut( __METHOD__."-interwiki" );
1760
1761 if ( $ns == NS_IMAGE ) {
1762 wfProfileIn( __METHOD__."-image" );
1763 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1764 # recursively parse links inside the image caption
1765 # actually, this will parse them in any other parameters, too,
1766 # but it might be hard to fix that, and it doesn't matter ATM
1767 $text = $this->replaceExternalLinks($text);
1768 $holders->merge( $this->replaceInternalLinks2( $text ) );
1769
1770 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1771 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1772 }
1773 $this->mOutput->addImage( $nt->getDBkey() );
1774 wfProfileOut( __METHOD__."-image" );
1775 continue;
1776
1777 }
1778
1779 if ( $ns == NS_CATEGORY ) {
1780 wfProfileIn( __METHOD__."-category" );
1781 $s = rtrim($s . "\n"); # bug 87
1782
1783 if ( $wasblank ) {
1784 $sortkey = $this->getDefaultSort();
1785 } else {
1786 $sortkey = $text;
1787 }
1788 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1789 $sortkey = str_replace( "\n", '', $sortkey );
1790 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1791 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1792
1793 /**
1794 * Strip the whitespace Category links produce, see bug 87
1795 * @todo We might want to use trim($tmp, "\n") here.
1796 */
1797 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1798
1799 wfProfileOut( __METHOD__."-category" );
1800 continue;
1801 }
1802 }
1803
1804 # Self-link checking
1805 if( $nt->getFragment() === '' && $nt->getNamespace() != NS_SPECIAL ) {
1806 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1807 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1808 continue;
1809 }
1810 }
1811
1812 # Special and Media are pseudo-namespaces; no pages actually exist in them
1813 if( $ns == NS_MEDIA ) {
1814 # Give extensions a chance to select the file revision for us
1815 $skip = $time = false;
1816 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1817 if ( $skip ) {
1818 $link = $sk->link( $nt );
1819 } else {
1820 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1821 }
1822 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1823 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1824 $this->mOutput->addImage( $nt->getDBkey() );
1825 continue;
1826 } elseif( $ns == NS_SPECIAL ) {
1827 if( SpecialPage::exists( $nt->getDBkey() ) ) {
1828 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1829 } else {
1830 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1831 }
1832 continue;
1833 } elseif( $ns == NS_IMAGE ) {
1834 $img = wfFindFile( $nt );
1835 if( $img ) {
1836 // Force a blue link if the file exists; may be a remote
1837 // upload on the shared repository, and we want to see its
1838 // auto-generated page.
1839 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1840 $this->mOutput->addLink( $nt );
1841 continue;
1842 }
1843 }
1844 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1845 }
1846 wfProfileOut( __METHOD__ );
1847 return $holders;
1848 }
1849
1850 /**
1851 * Make a link placeholder. The text returned can be later resolved to a real link with
1852 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1853 * parsing of interwiki links, and secondly to allow all existence checks and
1854 * article length checks (for stub links) to be bundled into a single query.
1855 *
1856 * @deprecated
1857 */
1858 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1859 return $this->mLinkHolders->makeHolder( $nt, $text, $query, $trail, $prefix );
1860 }
1861
1862 /**
1863 * Render a forced-blue link inline; protect against double expansion of
1864 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1865 * Since this little disaster has to split off the trail text to avoid
1866 * breaking URLs in the following text without breaking trails on the
1867 * wiki links, it's been made into a horrible function.
1868 *
1869 * @param Title $nt
1870 * @param string $text
1871 * @param string $query
1872 * @param string $trail
1873 * @param string $prefix
1874 * @return string HTML-wikitext mix oh yuck
1875 */
1876 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1877 list( $inside, $trail ) = Linker::splitTrail( $trail );
1878 $sk = $this->mOptions->getSkin();
1879 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1880 return $this->armorLinks( $link ) . $trail;
1881 }
1882
1883 /**
1884 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1885 * going to go through further parsing steps before inline URL expansion.
1886 *
1887 * Not needed quite as much as it used to be since free links are a bit
1888 * more sensible these days. But bracketed links are still an issue.
1889 *
1890 * @param string more-or-less HTML
1891 * @return string less-or-more HTML with NOPARSE bits
1892 */
1893 function armorLinks( $text ) {
1894 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1895 "{$this->mUniqPrefix}NOPARSE$1", $text );
1896 }
1897
1898 /**
1899 * Return true if subpage links should be expanded on this page.
1900 * @return bool
1901 */
1902 function areSubpagesAllowed() {
1903 # Some namespaces don't allow subpages
1904 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
1905 }
1906
1907 /**
1908 * Handle link to subpage if necessary
1909 * @param string $target the source of the link
1910 * @param string &$text the link text, modified as necessary
1911 * @return string the full name of the link
1912 * @private
1913 */
1914 function maybeDoSubpageLink($target, &$text) {
1915 # Valid link forms:
1916 # Foobar -- normal
1917 # :Foobar -- override special treatment of prefix (images, language links)
1918 # /Foobar -- convert to CurrentPage/Foobar
1919 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1920 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1921 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1922
1923 wfProfileIn( __METHOD__ );
1924 $ret = $target; # default return value is no change
1925
1926 # Some namespaces don't allow subpages,
1927 # so only perform processing if subpages are allowed
1928 if( $this->areSubpagesAllowed() ) {
1929 $hash = strpos( $target, '#' );
1930 if( $hash !== false ) {
1931 $suffix = substr( $target, $hash );
1932 $target = substr( $target, 0, $hash );
1933 } else {
1934 $suffix = '';
1935 }
1936 # bug 7425
1937 $target = trim( $target );
1938 # Look at the first character
1939 if( $target != '' && $target{0} === '/' ) {
1940 # / at end means we don't want the slash to be shown
1941 $m = array();
1942 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1943 if( $trailingSlashes ) {
1944 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1945 } else {
1946 $noslash = substr( $target, 1 );
1947 }
1948
1949 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1950 if( '' === $text ) {
1951 $text = $target . $suffix;
1952 } # this might be changed for ugliness reasons
1953 } else {
1954 # check for .. subpage backlinks
1955 $dotdotcount = 0;
1956 $nodotdot = $target;
1957 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1958 ++$dotdotcount;
1959 $nodotdot = substr( $nodotdot, 3 );
1960 }
1961 if($dotdotcount > 0) {
1962 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1963 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1964 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1965 # / at the end means don't show full path
1966 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1967 $nodotdot = substr( $nodotdot, 0, -1 );
1968 if( '' === $text ) {
1969 $text = $nodotdot . $suffix;
1970 }
1971 }
1972 $nodotdot = trim( $nodotdot );
1973 if( $nodotdot != '' ) {
1974 $ret .= '/' . $nodotdot;
1975 }
1976 $ret .= $suffix;
1977 }
1978 }
1979 }
1980 }
1981
1982 wfProfileOut( __METHOD__ );
1983 return $ret;
1984 }
1985
1986 /**#@+
1987 * Used by doBlockLevels()
1988 * @private
1989 */
1990 /* private */ function closeParagraph() {
1991 $result = '';
1992 if ( '' != $this->mLastSection ) {
1993 $result = '</' . $this->mLastSection . ">\n";
1994 }
1995 $this->mInPre = false;
1996 $this->mLastSection = '';
1997 return $result;
1998 }
1999 # getCommon() returns the length of the longest common substring
2000 # of both arguments, starting at the beginning of both.
2001 #
2002 /* private */ function getCommon( $st1, $st2 ) {
2003 $fl = strlen( $st1 );
2004 $shorter = strlen( $st2 );
2005 if ( $fl < $shorter ) { $shorter = $fl; }
2006
2007 for ( $i = 0; $i < $shorter; ++$i ) {
2008 if ( $st1{$i} != $st2{$i} ) { break; }
2009 }
2010 return $i;
2011 }
2012 # These next three functions open, continue, and close the list
2013 # element appropriate to the prefix character passed into them.
2014 #
2015 /* private */ function openList( $char ) {
2016 $result = $this->closeParagraph();
2017
2018 if ( '*' === $char ) { $result .= '<ul><li>'; }
2019 else if ( '#' === $char ) { $result .= '<ol><li>'; }
2020 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
2021 else if ( ';' === $char ) {
2022 $result .= '<dl><dt>';
2023 $this->mDTopen = true;
2024 }
2025 else { $result = '<!-- ERR 1 -->'; }
2026
2027 return $result;
2028 }
2029
2030 /* private */ function nextItem( $char ) {
2031 if ( '*' === $char || '#' === $char ) { return '</li><li>'; }
2032 else if ( ':' === $char || ';' === $char ) {
2033 $close = '</dd>';
2034 if ( $this->mDTopen ) { $close = '</dt>'; }
2035 if ( ';' === $char ) {
2036 $this->mDTopen = true;
2037 return $close . '<dt>';
2038 } else {
2039 $this->mDTopen = false;
2040 return $close . '<dd>';
2041 }
2042 }
2043 return '<!-- ERR 2 -->';
2044 }
2045
2046 /* private */ function closeList( $char ) {
2047 if ( '*' === $char ) { $text = '</li></ul>'; }
2048 else if ( '#' === $char ) { $text = '</li></ol>'; }
2049 else if ( ':' === $char ) {
2050 if ( $this->mDTopen ) {
2051 $this->mDTopen = false;
2052 $text = '</dt></dl>';
2053 } else {
2054 $text = '</dd></dl>';
2055 }
2056 }
2057 else { return '<!-- ERR 3 -->'; }
2058 return $text."\n";
2059 }
2060 /**#@-*/
2061
2062 /**
2063 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2064 *
2065 * @private
2066 * @return string the lists rendered as HTML
2067 */
2068 function doBlockLevels( $text, $linestart ) {
2069 wfProfileIn( __METHOD__ );
2070
2071 # Parsing through the text line by line. The main thing
2072 # happening here is handling of block-level elements p, pre,
2073 # and making lists from lines starting with * # : etc.
2074 #
2075 $textLines = StringUtils::explode( "\n", $text );
2076
2077 $lastPrefix = $output = '';
2078 $this->mDTopen = $inBlockElem = false;
2079 $prefixLength = 0;
2080 $paragraphStack = false;
2081
2082 foreach ( $textLines as $oLine ) {
2083 # Fix up $linestart
2084 if ( !$linestart ) {
2085 $output .= $oLine;
2086 $linestart = true;
2087 continue;
2088 }
2089
2090 $lastPrefixLength = strlen( $lastPrefix );
2091 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2092 $preOpenMatch = preg_match('/<pre/i', $oLine );
2093 if ( !$this->mInPre ) {
2094 # Multiple prefixes may abut each other for nested lists.
2095 $prefixLength = strspn( $oLine, '*#:;' );
2096 $prefix = substr( $oLine, 0, $prefixLength );
2097
2098 # eh?
2099 $prefix2 = str_replace( ';', ':', $prefix );
2100 $t = substr( $oLine, $prefixLength );
2101 $this->mInPre = (bool)$preOpenMatch;
2102 } else {
2103 # Don't interpret any other prefixes in preformatted text
2104 $prefixLength = 0;
2105 $prefix = $prefix2 = '';
2106 $t = $oLine;
2107 }
2108
2109 # List generation
2110 if( $prefixLength && $lastPrefix === $prefix2 ) {
2111 # Same as the last item, so no need to deal with nesting or opening stuff
2112 $output .= $this->nextItem( substr( $prefix, -1 ) );
2113 $paragraphStack = false;
2114
2115 if ( substr( $prefix, -1 ) === ';') {
2116 # The one nasty exception: definition lists work like this:
2117 # ; title : definition text
2118 # So we check for : in the remainder text to split up the
2119 # title and definition, without b0rking links.
2120 $term = $t2 = '';
2121 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2122 $t = $t2;
2123 $output .= $term . $this->nextItem( ':' );
2124 }
2125 }
2126 } elseif( $prefixLength || $lastPrefixLength ) {
2127 # Either open or close a level...
2128 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2129 $paragraphStack = false;
2130
2131 while( $commonPrefixLength < $lastPrefixLength ) {
2132 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2133 --$lastPrefixLength;
2134 }
2135 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2136 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2137 }
2138 while ( $prefixLength > $commonPrefixLength ) {
2139 $char = substr( $prefix, $commonPrefixLength, 1 );
2140 $output .= $this->openList( $char );
2141
2142 if ( ';' === $char ) {
2143 # FIXME: This is dupe of code above
2144 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2145 $t = $t2;
2146 $output .= $term . $this->nextItem( ':' );
2147 }
2148 }
2149 ++$commonPrefixLength;
2150 }
2151 $lastPrefix = $prefix2;
2152 }
2153 if( 0 == $prefixLength ) {
2154 wfProfileIn( __METHOD__."-paragraph" );
2155 # No prefix (not in list)--go to paragraph mode
2156 // XXX: use a stack for nestable elements like span, table and div
2157 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2158 $closematch = preg_match(
2159 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2160 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2161 if ( $openmatch or $closematch ) {
2162 $paragraphStack = false;
2163 # TODO bug 5718: paragraph closed
2164 $output .= $this->closeParagraph();
2165 if ( $preOpenMatch and !$preCloseMatch ) {
2166 $this->mInPre = true;
2167 }
2168 if ( $closematch ) {
2169 $inBlockElem = false;
2170 } else {
2171 $inBlockElem = true;
2172 }
2173 } else if ( !$inBlockElem && !$this->mInPre ) {
2174 if ( ' ' == $t{0} and ( $this->mLastSection === 'pre' or trim($t) != '' ) ) {
2175 // pre
2176 if ($this->mLastSection !== 'pre') {
2177 $paragraphStack = false;
2178 $output .= $this->closeParagraph().'<pre>';
2179 $this->mLastSection = 'pre';
2180 }
2181 $t = substr( $t, 1 );
2182 } else {
2183 // paragraph
2184 if ( '' == trim($t) ) {
2185 if ( $paragraphStack ) {
2186 $output .= $paragraphStack.'<br />';
2187 $paragraphStack = false;
2188 $this->mLastSection = 'p';
2189 } else {
2190 if ($this->mLastSection !== 'p' ) {
2191 $output .= $this->closeParagraph();
2192 $this->mLastSection = '';
2193 $paragraphStack = '<p>';
2194 } else {
2195 $paragraphStack = '</p><p>';
2196 }
2197 }
2198 } else {
2199 if ( $paragraphStack ) {
2200 $output .= $paragraphStack;
2201 $paragraphStack = false;
2202 $this->mLastSection = 'p';
2203 } else if ($this->mLastSection !== 'p') {
2204 $output .= $this->closeParagraph().'<p>';
2205 $this->mLastSection = 'p';
2206 }
2207 }
2208 }
2209 }
2210 wfProfileOut( __METHOD__."-paragraph" );
2211 }
2212 // somewhere above we forget to get out of pre block (bug 785)
2213 if($preCloseMatch && $this->mInPre) {
2214 $this->mInPre = false;
2215 }
2216 if ($paragraphStack === false) {
2217 $output .= $t."\n";
2218 }
2219 }
2220 while ( $prefixLength ) {
2221 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2222 --$prefixLength;
2223 }
2224 if ( '' != $this->mLastSection ) {
2225 $output .= '</' . $this->mLastSection . '>';
2226 $this->mLastSection = '';
2227 }
2228
2229 wfProfileOut( __METHOD__ );
2230 return $output;
2231 }
2232
2233 /**
2234 * Split up a string on ':', ignoring any occurences inside tags
2235 * to prevent illegal overlapping.
2236 * @param string $str the string to split
2237 * @param string &$before set to everything before the ':'
2238 * @param string &$after set to everything after the ':'
2239 * return string the position of the ':', or false if none found
2240 */
2241 function findColonNoLinks($str, &$before, &$after) {
2242 wfProfileIn( __METHOD__ );
2243
2244 $pos = strpos( $str, ':' );
2245 if( $pos === false ) {
2246 // Nothing to find!
2247 wfProfileOut( __METHOD__ );
2248 return false;
2249 }
2250
2251 $lt = strpos( $str, '<' );
2252 if( $lt === false || $lt > $pos ) {
2253 // Easy; no tag nesting to worry about
2254 $before = substr( $str, 0, $pos );
2255 $after = substr( $str, $pos+1 );
2256 wfProfileOut( __METHOD__ );
2257 return $pos;
2258 }
2259
2260 // Ugly state machine to walk through avoiding tags.
2261 $state = self::COLON_STATE_TEXT;
2262 $stack = 0;
2263 $len = strlen( $str );
2264 for( $i = 0; $i < $len; $i++ ) {
2265 $c = $str{$i};
2266
2267 switch( $state ) {
2268 // (Using the number is a performance hack for common cases)
2269 case 0: // self::COLON_STATE_TEXT:
2270 switch( $c ) {
2271 case "<":
2272 // Could be either a <start> tag or an </end> tag
2273 $state = self::COLON_STATE_TAGSTART;
2274 break;
2275 case ":":
2276 if( $stack == 0 ) {
2277 // We found it!
2278 $before = substr( $str, 0, $i );
2279 $after = substr( $str, $i + 1 );
2280 wfProfileOut( __METHOD__ );
2281 return $i;
2282 }
2283 // Embedded in a tag; don't break it.
2284 break;
2285 default:
2286 // Skip ahead looking for something interesting
2287 $colon = strpos( $str, ':', $i );
2288 if( $colon === false ) {
2289 // Nothing else interesting
2290 wfProfileOut( __METHOD__ );
2291 return false;
2292 }
2293 $lt = strpos( $str, '<', $i );
2294 if( $stack === 0 ) {
2295 if( $lt === false || $colon < $lt ) {
2296 // We found it!
2297 $before = substr( $str, 0, $colon );
2298 $after = substr( $str, $colon + 1 );
2299 wfProfileOut( __METHOD__ );
2300 return $i;
2301 }
2302 }
2303 if( $lt === false ) {
2304 // Nothing else interesting to find; abort!
2305 // We're nested, but there's no close tags left. Abort!
2306 break 2;
2307 }
2308 // Skip ahead to next tag start
2309 $i = $lt;
2310 $state = self::COLON_STATE_TAGSTART;
2311 }
2312 break;
2313 case 1: // self::COLON_STATE_TAG:
2314 // In a <tag>
2315 switch( $c ) {
2316 case ">":
2317 $stack++;
2318 $state = self::COLON_STATE_TEXT;
2319 break;
2320 case "/":
2321 // Slash may be followed by >?
2322 $state = self::COLON_STATE_TAGSLASH;
2323 break;
2324 default:
2325 // ignore
2326 }
2327 break;
2328 case 2: // self::COLON_STATE_TAGSTART:
2329 switch( $c ) {
2330 case "/":
2331 $state = self::COLON_STATE_CLOSETAG;
2332 break;
2333 case "!":
2334 $state = self::COLON_STATE_COMMENT;
2335 break;
2336 case ">":
2337 // Illegal early close? This shouldn't happen D:
2338 $state = self::COLON_STATE_TEXT;
2339 break;
2340 default:
2341 $state = self::COLON_STATE_TAG;
2342 }
2343 break;
2344 case 3: // self::COLON_STATE_CLOSETAG:
2345 // In a </tag>
2346 if( $c === ">" ) {
2347 $stack--;
2348 if( $stack < 0 ) {
2349 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
2350 wfProfileOut( __METHOD__ );
2351 return false;
2352 }
2353 $state = self::COLON_STATE_TEXT;
2354 }
2355 break;
2356 case self::COLON_STATE_TAGSLASH:
2357 if( $c === ">" ) {
2358 // Yes, a self-closed tag <blah/>
2359 $state = self::COLON_STATE_TEXT;
2360 } else {
2361 // Probably we're jumping the gun, and this is an attribute
2362 $state = self::COLON_STATE_TAG;
2363 }
2364 break;
2365 case 5: // self::COLON_STATE_COMMENT:
2366 if( $c === "-" ) {
2367 $state = self::COLON_STATE_COMMENTDASH;
2368 }
2369 break;
2370 case self::COLON_STATE_COMMENTDASH:
2371 if( $c === "-" ) {
2372 $state = self::COLON_STATE_COMMENTDASHDASH;
2373 } else {
2374 $state = self::COLON_STATE_COMMENT;
2375 }
2376 break;
2377 case self::COLON_STATE_COMMENTDASHDASH:
2378 if( $c === ">" ) {
2379 $state = self::COLON_STATE_TEXT;
2380 } else {
2381 $state = self::COLON_STATE_COMMENT;
2382 }
2383 break;
2384 default:
2385 throw new MWException( "State machine error in " . __METHOD__ );
2386 }
2387 }
2388 if( $stack > 0 ) {
2389 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2390 return false;
2391 }
2392 wfProfileOut( __METHOD__ );
2393 return false;
2394 }
2395
2396 /**
2397 * Return value of a magic variable (like PAGENAME)
2398 *
2399 * @private
2400 */
2401 function getVariableValue( $index ) {
2402 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2403
2404 /**
2405 * Some of these require message or data lookups and can be
2406 * expensive to check many times.
2407 */
2408 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2409 if ( isset( $this->mVarCache[$index] ) ) {
2410 return $this->mVarCache[$index];
2411 }
2412 }
2413
2414 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2415 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2416
2417 # Use the time zone
2418 global $wgLocaltimezone;
2419 if ( isset( $wgLocaltimezone ) ) {
2420 $oldtz = getenv( 'TZ' );
2421 putenv( 'TZ='.$wgLocaltimezone );
2422 }
2423
2424 wfSuppressWarnings(); // E_STRICT system time bitching
2425 $localTimestamp = date( 'YmdHis', $ts );
2426 $localMonth = date( 'm', $ts );
2427 $localMonthName = date( 'n', $ts );
2428 $localDay = date( 'j', $ts );
2429 $localDay2 = date( 'd', $ts );
2430 $localDayOfWeek = date( 'w', $ts );
2431 $localWeek = date( 'W', $ts );
2432 $localYear = date( 'Y', $ts );
2433 $localHour = date( 'H', $ts );
2434 if ( isset( $wgLocaltimezone ) ) {
2435 putenv( 'TZ='.$oldtz );
2436 }
2437 wfRestoreWarnings();
2438
2439 switch ( $index ) {
2440 case 'currentmonth':
2441 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2442 case 'currentmonthname':
2443 return $this->mVarCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2444 case 'currentmonthnamegen':
2445 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2446 case 'currentmonthabbrev':
2447 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2448 case 'currentday':
2449 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2450 case 'currentday2':
2451 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2452 case 'localmonth':
2453 return $this->mVarCache[$index] = $wgContLang->formatNum( $localMonth );
2454 case 'localmonthname':
2455 return $this->mVarCache[$index] = $wgContLang->getMonthName( $localMonthName );
2456 case 'localmonthnamegen':
2457 return $this->mVarCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2458 case 'localmonthabbrev':
2459 return $this->mVarCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2460 case 'localday':
2461 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay );
2462 case 'localday2':
2463 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDay2 );
2464 case 'pagename':
2465 return wfEscapeWikiText( $this->mTitle->getText() );
2466 case 'pagenamee':
2467 return $this->mTitle->getPartialURL();
2468 case 'fullpagename':
2469 return wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2470 case 'fullpagenamee':
2471 return $this->mTitle->getPrefixedURL();
2472 case 'subpagename':
2473 return wfEscapeWikiText( $this->mTitle->getSubpageText() );
2474 case 'subpagenamee':
2475 return $this->mTitle->getSubpageUrlForm();
2476 case 'basepagename':
2477 return wfEscapeWikiText( $this->mTitle->getBaseText() );
2478 case 'basepagenamee':
2479 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2480 case 'talkpagename':
2481 if( $this->mTitle->canTalk() ) {
2482 $talkPage = $this->mTitle->getTalkPage();
2483 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2484 } else {
2485 return '';
2486 }
2487 case 'talkpagenamee':
2488 if( $this->mTitle->canTalk() ) {
2489 $talkPage = $this->mTitle->getTalkPage();
2490 return $talkPage->getPrefixedUrl();
2491 } else {
2492 return '';
2493 }
2494 case 'subjectpagename':
2495 $subjPage = $this->mTitle->getSubjectPage();
2496 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2497 case 'subjectpagenamee':
2498 $subjPage = $this->mTitle->getSubjectPage();
2499 return $subjPage->getPrefixedUrl();
2500 case 'revisionid':
2501 // Let the edit saving system know we should parse the page
2502 // *after* a revision ID has been assigned.
2503 $this->mOutput->setFlag( 'vary-revision' );
2504 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2505 return $this->mRevisionId;
2506 case 'revisionday':
2507 // Let the edit saving system know we should parse the page
2508 // *after* a revision ID has been assigned. This is for null edits.
2509 $this->mOutput->setFlag( 'vary-revision' );
2510 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2511 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2512 case 'revisionday2':
2513 // Let the edit saving system know we should parse the page
2514 // *after* a revision ID has been assigned. This is for null edits.
2515 $this->mOutput->setFlag( 'vary-revision' );
2516 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2517 return substr( $this->getRevisionTimestamp(), 6, 2 );
2518 case 'revisionmonth':
2519 // Let the edit saving system know we should parse the page
2520 // *after* a revision ID has been assigned. This is for null edits.
2521 $this->mOutput->setFlag( 'vary-revision' );
2522 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2523 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2524 case 'revisionyear':
2525 // Let the edit saving system know we should parse the page
2526 // *after* a revision ID has been assigned. This is for null edits.
2527 $this->mOutput->setFlag( 'vary-revision' );
2528 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2529 return substr( $this->getRevisionTimestamp(), 0, 4 );
2530 case 'revisiontimestamp':
2531 // Let the edit saving system know we should parse the page
2532 // *after* a revision ID has been assigned. This is for null edits.
2533 $this->mOutput->setFlag( 'vary-revision' );
2534 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2535 return $this->getRevisionTimestamp();
2536 case 'namespace':
2537 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2538 case 'namespacee':
2539 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2540 case 'talkspace':
2541 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2542 case 'talkspacee':
2543 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2544 case 'subjectspace':
2545 return $this->mTitle->getSubjectNsText();
2546 case 'subjectspacee':
2547 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2548 case 'currentdayname':
2549 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2550 case 'currentyear':
2551 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2552 case 'currenttime':
2553 return $this->mVarCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2554 case 'currenthour':
2555 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2556 case 'currentweek':
2557 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2558 // int to remove the padding
2559 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2560 case 'currentdow':
2561 return $this->mVarCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2562 case 'localdayname':
2563 return $this->mVarCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2564 case 'localyear':
2565 return $this->mVarCache[$index] = $wgContLang->formatNum( $localYear, true );
2566 case 'localtime':
2567 return $this->mVarCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2568 case 'localhour':
2569 return $this->mVarCache[$index] = $wgContLang->formatNum( $localHour, true );
2570 case 'localweek':
2571 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2572 // int to remove the padding
2573 return $this->mVarCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2574 case 'localdow':
2575 return $this->mVarCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2576 case 'numberofarticles':
2577 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2578 case 'numberoffiles':
2579 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2580 case 'numberofusers':
2581 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2582 case 'numberofpages':
2583 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2584 case 'numberofadmins':
2585 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::numberingroup('sysop') );
2586 case 'numberofedits':
2587 return $this->mVarCache[$index] = $wgContLang->formatNum( SiteStats::edits() );
2588 case 'currenttimestamp':
2589 return $this->mVarCache[$index] = wfTimestamp( TS_MW, $ts );
2590 case 'localtimestamp':
2591 return $this->mVarCache[$index] = $localTimestamp;
2592 case 'currentversion':
2593 return $this->mVarCache[$index] = SpecialVersion::getVersion();
2594 case 'sitename':
2595 return $wgSitename;
2596 case 'server':
2597 return $wgServer;
2598 case 'servername':
2599 return $wgServerName;
2600 case 'scriptpath':
2601 return $wgScriptPath;
2602 case 'directionmark':
2603 return $wgContLang->getDirMark();
2604 case 'contentlanguage':
2605 global $wgContLanguageCode;
2606 return $wgContLanguageCode;
2607 default:
2608 $ret = null;
2609 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret ) ) )
2610 return $ret;
2611 else
2612 return null;
2613 }
2614 }
2615
2616 /**
2617 * initialise the magic variables (like CURRENTMONTHNAME)
2618 *
2619 * @private
2620 */
2621 function initialiseVariables() {
2622 wfProfileIn( __METHOD__ );
2623 $variableIDs = MagicWord::getVariableIDs();
2624
2625 $this->mVariables = new MagicWordArray( $variableIDs );
2626 wfProfileOut( __METHOD__ );
2627 }
2628
2629 /**
2630 * Preprocess some wikitext and return the document tree.
2631 * This is the ghost of replace_variables().
2632 *
2633 * @param string $text The text to parse
2634 * @param integer flags Bitwise combination of:
2635 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2636 * included. Default is to assume a direct page view.
2637 *
2638 * The generated DOM tree must depend only on the input text and the flags.
2639 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2640 *
2641 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2642 * change in the DOM tree for a given text, must be passed through the section identifier
2643 * in the section edit link and thus back to extractSections().
2644 *
2645 * The output of this function is currently only cached in process memory, but a persistent
2646 * cache may be implemented at a later date which takes further advantage of these strict
2647 * dependency requirements.
2648 *
2649 * @private
2650 */
2651 function preprocessToDom ( $text, $flags = 0 ) {
2652 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2653 return $dom;
2654 }
2655
2656 /*
2657 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2658 */
2659 public static function splitWhitespace( $s ) {
2660 $ltrimmed = ltrim( $s );
2661 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2662 $trimmed = rtrim( $ltrimmed );
2663 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2664 if ( $diff > 0 ) {
2665 $w2 = substr( $ltrimmed, -$diff );
2666 } else {
2667 $w2 = '';
2668 }
2669 return array( $w1, $trimmed, $w2 );
2670 }
2671
2672 /**
2673 * Replace magic variables, templates, and template arguments
2674 * with the appropriate text. Templates are substituted recursively,
2675 * taking care to avoid infinite loops.
2676 *
2677 * Note that the substitution depends on value of $mOutputType:
2678 * self::OT_WIKI: only {{subst:}} templates
2679 * self::OT_PREPROCESS: templates but not extension tags
2680 * self::OT_HTML: all templates and extension tags
2681 *
2682 * @param string $tex The text to transform
2683 * @param PPFrame $frame Object describing the arguments passed to the template.
2684 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2685 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2686 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2687 * @private
2688 */
2689 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2690 # Prevent too big inclusions
2691 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2692 return $text;
2693 }
2694
2695 wfProfileIn( __METHOD__ );
2696
2697 if ( $frame === false ) {
2698 $frame = $this->getPreprocessor()->newFrame();
2699 } elseif ( !( $frame instanceof PPFrame ) ) {
2700 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2701 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2702 }
2703
2704 $dom = $this->preprocessToDom( $text );
2705 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2706 $text = $frame->expand( $dom, $flags );
2707
2708 wfProfileOut( __METHOD__ );
2709 return $text;
2710 }
2711
2712 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2713 static function createAssocArgs( $args ) {
2714 $assocArgs = array();
2715 $index = 1;
2716 foreach( $args as $arg ) {
2717 $eqpos = strpos( $arg, '=' );
2718 if ( $eqpos === false ) {
2719 $assocArgs[$index++] = $arg;
2720 } else {
2721 $name = trim( substr( $arg, 0, $eqpos ) );
2722 $value = trim( substr( $arg, $eqpos+1 ) );
2723 if ( $value === false ) {
2724 $value = '';
2725 }
2726 if ( $name !== false ) {
2727 $assocArgs[$name] = $value;
2728 }
2729 }
2730 }
2731
2732 return $assocArgs;
2733 }
2734
2735 /**
2736 * Warn the user when a parser limitation is reached
2737 * Will warn at most once the user per limitation type
2738 *
2739 * @param string $limitationType, should be one of:
2740 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2741 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2742 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2743 * @params int $current, $max When an explicit limit has been
2744 * exceeded, provide the values (optional)
2745 */
2746 function limitationWarn( $limitationType, $current=null, $max=null) {
2747 $msgName = $limitationType . '-warning';
2748 //does no harm if $current and $max are present but are unnecessary for the message
2749 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2750 $this->mOutput->addWarning( $warning );
2751 $cat = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( $limitationType . '-category' ) );
2752 if ( $cat ) {
2753 $this->mOutput->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2754 }
2755 }
2756
2757 /**
2758 * Return the text of a template, after recursively
2759 * replacing any variables or templates within the template.
2760 *
2761 * @param array $piece The parts of the template
2762 * $piece['title']: the title, i.e. the part before the |
2763 * $piece['parts']: the parameter array
2764 * $piece['lineStart']: whether the brace was at the start of a line
2765 * @param PPFrame The current frame, contains template arguments
2766 * @return string the text of the template
2767 * @private
2768 */
2769 function braceSubstitution( $piece, $frame ) {
2770 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
2771 wfProfileIn( __METHOD__ );
2772 wfProfileIn( __METHOD__.'-setup' );
2773
2774 # Flags
2775 $found = false; # $text has been filled
2776 $nowiki = false; # wiki markup in $text should be escaped
2777 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2778 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2779 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2780 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2781
2782 # Title object, where $text came from
2783 $title = NULL;
2784
2785 # $part1 is the bit before the first |, and must contain only title characters.
2786 # Various prefixes will be stripped from it later.
2787 $titleWithSpaces = $frame->expand( $piece['title'] );
2788 $part1 = trim( $titleWithSpaces );
2789 $titleText = false;
2790
2791 # Original title text preserved for various purposes
2792 $originalTitle = $part1;
2793
2794 # $args is a list of argument nodes, starting from index 0, not including $part1
2795 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2796 wfProfileOut( __METHOD__.'-setup' );
2797
2798 # SUBST
2799 wfProfileIn( __METHOD__.'-modifiers' );
2800 if ( !$found ) {
2801 $mwSubst = MagicWord::get( 'subst' );
2802 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
2803 # One of two possibilities is true:
2804 # 1) Found SUBST but not in the PST phase
2805 # 2) Didn't find SUBST and in the PST phase
2806 # In either case, return without further processing
2807 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2808 $isLocalObj = true;
2809 $found = true;
2810 }
2811 }
2812
2813 # Variables
2814 if ( !$found && $args->getLength() == 0 ) {
2815 $id = $this->mVariables->matchStartToEnd( $part1 );
2816 if ( $id !== false ) {
2817 $text = $this->getVariableValue( $id );
2818 if (MagicWord::getCacheTTL($id)>-1)
2819 $this->mOutput->mContainsOldMagic = true;
2820 $found = true;
2821 }
2822 }
2823
2824 # MSG, MSGNW and RAW
2825 if ( !$found ) {
2826 # Check for MSGNW:
2827 $mwMsgnw = MagicWord::get( 'msgnw' );
2828 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2829 $nowiki = true;
2830 } else {
2831 # Remove obsolete MSG:
2832 $mwMsg = MagicWord::get( 'msg' );
2833 $mwMsg->matchStartAndRemove( $part1 );
2834 }
2835
2836 # Check for RAW:
2837 $mwRaw = MagicWord::get( 'raw' );
2838 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2839 $forceRawInterwiki = true;
2840 }
2841 }
2842 wfProfileOut( __METHOD__.'-modifiers' );
2843
2844 # Parser functions
2845 if ( !$found ) {
2846 wfProfileIn( __METHOD__ . '-pfunc' );
2847
2848 $colonPos = strpos( $part1, ':' );
2849 if ( $colonPos !== false ) {
2850 # Case sensitive functions
2851 $function = substr( $part1, 0, $colonPos );
2852 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
2853 $function = $this->mFunctionSynonyms[1][$function];
2854 } else {
2855 # Case insensitive functions
2856 $function = strtolower( $function );
2857 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
2858 $function = $this->mFunctionSynonyms[0][$function];
2859 } else {
2860 $function = false;
2861 }
2862 }
2863 if ( $function ) {
2864 list( $callback, $flags ) = $this->mFunctionHooks[$function];
2865 $initialArgs = array( &$this );
2866 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
2867 if ( $flags & SFH_OBJECT_ARGS ) {
2868 # Add a frame parameter, and pass the arguments as an array
2869 $allArgs = $initialArgs;
2870 $allArgs[] = $frame;
2871 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2872 $funcArgs[] = $args->item( $i );
2873 }
2874 $allArgs[] = $funcArgs;
2875 } else {
2876 # Convert arguments to plain text
2877 for ( $i = 0; $i < $args->getLength(); $i++ ) {
2878 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2879 }
2880 $allArgs = array_merge( $initialArgs, $funcArgs );
2881 }
2882
2883 # Workaround for PHP bug 35229 and similar
2884 if ( !is_callable( $callback ) ) {
2885 throw new MWException( "Tag hook for $function is not callable\n" );
2886 }
2887 $result = call_user_func_array( $callback, $allArgs );
2888 $found = true;
2889 $noparse = true;
2890 $preprocessFlags = 0;
2891
2892 if ( is_array( $result ) ) {
2893 if ( isset( $result[0] ) ) {
2894 $text = $result[0];
2895 unset( $result[0] );
2896 }
2897
2898 // Extract flags into the local scope
2899 // This allows callers to set flags such as nowiki, found, etc.
2900 extract( $result );
2901 } else {
2902 $text = $result;
2903 }
2904 if ( !$noparse ) {
2905 $text = $this->preprocessToDom( $text, $preprocessFlags );
2906 $isChildObj = true;
2907 }
2908 }
2909 }
2910 wfProfileOut( __METHOD__ . '-pfunc' );
2911 }
2912
2913 # Finish mangling title and then check for loops.
2914 # Set $title to a Title object and $titleText to the PDBK
2915 if ( !$found ) {
2916 $ns = NS_TEMPLATE;
2917 # Split the title into page and subpage
2918 $subpage = '';
2919 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2920 if ($subpage !== '') {
2921 $ns = $this->mTitle->getNamespace();
2922 }
2923 $title = Title::newFromText( $part1, $ns );
2924 if ( $title ) {
2925 $titleText = $title->getPrefixedText();
2926 # Check for language variants if the template is not found
2927 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2928 $wgContLang->findVariantLink( $part1, $title, true );
2929 }
2930 # Do infinite loop check
2931 if ( !$frame->loopCheck( $title ) ) {
2932 $found = true;
2933 $text = "<span class=\"error\">Template loop detected: [[$titleText]]</span>";
2934 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
2935 }
2936 # Do recursion depth check
2937 $limit = $this->mOptions->getMaxTemplateDepth();
2938 if ( $frame->depth >= $limit ) {
2939 $found = true;
2940 $text = "<span class=\"error\">Template recursion depth limit exceeded ($limit)</span>";
2941 }
2942 }
2943 }
2944
2945 # Load from database
2946 if ( !$found && $title ) {
2947 wfProfileIn( __METHOD__ . '-loadtpl' );
2948 if ( !$title->isExternal() ) {
2949 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
2950 $text = SpecialPage::capturePath( $title );
2951 if ( is_string( $text ) ) {
2952 $found = true;
2953 $isHTML = true;
2954 $this->disableCache();
2955 }
2956 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2957 $found = false; //access denied
2958 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
2959 } else {
2960 list( $text, $title ) = $this->getTemplateDom( $title );
2961 if ( $text !== false ) {
2962 $found = true;
2963 $isChildObj = true;
2964 }
2965 }
2966
2967 # If the title is valid but undisplayable, make a link to it
2968 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
2969 $text = "[[:$titleText]]";
2970 $found = true;
2971 }
2972 } elseif ( $title->isTrans() ) {
2973 // Interwiki transclusion
2974 if ( $this->ot['html'] && !$forceRawInterwiki ) {
2975 $text = $this->interwikiTransclude( $title, 'render' );
2976 $isHTML = true;
2977 } else {
2978 $text = $this->interwikiTransclude( $title, 'raw' );
2979 // Preprocess it like a template
2980 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
2981 $isChildObj = true;
2982 }
2983 $found = true;
2984 }
2985 wfProfileOut( __METHOD__ . '-loadtpl' );
2986 }
2987
2988 # If we haven't found text to substitute by now, we're done
2989 # Recover the source wikitext and return it
2990 if ( !$found ) {
2991 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2992 wfProfileOut( __METHOD__ );
2993 return array( 'object' => $text );
2994 }
2995
2996 # Expand DOM-style return values in a child frame
2997 if ( $isChildObj ) {
2998 # Clean up argument array
2999 $newFrame = $frame->newChild( $args, $title );
3000
3001 if ( $nowiki ) {
3002 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3003 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3004 # Expansion is eligible for the empty-frame cache
3005 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3006 $text = $this->mTplExpandCache[$titleText];
3007 } else {
3008 $text = $newFrame->expand( $text );
3009 $this->mTplExpandCache[$titleText] = $text;
3010 }
3011 } else {
3012 # Uncached expansion
3013 $text = $newFrame->expand( $text );
3014 }
3015 }
3016 if ( $isLocalObj && $nowiki ) {
3017 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3018 $isLocalObj = false;
3019 }
3020
3021 # Replace raw HTML by a placeholder
3022 # Add a blank line preceding, to prevent it from mucking up
3023 # immediately preceding headings
3024 if ( $isHTML ) {
3025 $text = "\n\n" . $this->insertStripItem( $text );
3026 }
3027 # Escape nowiki-style return values
3028 elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3029 $text = wfEscapeWikiText( $text );
3030 }
3031 # Bug 529: if the template begins with a table or block-level
3032 # element, it should be treated as beginning a new line.
3033 # This behaviour is somewhat controversial.
3034 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3035 $text = "\n" . $text;
3036 }
3037
3038 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3039 # Error, oversize inclusion
3040 $text = "[[$originalTitle]]" .
3041 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3042 $this->limitationWarn( 'post-expand-template-inclusion' );
3043 }
3044
3045 if ( $isLocalObj ) {
3046 $ret = array( 'object' => $text );
3047 } else {
3048 $ret = array( 'text' => $text );
3049 }
3050
3051 wfProfileOut( __METHOD__ );
3052 return $ret;
3053 }
3054
3055 /**
3056 * Get the semi-parsed DOM representation of a template with a given title,
3057 * and its redirect destination title. Cached.
3058 */
3059 function getTemplateDom( $title ) {
3060 $cacheTitle = $title;
3061 $titleText = $title->getPrefixedDBkey();
3062
3063 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3064 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3065 $title = Title::makeTitle( $ns, $dbk );
3066 $titleText = $title->getPrefixedDBkey();
3067 }
3068 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3069 return array( $this->mTplDomCache[$titleText], $title );
3070 }
3071
3072 // Cache miss, go to the database
3073 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3074
3075 if ( $text === false ) {
3076 $this->mTplDomCache[$titleText] = false;
3077 return array( false, $title );
3078 }
3079
3080 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3081 $this->mTplDomCache[ $titleText ] = $dom;
3082
3083 if (! $title->equals($cacheTitle)) {
3084 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3085 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3086 }
3087
3088 return array( $dom, $title );
3089 }
3090
3091 /**
3092 * Fetch the unparsed text of a template and register a reference to it.
3093 */
3094 function fetchTemplateAndTitle( $title ) {
3095 $templateCb = $this->mOptions->getTemplateCallback();
3096 $stuff = call_user_func( $templateCb, $title, $this );
3097 $text = $stuff['text'];
3098 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3099 if ( isset( $stuff['deps'] ) ) {
3100 foreach ( $stuff['deps'] as $dep ) {
3101 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3102 }
3103 }
3104 return array($text,$finalTitle);
3105 }
3106
3107 function fetchTemplate( $title ) {
3108 $rv = $this->fetchTemplateAndTitle($title);
3109 return $rv[0];
3110 }
3111
3112 /**
3113 * Static function to get a template
3114 * Can be overridden via ParserOptions::setTemplateCallback().
3115 */
3116 static function statelessFetchTemplate( $title, $parser=false ) {
3117 $text = $skip = false;
3118 $finalTitle = $title;
3119 $deps = array();
3120
3121 // Loop to fetch the article, with up to 1 redirect
3122 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3123 # Give extensions a chance to select the revision instead
3124 $id = false; // Assume current
3125 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3126
3127 if( $skip ) {
3128 $text = false;
3129 $deps[] = array(
3130 'title' => $title,
3131 'page_id' => $title->getArticleID(),
3132 'rev_id' => null );
3133 break;
3134 }
3135 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3136 $rev_id = $rev ? $rev->getId() : 0;
3137 // If there is no current revision, there is no page
3138 if( $id === false && !$rev ) {
3139 $linkCache = LinkCache::singleton();
3140 $linkCache->addBadLinkObj( $title );
3141 }
3142
3143 $deps[] = array(
3144 'title' => $title,
3145 'page_id' => $title->getArticleID(),
3146 'rev_id' => $rev_id );
3147
3148 if( $rev ) {
3149 $text = $rev->getText();
3150 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3151 global $wgLang;
3152 $message = $wgLang->lcfirst( $title->getText() );
3153 $text = wfMsgForContentNoTrans( $message );
3154 if( wfEmptyMsg( $message, $text ) ) {
3155 $text = false;
3156 break;
3157 }
3158 } else {
3159 break;
3160 }
3161 if ( $text === false ) {
3162 break;
3163 }
3164 // Redirect?
3165 $finalTitle = $title;
3166 $title = Title::newFromRedirect( $text );
3167 }
3168 return array(
3169 'text' => $text,
3170 'finalTitle' => $finalTitle,
3171 'deps' => $deps );
3172 }
3173
3174 /**
3175 * Transclude an interwiki link.
3176 */
3177 function interwikiTransclude( $title, $action ) {
3178 global $wgEnableScaryTranscluding;
3179
3180 if (!$wgEnableScaryTranscluding)
3181 return wfMsg('scarytranscludedisabled');
3182
3183 $url = $title->getFullUrl( "action=$action" );
3184
3185 if (strlen($url) > 255)
3186 return wfMsg('scarytranscludetoolong');
3187 return $this->fetchScaryTemplateMaybeFromCache($url);
3188 }
3189
3190 function fetchScaryTemplateMaybeFromCache($url) {
3191 global $wgTranscludeCacheExpiry;
3192 $dbr = wfGetDB(DB_SLAVE);
3193 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3194 array('tc_url' => $url));
3195 if ($obj) {
3196 $time = $obj->tc_time;
3197 $text = $obj->tc_contents;
3198 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3199 return $text;
3200 }
3201 }
3202
3203 $text = Http::get($url);
3204 if (!$text)
3205 return wfMsg('scarytranscludefailed', $url);
3206
3207 $dbw = wfGetDB(DB_MASTER);
3208 $dbw->replace('transcache', array('tc_url'), array(
3209 'tc_url' => $url,
3210 'tc_time' => time(),
3211 'tc_contents' => $text));
3212 return $text;
3213 }
3214
3215
3216 /**
3217 * Triple brace replacement -- used for template arguments
3218 * @private
3219 */
3220 function argSubstitution( $piece, $frame ) {
3221 wfProfileIn( __METHOD__ );
3222
3223 $error = false;
3224 $parts = $piece['parts'];
3225 $nameWithSpaces = $frame->expand( $piece['title'] );
3226 $argName = trim( $nameWithSpaces );
3227 $object = false;
3228 $text = $frame->getArgument( $argName );
3229 if ( $text === false && $parts->getLength() > 0
3230 && (
3231 $this->ot['html']
3232 || $this->ot['pre']
3233 || ( $this->ot['wiki'] && $frame->isTemplate() )
3234 )
3235 ) {
3236 # No match in frame, use the supplied default
3237 $object = $parts->item( 0 )->getChildren();
3238 }
3239 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3240 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3241 $this->limitationWarn( 'post-expand-template-argument' );
3242 }
3243
3244 if ( $text === false && $object === false ) {
3245 # No match anywhere
3246 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3247 }
3248 if ( $error !== false ) {
3249 $text .= $error;
3250 }
3251 if ( $object !== false ) {
3252 $ret = array( 'object' => $object );
3253 } else {
3254 $ret = array( 'text' => $text );
3255 }
3256
3257 wfProfileOut( __METHOD__ );
3258 return $ret;
3259 }
3260
3261 /**
3262 * Return the text to be used for a given extension tag.
3263 * This is the ghost of strip().
3264 *
3265 * @param array $params Associative array of parameters:
3266 * name PPNode for the tag name
3267 * attr PPNode for unparsed text where tag attributes are thought to be
3268 * attributes Optional associative array of parsed attributes
3269 * inner Contents of extension element
3270 * noClose Original text did not have a close tag
3271 * @param PPFrame $frame
3272 */
3273 function extensionSubstitution( $params, $frame ) {
3274 global $wgRawHtml, $wgContLang;
3275
3276 $name = $frame->expand( $params['name'] );
3277 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3278 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3279
3280 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++) . self::MARKER_SUFFIX;
3281
3282 if ( $this->ot['html'] ) {
3283 $name = strtolower( $name );
3284
3285 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3286 if ( isset( $params['attributes'] ) ) {
3287 $attributes = $attributes + $params['attributes'];
3288 }
3289 switch ( $name ) {
3290 case 'html':
3291 if( $wgRawHtml ) {
3292 $output = $content;
3293 break;
3294 } else {
3295 throw new MWException( '<html> extension tag encountered unexpectedly' );
3296 }
3297 case 'nowiki':
3298 $output = Xml::escapeTagsOnly( $content );
3299 break;
3300 case 'math':
3301 $output = $wgContLang->armourMath(
3302 MathRenderer::renderMath( $content, $attributes ) );
3303 break;
3304 case 'gallery':
3305 $output = $this->renderImageGallery( $content, $attributes );
3306 break;
3307 default:
3308 if( isset( $this->mTagHooks[$name] ) ) {
3309 # Workaround for PHP bug 35229 and similar
3310 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3311 throw new MWException( "Tag hook for $name is not callable\n" );
3312 }
3313 $output = call_user_func_array( $this->mTagHooks[$name],
3314 array( $content, $attributes, $this ) );
3315 } else {
3316 $output = '<span class="error">Invalid tag extension name: ' .
3317 htmlspecialchars( $name ) . '</span>';
3318 }
3319 }
3320 } else {
3321 if ( is_null( $attrText ) ) {
3322 $attrText = '';
3323 }
3324 if ( isset( $params['attributes'] ) ) {
3325 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3326 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3327 htmlspecialchars( $attrValue ) . '"';
3328 }
3329 }
3330 if ( $content === null ) {
3331 $output = "<$name$attrText/>";
3332 } else {
3333 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3334 $output = "<$name$attrText>$content$close";
3335 }
3336 }
3337
3338 if ( $name === 'html' || $name === 'nowiki' ) {
3339 $this->mStripState->nowiki->setPair( $marker, $output );
3340 } else {
3341 $this->mStripState->general->setPair( $marker, $output );
3342 }
3343 return $marker;
3344 }
3345
3346 /**
3347 * Increment an include size counter
3348 *
3349 * @param string $type The type of expansion
3350 * @param integer $size The size of the text
3351 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3352 */
3353 function incrementIncludeSize( $type, $size ) {
3354 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3355 return false;
3356 } else {
3357 $this->mIncludeSizes[$type] += $size;
3358 return true;
3359 }
3360 }
3361
3362 /**
3363 * Increment the expensive function count
3364 *
3365 * @return boolean False if the limit has been exceeded
3366 */
3367 function incrementExpensiveFunctionCount() {
3368 global $wgExpensiveParserFunctionLimit;
3369 $this->mExpensiveFunctionCount++;
3370 if($this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit) {
3371 return true;
3372 }
3373 return false;
3374 }
3375
3376 /**
3377 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3378 * Fills $this->mDoubleUnderscores, returns the modified text
3379 */
3380 function doDoubleUnderscore( $text ) {
3381 // The position of __TOC__ needs to be recorded
3382 $mw = MagicWord::get( 'toc' );
3383 if( $mw->match( $text ) ) {
3384 $this->mShowToc = true;
3385 $this->mForceTocPosition = true;
3386
3387 // Set a placeholder. At the end we'll fill it in with the TOC.
3388 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3389
3390 // Only keep the first one.
3391 $text = $mw->replace( '', $text );
3392 }
3393
3394 // Now match and remove the rest of them
3395 $mwa = MagicWord::getDoubleUnderscoreArray();
3396 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3397
3398 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3399 $this->mOutput->mNoGallery = true;
3400 }
3401 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3402 $this->mShowToc = false;
3403 }
3404 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3405 $this->mOutput->setProperty( 'hiddencat', 'y' );
3406
3407 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, wfMsgForContent( 'hidden-category-category' ) );
3408 if ( $containerCategory ) {
3409 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3410 } else {
3411 wfDebug( __METHOD__.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3412 }
3413 }
3414 # (bug 8068) Allow control over whether robots index a page.
3415 #
3416 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3417 # is not desirable, the last one on the page should win.
3418 if( isset( $this->mDoubleUnderscores['noindex'] ) ) {
3419 $this->mOutput->setIndexPolicy( 'noindex' );
3420 } elseif( isset( $this->mDoubleUnderscores['index'] ) ) {
3421 $this->mOutput->setIndexPolicy( 'index' );
3422 }
3423
3424 return $text;
3425 }
3426
3427 /**
3428 * This function accomplishes several tasks:
3429 * 1) Auto-number headings if that option is enabled
3430 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3431 * 3) Add a Table of contents on the top for users who have enabled the option
3432 * 4) Auto-anchor headings
3433 *
3434 * It loops through all headlines, collects the necessary data, then splits up the
3435 * string and re-inserts the newly formatted headlines.
3436 *
3437 * @param string $text
3438 * @param boolean $isMain
3439 * @private
3440 */
3441 function formatHeadings( $text, $isMain=true ) {
3442 global $wgMaxTocLevel, $wgContLang;
3443
3444 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3445 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3446 $showEditLink = 0;
3447 } else {
3448 $showEditLink = $this->mOptions->getEditSection();
3449 }
3450
3451 # Inhibit editsection links if requested in the page
3452 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3453 $showEditLink = 0;
3454 }
3455
3456 # Get all headlines for numbering them and adding funky stuff like [edit]
3457 # links - this is for later, but we need the number of headlines right now
3458 $matches = array();
3459 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3460
3461 # if there are fewer than 4 headlines in the article, do not show TOC
3462 # unless it's been explicitly enabled.
3463 $enoughToc = $this->mShowToc &&
3464 (($numMatches >= 4) || $this->mForceTocPosition);
3465
3466 # Allow user to stipulate that a page should have a "new section"
3467 # link added via __NEWSECTIONLINK__
3468 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3469 $this->mOutput->setNewSection( true );
3470 }
3471
3472 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3473 # override above conditions and always show TOC above first header
3474 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3475 $this->mShowToc = true;
3476 $enoughToc = true;
3477 }
3478
3479 # We need this to perform operations on the HTML
3480 $sk = $this->mOptions->getSkin();
3481
3482 # headline counter
3483 $headlineCount = 0;
3484 $numVisible = 0;
3485
3486 # Ugh .. the TOC should have neat indentation levels which can be
3487 # passed to the skin functions. These are determined here
3488 $toc = '';
3489 $full = '';
3490 $head = array();
3491 $sublevelCount = array();
3492 $levelCount = array();
3493 $toclevel = 0;
3494 $level = 0;
3495 $prevlevel = 0;
3496 $toclevel = 0;
3497 $prevtoclevel = 0;
3498 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3499 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3500 $tocraw = array();
3501
3502 foreach( $matches[3] as $headline ) {
3503 $isTemplate = false;
3504 $titleText = false;
3505 $sectionIndex = false;
3506 $numbering = '';
3507 $markerMatches = array();
3508 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3509 $serial = $markerMatches[1];
3510 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3511 $isTemplate = ($titleText != $baseTitleText);
3512 $headline = preg_replace("/^$markerRegex/", "", $headline);
3513 }
3514
3515 if( $toclevel ) {
3516 $prevlevel = $level;
3517 $prevtoclevel = $toclevel;
3518 }
3519 $level = $matches[1][$headlineCount];
3520
3521 if( $doNumberHeadings || $enoughToc ) {
3522
3523 if ( $level > $prevlevel ) {
3524 # Increase TOC level
3525 $toclevel++;
3526 $sublevelCount[$toclevel] = 0;
3527 if( $toclevel<$wgMaxTocLevel ) {
3528 $prevtoclevel = $toclevel;
3529 $toc .= $sk->tocIndent();
3530 $numVisible++;
3531 }
3532 }
3533 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3534 # Decrease TOC level, find level to jump to
3535
3536 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3537 # Can only go down to level 1
3538 $toclevel = 1;
3539 } else {
3540 for ($i = $toclevel; $i > 0; $i--) {
3541 if ( $levelCount[$i] == $level ) {
3542 # Found last matching level
3543 $toclevel = $i;
3544 break;
3545 }
3546 elseif ( $levelCount[$i] < $level ) {
3547 # Found first matching level below current level
3548 $toclevel = $i + 1;
3549 break;
3550 }
3551 }
3552 }
3553 if( $toclevel<$wgMaxTocLevel ) {
3554 if($prevtoclevel < $wgMaxTocLevel) {
3555 # Unindent only if the previous toc level was shown :p
3556 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3557 $prevtoclevel = $toclevel;
3558 } else {
3559 $toc .= $sk->tocLineEnd();
3560 }
3561 }
3562 }
3563 else {
3564 # No change in level, end TOC line
3565 if( $toclevel<$wgMaxTocLevel ) {
3566 $toc .= $sk->tocLineEnd();
3567 }
3568 }
3569
3570 $levelCount[$toclevel] = $level;
3571
3572 # count number of headlines for each level
3573 @$sublevelCount[$toclevel]++;
3574 $dot = 0;
3575 for( $i = 1; $i <= $toclevel; $i++ ) {
3576 if( !empty( $sublevelCount[$i] ) ) {
3577 if( $dot ) {
3578 $numbering .= '.';
3579 }
3580 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3581 $dot = 1;
3582 }
3583 }
3584 }
3585
3586 # The safe header is a version of the header text safe to use for links
3587 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3588 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3589
3590 # Remove link placeholders by the link text.
3591 # <!--LINK number-->
3592 # turns into
3593 # link text with suffix
3594 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3595
3596 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3597 $tocline = preg_replace(
3598 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3599 array( '', '<$1>'),
3600 $safeHeadline
3601 );
3602 $tocline = trim( $tocline );
3603
3604 # For the anchor, strip out HTML-y stuff period
3605 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3606 $safeHeadline = trim( $safeHeadline );
3607
3608 # Save headline for section edit hint before it's escaped
3609 $headlineHint = $safeHeadline;
3610 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3611 # HTML names must be case-insensitively unique (bug 10721)
3612 $arrayKey = strtolower( $safeHeadline );
3613
3614 # count how many in assoc. array so we can track dupes in anchors
3615 isset( $refers[$arrayKey] ) ? $refers[$arrayKey]++ : $refers[$arrayKey] = 1;
3616 $refcount[$headlineCount] = $refers[$arrayKey];
3617
3618 # Don't number the heading if it is the only one (looks silly)
3619 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3620 # the two are different if the line contains a link
3621 $headline=$numbering . ' ' . $headline;
3622 }
3623
3624 # Create the anchor for linking from the TOC to the section
3625 $anchor = $safeHeadline;
3626 if($refcount[$headlineCount] > 1 ) {
3627 $anchor .= '_' . $refcount[$headlineCount];
3628 }
3629 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3630 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3631 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3632 }
3633 # give headline the correct <h#> tag
3634 if( $showEditLink && $sectionIndex !== false ) {
3635 if( $isTemplate ) {
3636 # Put a T flag in the section identifier, to indicate to extractSections()
3637 # that sections inside <includeonly> should be counted.
3638 $editlink = $sk->doEditSectionLink(Title::newFromText( $titleText ), "T-$sectionIndex");
3639 } else {
3640 $editlink = $sk->doEditSectionLink($this->mTitle, $sectionIndex, $headlineHint);
3641 }
3642 } else {
3643 $editlink = '';
3644 }
3645 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
3646
3647 $headlineCount++;
3648 }
3649
3650 $this->mOutput->setSections( $tocraw );
3651
3652 # Never ever show TOC if no headers
3653 if( $numVisible < 1 ) {
3654 $enoughToc = false;
3655 }
3656
3657 if( $enoughToc ) {
3658 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3659 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3660 }
3661 $toc = $sk->tocList( $toc );
3662 }
3663
3664 # split up and insert constructed headlines
3665
3666 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3667 $i = 0;
3668
3669 foreach( $blocks as $block ) {
3670 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3671 # This is the [edit] link that appears for the top block of text when
3672 # section editing is enabled
3673
3674 # Disabled because it broke block formatting
3675 # For example, a bullet point in the top line
3676 # $full .= $sk->editSectionLink(0);
3677 }
3678 $full .= $block;
3679 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3680 # Top anchor now in skin
3681 $full = $full.$toc;
3682 }
3683
3684 if( !empty( $head[$i] ) ) {
3685 $full .= $head[$i];
3686 }
3687 $i++;
3688 }
3689 if( $this->mForceTocPosition ) {
3690 return str_replace( '<!--MWTOC-->', $toc, $full );
3691 } else {
3692 return $full;
3693 }
3694 }
3695
3696 /**
3697 * Transform wiki markup when saving a page by doing \r\n -> \n
3698 * conversion, substitting signatures, {{subst:}} templates, etc.
3699 *
3700 * @param string $text the text to transform
3701 * @param Title &$title the Title object for the current article
3702 * @param User &$user the User object describing the current user
3703 * @param ParserOptions $options parsing options
3704 * @param bool $clearState whether to clear the parser state first
3705 * @return string the altered wiki markup
3706 * @public
3707 */
3708 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3709 $this->mOptions = $options;
3710 $this->setTitle( $title );
3711 $this->setOutputType( self::OT_WIKI );
3712
3713 if ( $clearState ) {
3714 $this->clearState();
3715 }
3716
3717 $pairs = array(
3718 "\r\n" => "\n",
3719 );
3720 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3721 $text = $this->pstPass2( $text, $user );
3722 $text = $this->mStripState->unstripBoth( $text );
3723 return $text;
3724 }
3725
3726 /**
3727 * Pre-save transform helper function
3728 * @private
3729 */
3730 function pstPass2( $text, $user ) {
3731 global $wgContLang, $wgLocaltimezone;
3732
3733 /* Note: This is the timestamp saved as hardcoded wikitext to
3734 * the database, we use $wgContLang here in order to give
3735 * everyone the same signature and use the default one rather
3736 * than the one selected in each user's preferences.
3737 *
3738 * (see also bug 12815)
3739 */
3740 $ts = $this->mOptions->getTimestamp();
3741 $tz = wfMsgForContent( 'timezone-utc' );
3742 if ( isset( $wgLocaltimezone ) ) {
3743 $unixts = wfTimestamp( TS_UNIX, $ts );
3744 $oldtz = getenv( 'TZ' );
3745 putenv( 'TZ='.$wgLocaltimezone );
3746 $ts = date( 'YmdHis', $unixts );
3747 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3748 putenv( 'TZ='.$oldtz );
3749 }
3750
3751 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3752
3753 # Variable replacement
3754 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3755 $text = $this->replaceVariables( $text );
3756
3757 # Signatures
3758 $sigText = $this->getUserSig( $user );
3759 $text = strtr( $text, array(
3760 '~~~~~' => $d,
3761 '~~~~' => "$sigText $d",
3762 '~~~' => $sigText
3763 ) );
3764
3765 # Context links: [[|name]] and [[name (context)|]]
3766 #
3767 global $wgLegalTitleChars;
3768 $tc = "[$wgLegalTitleChars]";
3769 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3770
3771 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3772 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3773 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3774 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3775
3776 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3777 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3778 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3779 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3780
3781 $t = $this->mTitle->getText();
3782 $m = array();
3783 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3784 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3785 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3786 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3787 } else {
3788 # if there's no context, don't bother duplicating the title
3789 $text = preg_replace( $p2, '[[\\1]]', $text );
3790 }
3791
3792 # Trim trailing whitespace
3793 $text = rtrim( $text );
3794
3795 return $text;
3796 }
3797
3798 /**
3799 * Fetch the user's signature text, if any, and normalize to
3800 * validated, ready-to-insert wikitext.
3801 *
3802 * @param User $user
3803 * @return string
3804 * @private
3805 */
3806 function getUserSig( &$user ) {
3807 global $wgMaxSigChars;
3808
3809 $username = $user->getName();
3810 $nickname = $user->getOption( 'nickname' );
3811 $nickname = $nickname === '' ? $username : $nickname;
3812
3813 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3814 $nickname = $username;
3815 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
3816 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3817 # Sig. might contain markup; validate this
3818 if( $this->validateSig( $nickname ) !== false ) {
3819 # Validated; clean up (if needed) and return it
3820 return $this->cleanSig( $nickname, true );
3821 } else {
3822 # Failed to validate; fall back to the default
3823 $nickname = $username;
3824 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
3825 }
3826 }
3827
3828 // Make sure nickname doesnt get a sig in a sig
3829 $nickname = $this->cleanSigInSig( $nickname );
3830
3831 # If we're still here, make it a link to the user page
3832 $userText = wfEscapeWikiText( $username );
3833 $nickText = wfEscapeWikiText( $nickname );
3834 if ( $user->isAnon() ) {
3835 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3836 } else {
3837 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3838 }
3839 }
3840
3841 /**
3842 * Check that the user's signature contains no bad XML
3843 *
3844 * @param string $text
3845 * @return mixed An expanded string, or false if invalid.
3846 */
3847 function validateSig( $text ) {
3848 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
3849 }
3850
3851 /**
3852 * Clean up signature text
3853 *
3854 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3855 * 2) Substitute all transclusions
3856 *
3857 * @param string $text
3858 * @param $parsing Whether we're cleaning (preferences save) or parsing
3859 * @return string Signature text
3860 */
3861 function cleanSig( $text, $parsing = false ) {
3862 if ( !$parsing ) {
3863 global $wgTitle;
3864 $this->clearState();
3865 $this->setTitle( $wgTitle );
3866 $this->mOptions = new ParserOptions;
3867 $this->setOutputType = self::OT_PREPROCESS;
3868 }
3869
3870 # Option to disable this feature
3871 if ( !$this->mOptions->getCleanSignatures() ) {
3872 return $text;
3873 }
3874
3875 # FIXME: regex doesn't respect extension tags or nowiki
3876 # => Move this logic to braceSubstitution()
3877 $substWord = MagicWord::get( 'subst' );
3878 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3879 $substText = '{{' . $substWord->getSynonym( 0 );
3880
3881 $text = preg_replace( $substRegex, $substText, $text );
3882 $text = $this->cleanSigInSig( $text );
3883 $dom = $this->preprocessToDom( $text );
3884 $frame = $this->getPreprocessor()->newFrame();
3885 $text = $frame->expand( $dom );
3886
3887 if ( !$parsing ) {
3888 $text = $this->mStripState->unstripBoth( $text );
3889 }
3890
3891 return $text;
3892 }
3893
3894 /**
3895 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3896 * @param string $text
3897 * @return string Signature text with /~{3,5}/ removed
3898 */
3899 function cleanSigInSig( $text ) {
3900 $text = preg_replace( '/~{3,5}/', '', $text );
3901 return $text;
3902 }
3903
3904 /**
3905 * Set up some variables which are usually set up in parse()
3906 * so that an external function can call some class members with confidence
3907 * @public
3908 */
3909 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3910 $this->setTitle( $title );
3911 $this->mOptions = $options;
3912 $this->setOutputType( $outputType );
3913 if ( $clearState ) {
3914 $this->clearState();
3915 }
3916 }
3917
3918 /**
3919 * Wrapper for preprocess()
3920 *
3921 * @param string $text the text to preprocess
3922 * @param ParserOptions $options options
3923 * @return string
3924 * @public
3925 */
3926 function transformMsg( $text, $options ) {
3927 global $wgTitle;
3928 static $executing = false;
3929
3930 # Guard against infinite recursion
3931 if ( $executing ) {
3932 return $text;
3933 }
3934 $executing = true;
3935
3936 wfProfileIn(__METHOD__);
3937 $text = $this->preprocess( $text, $wgTitle, $options );
3938
3939 $executing = false;
3940 wfProfileOut(__METHOD__);
3941 return $text;
3942 }
3943
3944 /**
3945 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3946 * The callback should have the following form:
3947 * function myParserHook( $text, $params, &$parser ) { ... }
3948 *
3949 * Transform and return $text. Use $parser for any required context, e.g. use
3950 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3951 *
3952 * @public
3953 *
3954 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3955 * @param mixed $callback The callback function (and object) to use for the tag
3956 *
3957 * @return The old value of the mTagHooks array associated with the hook
3958 */
3959 function setHook( $tag, $callback ) {
3960 $tag = strtolower( $tag );
3961 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
3962 $this->mTagHooks[$tag] = $callback;
3963 if( !in_array( $tag, $this->mStripList ) ) {
3964 $this->mStripList[] = $tag;
3965 }
3966
3967 return $oldVal;
3968 }
3969
3970 function setTransparentTagHook( $tag, $callback ) {
3971 $tag = strtolower( $tag );
3972 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
3973 $this->mTransparentTagHooks[$tag] = $callback;
3974
3975 return $oldVal;
3976 }
3977
3978 /**
3979 * Remove all tag hooks
3980 */
3981 function clearTagHooks() {
3982 $this->mTagHooks = array();
3983 $this->mStripList = $this->mDefaultStripList;
3984 }
3985
3986 /**
3987 * Create a function, e.g. {{sum:1|2|3}}
3988 * The callback function should have the form:
3989 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3990 *
3991 * Or with SFH_OBJECT_ARGS:
3992 * function myParserFunction( $parser, $frame, $args ) { ... }
3993 *
3994 * The callback may either return the text result of the function, or an array with the text
3995 * in element 0, and a number of flags in the other elements. The names of the flags are
3996 * specified in the keys. Valid flags are:
3997 * found The text returned is valid, stop processing the template. This
3998 * is on by default.
3999 * nowiki Wiki markup in the return value should be escaped
4000 * isHTML The returned text is HTML, armour it against wikitext transformation
4001 *
4002 * @public
4003 *
4004 * @param string $id The magic word ID
4005 * @param mixed $callback The callback function (and object) to use
4006 * @param integer $flags a combination of the following flags:
4007 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4008 *
4009 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4010 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4011 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4012 * the arguments, and to control the way they are expanded.
4013 *
4014 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4015 * arguments, for instance:
4016 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4017 *
4018 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4019 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4020 * working if/when this is changed.
4021 *
4022 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4023 * expansion.
4024 *
4025 * Please read the documentation in includes/parser/Preprocessor.php for more information
4026 * about the methods available in PPFrame and PPNode.
4027 *
4028 * @return The old callback function for this name, if any
4029 */
4030 function setFunctionHook( $id, $callback, $flags = 0 ) {
4031 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4032 $this->mFunctionHooks[$id] = array( $callback, $flags );
4033
4034 # Add to function cache
4035 $mw = MagicWord::get( $id );
4036 if( !$mw )
4037 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4038
4039 $synonyms = $mw->getSynonyms();
4040 $sensitive = intval( $mw->isCaseSensitive() );
4041
4042 foreach ( $synonyms as $syn ) {
4043 # Case
4044 if ( !$sensitive ) {
4045 $syn = strtolower( $syn );
4046 }
4047 # Add leading hash
4048 if ( !( $flags & SFH_NO_HASH ) ) {
4049 $syn = '#' . $syn;
4050 }
4051 # Remove trailing colon
4052 if ( substr( $syn, -1, 1 ) === ':' ) {
4053 $syn = substr( $syn, 0, -1 );
4054 }
4055 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4056 }
4057 return $oldVal;
4058 }
4059
4060 /**
4061 * Get all registered function hook identifiers
4062 *
4063 * @return array
4064 */
4065 function getFunctionHooks() {
4066 return array_keys( $this->mFunctionHooks );
4067 }
4068
4069 /**
4070 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4071 * Placeholders created in Skin::makeLinkObj()
4072 * Returns an array of link CSS classes, indexed by PDBK.
4073 */
4074 function replaceLinkHolders( &$text, $options = 0 ) {
4075 return $this->mLinkHolders->replace( $text );
4076 }
4077
4078 /**
4079 * Replace <!--LINK--> link placeholders with plain text of links
4080 * (not HTML-formatted).
4081 * @param string $text
4082 * @return string
4083 */
4084 function replaceLinkHoldersText( $text ) {
4085 return $this->mLinkHolders->replaceText( $text );
4086 }
4087
4088 /**
4089 * Tag hook handler for 'pre'.
4090 */
4091 function renderPreTag( $text, $attribs ) {
4092 // Backwards-compatibility hack
4093 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4094
4095 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4096 return wfOpenElement( 'pre', $attribs ) .
4097 Xml::escapeTagsOnly( $content ) .
4098 '</pre>';
4099 }
4100
4101 /**
4102 * Renders an image gallery from a text with one line per image.
4103 * text labels may be given by using |-style alternative text. E.g.
4104 * Image:one.jpg|The number "1"
4105 * Image:tree.jpg|A tree
4106 * given as text will return the HTML of a gallery with two images,
4107 * labeled 'The number "1"' and
4108 * 'A tree'.
4109 */
4110 function renderImageGallery( $text, $params ) {
4111 $ig = new ImageGallery();
4112 $ig->setContextTitle( $this->mTitle );
4113 $ig->setShowBytes( false );
4114 $ig->setShowFilename( false );
4115 $ig->setParser( $this );
4116 $ig->setHideBadImages();
4117 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4118 $ig->useSkin( $this->mOptions->getSkin() );
4119 $ig->mRevisionId = $this->mRevisionId;
4120
4121 if( isset( $params['caption'] ) ) {
4122 $caption = $params['caption'];
4123 $caption = htmlspecialchars( $caption );
4124 $caption = $this->replaceInternalLinks( $caption );
4125 $ig->setCaptionHtml( $caption );
4126 }
4127 if( isset( $params['perrow'] ) ) {
4128 $ig->setPerRow( $params['perrow'] );
4129 }
4130 if( isset( $params['widths'] ) ) {
4131 $ig->setWidths( $params['widths'] );
4132 }
4133 if( isset( $params['heights'] ) ) {
4134 $ig->setHeights( $params['heights'] );
4135 }
4136
4137 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4138
4139 $lines = StringUtils::explode( "\n", $text );
4140 foreach ( $lines as $line ) {
4141 # match lines like these:
4142 # Image:someimage.jpg|This is some image
4143 $matches = array();
4144 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4145 # Skip empty lines
4146 if ( count( $matches ) == 0 ) {
4147 continue;
4148 }
4149
4150 if ( strpos( $matches[0], '%' ) !== false )
4151 $matches[1] = urldecode( $matches[1] );
4152 $tp = Title::newFromText( $matches[1]/*, NS_IMAGE*/ );
4153 $nt =& $tp;
4154 if( is_null( $nt ) ) {
4155 # Bogus title. Ignore these so we don't bomb out later.
4156 continue;
4157 }
4158 if ( isset( $matches[3] ) ) {
4159 $label = $matches[3];
4160 } else {
4161 $label = '';
4162 }
4163
4164 $html = $this->recursiveTagParse( trim( $label ) );
4165
4166 $ig->add( $nt, $html );
4167
4168 # Only add real images (bug #5586)
4169 if ( $nt->getNamespace() == NS_IMAGE ) {
4170 $this->mOutput->addImage( $nt->getDBkey() );
4171 }
4172 }
4173 return $ig->toHTML();
4174 }
4175
4176 function getImageParams( $handler ) {
4177 if ( $handler ) {
4178 $handlerClass = get_class( $handler );
4179 } else {
4180 $handlerClass = '';
4181 }
4182 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4183 // Initialise static lists
4184 static $internalParamNames = array(
4185 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4186 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4187 'bottom', 'text-bottom' ),
4188 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4189 'upright', 'border' ),
4190 );
4191 static $internalParamMap;
4192 if ( !$internalParamMap ) {
4193 $internalParamMap = array();
4194 foreach ( $internalParamNames as $type => $names ) {
4195 foreach ( $names as $name ) {
4196 $magicName = str_replace( '-', '_', "img_$name" );
4197 $internalParamMap[$magicName] = array( $type, $name );
4198 }
4199 }
4200 }
4201
4202 // Add handler params
4203 $paramMap = $internalParamMap;
4204 if ( $handler ) {
4205 $handlerParamMap = $handler->getParamMap();
4206 foreach ( $handlerParamMap as $magic => $paramName ) {
4207 $paramMap[$magic] = array( 'handler', $paramName );
4208 }
4209 }
4210 $this->mImageParams[$handlerClass] = $paramMap;
4211 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4212 }
4213 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4214 }
4215
4216 /**
4217 * Parse image options text and use it to make an image
4218 * @param Title $title
4219 * @param string $options
4220 * @param LinkHolderArray $holders
4221 */
4222 function makeImage( $title, $options, $holders = false ) {
4223 # Check if the options text is of the form "options|alt text"
4224 # Options are:
4225 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4226 # * left no resizing, just left align. label is used for alt= only
4227 # * right same, but right aligned
4228 # * none same, but not aligned
4229 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4230 # * center center the image
4231 # * framed Keep original image size, no magnify-button.
4232 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4233 # * upright reduce width for upright images, rounded to full __0 px
4234 # * border draw a 1px border around the image
4235 # vertical-align values (no % or length right now):
4236 # * baseline
4237 # * sub
4238 # * super
4239 # * top
4240 # * text-top
4241 # * middle
4242 # * bottom
4243 # * text-bottom
4244
4245 $parts = StringUtils::explode( "|", $options );
4246 $sk = $this->mOptions->getSkin();
4247
4248 # Give extensions a chance to select the file revision for us
4249 $skip = $time = $descQuery = false;
4250 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4251
4252 if ( $skip ) {
4253 return $sk->link( $title );
4254 }
4255
4256 # Get parameter map
4257 $file = wfFindFile( $title, $time );
4258 $handler = $file ? $file->getHandler() : false;
4259
4260 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4261
4262 # Process the input parameters
4263 $caption = '';
4264 $params = array( 'frame' => array(), 'handler' => array(),
4265 'horizAlign' => array(), 'vertAlign' => array() );
4266 foreach( $parts as $part ) {
4267 $part = trim( $part );
4268 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4269 $validated = false;
4270 if( isset( $paramMap[$magicName] ) ) {
4271 list( $type, $paramName ) = $paramMap[$magicName];
4272
4273 // Special case; width and height come in one variable together
4274 if( $type === 'handler' && $paramName === 'width' ) {
4275 $m = array();
4276 # (bug 13500) In both cases (width/height and width only),
4277 # permit trailing "px" for backward compatibility.
4278 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4279 $width = intval( $m[1] );
4280 $height = intval( $m[2] );
4281 if ( $handler->validateParam( 'width', $width ) ) {
4282 $params[$type]['width'] = $width;
4283 $validated = true;
4284 }
4285 if ( $handler->validateParam( 'height', $height ) ) {
4286 $params[$type]['height'] = $height;
4287 $validated = true;
4288 }
4289 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4290 $width = intval( $value );
4291 if ( $handler->validateParam( 'width', $width ) ) {
4292 $params[$type]['width'] = $width;
4293 $validated = true;
4294 }
4295 } // else no validation -- bug 13436
4296 } else {
4297 if ( $type === 'handler' ) {
4298 # Validate handler parameter
4299 $validated = $handler->validateParam( $paramName, $value );
4300 } else {
4301 # Validate internal parameters
4302 switch( $paramName ) {
4303 case "manualthumb":
4304 /// @fixme - possibly check validity here?
4305 /// downstream behavior seems odd with missing manual thumbs.
4306 $validated = true;
4307 break;
4308 default:
4309 // Most other things appear to be empty or numeric...
4310 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4311 }
4312 }
4313
4314 if ( $validated ) {
4315 $params[$type][$paramName] = $value;
4316 }
4317 }
4318 }
4319 if ( !$validated ) {
4320 $caption = $part;
4321 }
4322 }
4323
4324 # Process alignment parameters
4325 if ( $params['horizAlign'] ) {
4326 $params['frame']['align'] = key( $params['horizAlign'] );
4327 }
4328 if ( $params['vertAlign'] ) {
4329 $params['frame']['valign'] = key( $params['vertAlign'] );
4330 }
4331
4332 # Strip bad stuff out of the alt text
4333 # We can't just use replaceLinkHoldersText() here, because if this function
4334 # is called from replaceInternalLinks2(), mLinkHolders won't be up to date.
4335 if ( $holders ) {
4336 $alt = $holders->replaceText( $caption );
4337 } else {
4338 $alt = $this->replaceLinkHoldersText( $caption );
4339 }
4340
4341 # make sure there are no placeholders in thumbnail attributes
4342 # that are later expanded to html- so expand them now and
4343 # remove the tags
4344 $alt = $this->mStripState->unstripBoth( $alt );
4345 $alt = Sanitizer::stripAllTags( $alt );
4346
4347 $params['frame']['alt'] = $alt;
4348 $params['frame']['caption'] = $caption;
4349
4350 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4351
4352 # Linker does the rest
4353 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4354
4355 # Give the handler a chance to modify the parser object
4356 if ( $handler ) {
4357 $handler->parserTransformHook( $this, $file );
4358 }
4359
4360 return $ret;
4361 }
4362
4363 /**
4364 * Set a flag in the output object indicating that the content is dynamic and
4365 * shouldn't be cached.
4366 */
4367 function disableCache() {
4368 wfDebug( "Parser output marked as uncacheable.\n" );
4369 $this->mOutput->mCacheTime = -1;
4370 }
4371
4372 /**#@+
4373 * Callback from the Sanitizer for expanding items found in HTML attribute
4374 * values, so they can be safely tested and escaped.
4375 * @param string $text
4376 * @param PPFrame $frame
4377 * @return string
4378 * @private
4379 */
4380 function attributeStripCallback( &$text, $frame = false ) {
4381 $text = $this->replaceVariables( $text, $frame );
4382 $text = $this->mStripState->unstripBoth( $text );
4383 return $text;
4384 }
4385
4386 /**#@-*/
4387
4388 /**#@+
4389 * Accessor/mutator
4390 */
4391 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4392 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4393 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4394 /**#@-*/
4395
4396 /**#@+
4397 * Accessor
4398 */
4399 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4400 /**#@-*/
4401
4402
4403 /**
4404 * Break wikitext input into sections, and either pull or replace
4405 * some particular section's text.
4406 *
4407 * External callers should use the getSection and replaceSection methods.
4408 *
4409 * @param string $text Page wikitext
4410 * @param string $section A section identifier string of the form:
4411 * <flag1> - <flag2> - ... - <section number>
4412 *
4413 * Currently the only recognised flag is "T", which means the target section number
4414 * was derived during a template inclusion parse, in other words this is a template
4415 * section edit link. If no flags are given, it was an ordinary section edit link.
4416 * This flag is required to avoid a section numbering mismatch when a section is
4417 * enclosed by <includeonly> (bug 6563).
4418 *
4419 * The section number 0 pulls the text before the first heading; other numbers will
4420 * pull the given section along with its lower-level subsections. If the section is
4421 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4422 *
4423 * @param string $mode One of "get" or "replace"
4424 * @param string $newText Replacement text for section data.
4425 * @return string for "get", the extracted section text.
4426 * for "replace", the whole page with the section replaced.
4427 */
4428 private function extractSections( $text, $section, $mode, $newText='' ) {
4429 global $wgTitle;
4430 $this->clearState();
4431 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4432 $this->mOptions = new ParserOptions;
4433 $this->setOutputType( self::OT_WIKI );
4434 $outText = '';
4435 $frame = $this->getPreprocessor()->newFrame();
4436
4437 // Process section extraction flags
4438 $flags = 0;
4439 $sectionParts = explode( '-', $section );
4440 $sectionIndex = array_pop( $sectionParts );
4441 foreach ( $sectionParts as $part ) {
4442 if ( $part === 'T' ) {
4443 $flags |= self::PTD_FOR_INCLUSION;
4444 }
4445 }
4446 // Preprocess the text
4447 $root = $this->preprocessToDom( $text, $flags );
4448
4449 // <h> nodes indicate section breaks
4450 // They can only occur at the top level, so we can find them by iterating the root's children
4451 $node = $root->getFirstChild();
4452
4453 // Find the target section
4454 if ( $sectionIndex == 0 ) {
4455 // Section zero doesn't nest, level=big
4456 $targetLevel = 1000;
4457 } else {
4458 while ( $node ) {
4459 if ( $node->getName() === 'h' ) {
4460 $bits = $node->splitHeading();
4461 if ( $bits['i'] == $sectionIndex ) {
4462 $targetLevel = $bits['level'];
4463 break;
4464 }
4465 }
4466 if ( $mode === 'replace' ) {
4467 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4468 }
4469 $node = $node->getNextSibling();
4470 }
4471 }
4472
4473 if ( !$node ) {
4474 // Not found
4475 if ( $mode === 'get' ) {
4476 return $newText;
4477 } else {
4478 return $text;
4479 }
4480 }
4481
4482 // Find the end of the section, including nested sections
4483 do {
4484 if ( $node->getName() === 'h' ) {
4485 $bits = $node->splitHeading();
4486 $curLevel = $bits['level'];
4487 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4488 break;
4489 }
4490 }
4491 if ( $mode === 'get' ) {
4492 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4493 }
4494 $node = $node->getNextSibling();
4495 } while ( $node );
4496
4497 // Write out the remainder (in replace mode only)
4498 if ( $mode === 'replace' ) {
4499 // Output the replacement text
4500 // Add two newlines on -- trailing whitespace in $newText is conventionally
4501 // stripped by the editor, so we need both newlines to restore the paragraph gap
4502 $outText .= $newText . "\n\n";
4503 while ( $node ) {
4504 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4505 $node = $node->getNextSibling();
4506 }
4507 }
4508
4509 if ( is_string( $outText ) ) {
4510 // Re-insert stripped tags
4511 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4512 }
4513
4514 return $outText;
4515 }
4516
4517 /**
4518 * This function returns the text of a section, specified by a number ($section).
4519 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4520 * the first section before any such heading (section 0).
4521 *
4522 * If a section contains subsections, these are also returned.
4523 *
4524 * @param string $text text to look in
4525 * @param string $section section identifier
4526 * @param string $deftext default to return if section is not found
4527 * @return string text of the requested section
4528 */
4529 public function getSection( $text, $section, $deftext='' ) {
4530 return $this->extractSections( $text, $section, "get", $deftext );
4531 }
4532
4533 public function replaceSection( $oldtext, $section, $text ) {
4534 return $this->extractSections( $oldtext, $section, "replace", $text );
4535 }
4536
4537 /**
4538 * Get the timestamp associated with the current revision, adjusted for
4539 * the default server-local timestamp
4540 */
4541 function getRevisionTimestamp() {
4542 if ( is_null( $this->mRevisionTimestamp ) ) {
4543 wfProfileIn( __METHOD__ );
4544 global $wgContLang;
4545 $dbr = wfGetDB( DB_SLAVE );
4546 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4547 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4548
4549 // Normalize timestamp to internal MW format for timezone processing.
4550 // This has the added side-effect of replacing a null value with
4551 // the current time, which gives us more sensible behavior for
4552 // previews.
4553 $timestamp = wfTimestamp( TS_MW, $timestamp );
4554
4555 // The cryptic '' timezone parameter tells to use the site-default
4556 // timezone offset instead of the user settings.
4557 //
4558 // Since this value will be saved into the parser cache, served
4559 // to other users, and potentially even used inside links and such,
4560 // it needs to be consistent for all visitors.
4561 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4562
4563 wfProfileOut( __METHOD__ );
4564 }
4565 return $this->mRevisionTimestamp;
4566 }
4567
4568 /**
4569 * Mutator for $mDefaultSort
4570 *
4571 * @param $sort New value
4572 */
4573 public function setDefaultSort( $sort ) {
4574 $this->mDefaultSort = $sort;
4575 }
4576
4577 /**
4578 * Accessor for $mDefaultSort
4579 * Will use the title/prefixed title if none is set
4580 *
4581 * @return string
4582 */
4583 public function getDefaultSort() {
4584 global $wgCategoryPrefixedDefaultSortkey;
4585 if( $this->mDefaultSort !== false ) {
4586 return $this->mDefaultSort;
4587 } elseif ($this->mTitle->getNamespace() == NS_CATEGORY ||
4588 !$wgCategoryPrefixedDefaultSortkey) {
4589 return $this->mTitle->getText();
4590 } else {
4591 return $this->mTitle->getPrefixedText();
4592 }
4593 }
4594
4595 /**
4596 * Try to guess the section anchor name based on a wikitext fragment
4597 * presumably extracted from a heading, for example "Header" from
4598 * "== Header ==".
4599 */
4600 public function guessSectionNameFromWikiText( $text ) {
4601 # Strip out wikitext links(they break the anchor)
4602 $text = $this->stripSectionName( $text );
4603 $headline = Sanitizer::decodeCharReferences( $text );
4604 # strip out HTML
4605 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
4606 $headline = trim( $headline );
4607 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4608 $replacearray = array(
4609 '%3A' => ':',
4610 '%' => '.'
4611 );
4612 return str_replace(
4613 array_keys( $replacearray ),
4614 array_values( $replacearray ),
4615 $sectionanchor );
4616 }
4617
4618 /**
4619 * Strips a text string of wikitext for use in a section anchor
4620 *
4621 * Accepts a text string and then removes all wikitext from the
4622 * string and leaves only the resultant text (i.e. the result of
4623 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4624 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4625 * to create valid section anchors by mimicing the output of the
4626 * parser when headings are parsed.
4627 *
4628 * @param $text string Text string to be stripped of wikitext
4629 * for use in a Section anchor
4630 * @return Filtered text string
4631 */
4632 public function stripSectionName( $text ) {
4633 # Strip internal link markup
4634 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4635 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4636
4637 # Strip external link markup (FIXME: Not Tolerant to blank link text
4638 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4639 # on how many empty links there are on the page - need to figure that out.
4640 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4641
4642 # Parse wikitext quotes (italics & bold)
4643 $text = $this->doQuotes($text);
4644
4645 # Strip HTML tags
4646 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
4647 return $text;
4648 }
4649
4650 function srvus( $text ) {
4651 return $this->testSrvus( $text, $this->mOutputType );
4652 }
4653
4654 /**
4655 * strip/replaceVariables/unstrip for preprocessor regression testing
4656 */
4657 function testSrvus( $text, $title, $options, $outputType = self::OT_HTML ) {
4658 $this->clearState();
4659 if ( ! ( $title instanceof Title ) ) {
4660 $title = Title::newFromText( $title );
4661 }
4662 $this->mTitle = $title;
4663 $this->mOptions = $options;
4664 $this->setOutputType( $outputType );
4665 $text = $this->replaceVariables( $text );
4666 $text = $this->mStripState->unstripBoth( $text );
4667 $text = Sanitizer::removeHTMLtags( $text );
4668 return $text;
4669 }
4670
4671 function testPst( $text, $title, $options ) {
4672 global $wgUser;
4673 if ( ! ( $title instanceof Title ) ) {
4674 $title = Title::newFromText( $title );
4675 }
4676 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4677 }
4678
4679 function testPreprocess( $text, $title, $options ) {
4680 if ( ! ( $title instanceof Title ) ) {
4681 $title = Title::newFromText( $title );
4682 }
4683 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
4684 }
4685
4686 function markerSkipCallback( $s, $callback ) {
4687 $i = 0;
4688 $out = '';
4689 while ( $i < strlen( $s ) ) {
4690 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
4691 if ( $markerStart === false ) {
4692 $out .= call_user_func( $callback, substr( $s, $i ) );
4693 break;
4694 } else {
4695 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4696 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
4697 if ( $markerEnd === false ) {
4698 $out .= substr( $s, $markerStart );
4699 break;
4700 } else {
4701 $markerEnd += strlen( self::MARKER_SUFFIX );
4702 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4703 $i = $markerEnd;
4704 }
4705 }
4706 }
4707 return $out;
4708 }
4709 }
4710
4711 /**
4712 * @todo document, briefly.
4713 * @ingroup Parser
4714 */
4715 class StripState {
4716 var $general, $nowiki;
4717
4718 function __construct() {
4719 $this->general = new ReplacementArray;
4720 $this->nowiki = new ReplacementArray;
4721 }
4722
4723 function unstripGeneral( $text ) {
4724 wfProfileIn( __METHOD__ );
4725 do {
4726 $oldText = $text;
4727 $text = $this->general->replace( $text );
4728 } while ( $text !== $oldText );
4729 wfProfileOut( __METHOD__ );
4730 return $text;
4731 }
4732
4733 function unstripNoWiki( $text ) {
4734 wfProfileIn( __METHOD__ );
4735 do {
4736 $oldText = $text;
4737 $text = $this->nowiki->replace( $text );
4738 } while ( $text !== $oldText );
4739 wfProfileOut( __METHOD__ );
4740 return $text;
4741 }
4742
4743 function unstripBoth( $text ) {
4744 wfProfileIn( __METHOD__ );
4745 do {
4746 $oldText = $text;
4747 $text = $this->general->replace( $text );
4748 $text = $this->nowiki->replace( $text );
4749 } while ( $text !== $oldText );
4750 wfProfileOut( __METHOD__ );
4751 return $text;
4752 }
4753 }
4754
4755 /**
4756 * @todo document, briefly.
4757 * @ingroup Parser
4758 */
4759 class OnlyIncludeReplacer {
4760 var $output = '';
4761
4762 function replace( $matches ) {
4763 if ( substr( $matches[1], -1 ) === "\n" ) {
4764 $this->output .= substr( $matches[1], 0, -1 );
4765 } else {
4766 $this->output .= $matches[1];
4767 }
4768 }
4769 }