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