Fix for bug 2319, accidentally reverted in last checkin
[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 require_once( 'Sanitizer.php' );
11
12 /**
13 * Update this version number when the ParserOutput format
14 * changes in an incompatible way, so the parser cache
15 * can automatically discard old data.
16 */
17 define( 'MW_PARSER_VERSION', '1.5.0' );
18
19 /**
20 * Variable substitution O(N^2) attack
21 *
22 * Without countermeasures, it would be possible to attack the parser by saving
23 * a page filled with a large number of inclusions of large pages. The size of
24 * the generated page would be proportional to the square of the input size.
25 * Hence, we limit the number of inclusions of any given page, thus bringing any
26 * attack back to O(N).
27 */
28
29 define( 'MAX_INCLUDE_REPEAT', 100 );
30 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
31
32 define( 'RLH_FOR_UPDATE', 1 );
33
34 # Allowed values for $mOutputType
35 define( 'OT_HTML', 1 );
36 define( 'OT_WIKI', 2 );
37 define( 'OT_MSG' , 3 );
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 # prefix for escaping, used in two functions at least
46 define( 'UNIQ_PREFIX', 'NaodW29');
47
48 # Constants needed for external link processing
49 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
50 define( 'HTTP_PROTOCOLS', 'http|https' );
51 # Everything except bracket, space, or control characters
52 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
53 # Including space
54 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
55 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
56 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
57 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS.'):'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
58 define( 'EXT_IMAGE_REGEX',
59 '/^('.HTTP_PROTOCOLS.':)'. # Protocol
60 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
61 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
62 );
63
64 /**
65 * PHP Parser
66 *
67 * Processes wiki markup
68 *
69 * <pre>
70 * There are three main entry points into the Parser class:
71 * parse()
72 * produces HTML output
73 * preSaveTransform().
74 * produces altered wiki markup.
75 * transformMsg()
76 * performs brace substitution on MediaWiki messages
77 *
78 * Globals used:
79 * objects: $wgLang, $wgLinkCache
80 *
81 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
82 *
83 * settings:
84 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
85 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
86 * $wgLocaltimezone, $wgAllowSpecialInclusion*
87 *
88 * * only within ParserOptions
89 * </pre>
90 *
91 * @package MediaWiki
92 */
93 class Parser
94 {
95 /**#@+
96 * @access private
97 */
98 # Persistent:
99 var $mTagHooks;
100
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
103 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mInterwikiLinkHolders, $mLinkHolders;
105
106 # Temporary:
107 var $mOptions, $mTitle, $mOutputType,
108 $mTemplates, // cache of already loaded templates, avoids
109 // multiple SQL queries for the same string
110 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
111 // in this path. Used for loop detection.
112
113 /**#@-*/
114
115 /**
116 * Constructor
117 *
118 * @access public
119 */
120 function Parser() {
121 global $wgContLang;
122 $this->mTemplates = array();
123 $this->mTemplatePath = array();
124 $this->mTagHooks = array();
125 $this->clearState();
126 }
127
128 /**
129 * Clear Parser state
130 *
131 * @access private
132 */
133 function clearState() {
134 $this->mOutput = new ParserOutput;
135 $this->mAutonumber = 0;
136 $this->mLastSection = '';
137 $this->mDTopen = false;
138 $this->mVariables = false;
139 $this->mIncludeCount = array();
140 $this->mStripState = array();
141 $this->mArgStack = array();
142 $this->mInPre = false;
143 $this->mInterwikiLinkHolders = array(
144 'texts' => array(),
145 'titles' => array()
146 );
147 $this->mLinkHolders = array(
148 'namespaces' => array(),
149 'dbkeys' => array(),
150 'queries' => array(),
151 'texts' => array(),
152 'titles' => array()
153 );
154 }
155
156 /**
157 * First pass--just handle <nowiki> sections, pass the rest off
158 * to internalParse() which does all the real work.
159 *
160 * @access private
161 * @param string $text Text we want to parse
162 * @param Title &$title A title object
163 * @param array $options
164 * @param boolean $linestart
165 * @param boolean $clearState
166 * @return ParserOutput a ParserOutput
167 */
168 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
169 global $wgUseTidy, $wgContLang;
170 $fname = 'Parser::parse';
171 wfProfileIn( $fname );
172
173 if ( $clearState ) {
174 $this->clearState();
175 }
176
177 $this->mOptions = $options;
178 $this->mTitle =& $title;
179 $this->mOutputType = OT_HTML;
180
181 $this->mStripState = NULL;
182
183 //$text = $this->strip( $text, $this->mStripState );
184 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
185 $x =& $this->mStripState;
186 $text = $this->strip( $text, $x );
187
188 $text = $this->internalParse( $text );
189
190
191 $text = $this->unstrip( $text, $this->mStripState );
192
193 # Clean up special characters, only run once, next-to-last before doBlockLevels
194 $fixtags = array(
195 # french spaces, last one Guillemet-left
196 # only if there is something before the space
197 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
198 # french spaces, Guillemet-right
199 '/(\\302\\253) /' => '\\1&nbsp;',
200 '/<center *>/i' => '<div class="center">',
201 '/<\\/center *>/i' => '</div>',
202 );
203 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
204
205 # only once and last
206 $text = $this->doBlockLevels( $text, $linestart );
207
208 $this->replaceLinkHolders( $text );
209
210 $dashReplace = array(
211 '/ - /' => "&nbsp;&ndash; ", # N dash
212 '/(?<=[\d])-(?=[\d])/' => "&ndash;", # N dash between numbers
213 '/ -- /' => "&nbsp;&mdash; " # M dash
214 );
215 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
216
217 # the position of the convert() call should not be changed. it
218 # assumes that the links are all replaces and the only thing left
219 # is the <nowiki> mark.
220 $text = $wgContLang->convert($text);
221 $this->mOutput->setTitleText($wgContLang->getParsedTitle());
222
223 $text = $this->unstripNoWiki( $text, $this->mStripState );
224
225 $text = Sanitizer::normalizeCharReferences( $text );
226 global $wgUseTidy;
227 if ($wgUseTidy) {
228 $text = Parser::tidy($text);
229 }
230
231 $this->mOutput->setText( $text );
232 wfProfileOut( $fname );
233 return $this->mOutput;
234 }
235
236 /**
237 * Get a random string
238 *
239 * @access private
240 * @static
241 */
242 function getRandomString() {
243 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
244 }
245
246 /**
247 * Replaces all occurrences of <$tag>content</$tag> in the text
248 * with a random marker and returns the new text. the output parameter
249 * $content will be an associative array filled with data on the form
250 * $unique_marker => content.
251 *
252 * If $content is already set, the additional entries will be appended
253 * If $tag is set to STRIP_COMMENTS, the function will extract
254 * <!-- HTML comments -->
255 *
256 * @access private
257 * @static
258 */
259 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
260 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
261 if ( !$content ) {
262 $content = array( );
263 }
264 $n = 1;
265 $stripped = '';
266
267 if ( !$tags ) {
268 $tags = array( );
269 }
270
271 if ( !$params ) {
272 $params = array( );
273 }
274
275 if( $tag == STRIP_COMMENTS ) {
276 $start = '/<!--()/';
277 $end = '/-->/';
278 } else {
279 $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
280 $end = "/<\\/$tag\\s*>/i";
281 }
282
283 while ( '' != $text ) {
284 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
285 $stripped .= $p[0];
286 if( count( $p ) < 3 ) {
287 break;
288 }
289 $attributes = $p[1];
290 $inside = $p[2];
291
292 $marker = $rnd . sprintf('%08X', $n++);
293 $stripped .= $marker;
294
295 $tags[$marker] = "<$tag$attributes>";
296 $params[$marker] = Sanitizer::decodeTagAttributes( $attributes );
297
298 $q = preg_split( $end, $inside, 2 );
299 $content[$marker] = $q[0];
300 if( count( $q ) < 1 ) {
301 # No end tag -- let it run out to the end of the text.
302 break;
303 } else {
304 $text = $q[1];
305 }
306 }
307 return $stripped;
308 }
309
310 /**
311 * Wrapper function for extractTagsAndParams
312 * for cases where $tags and $params isn't needed
313 * i.e. where tags will never have params, like <nowiki>
314 *
315 * @access private
316 * @static
317 */
318 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
319 $dummy_tags = array();
320 $dummy_params = array();
321
322 return Parser::extractTagsAndParams( $tag, $text, $content,
323 $dummy_tags, $dummy_params, $uniq_prefix );
324 }
325
326 /**
327 * Strips and renders nowiki, pre, math, hiero
328 * If $render is set, performs necessary rendering operations on plugins
329 * Returns the text, and fills an array with data needed in unstrip()
330 * If the $state is already a valid strip state, it adds to the state
331 *
332 * @param bool $stripcomments when set, HTML comments <!-- like this -->
333 * will be stripped in addition to other tags. This is important
334 * for section editing, where these comments cause confusion when
335 * counting the sections in the wikisource
336 *
337 * @access private
338 */
339 function strip( $text, &$state, $stripcomments = false ) {
340 $render = ($this->mOutputType == OT_HTML);
341 $html_content = array();
342 $nowiki_content = array();
343 $math_content = array();
344 $pre_content = array();
345 $comment_content = array();
346 $ext_content = array();
347 $ext_tags = array();
348 $ext_params = array();
349 $gallery_content = array();
350
351 # Replace any instances of the placeholders
352 $uniq_prefix = UNIQ_PREFIX;
353 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
354
355 # html
356 global $wgRawHtml, $wgWhitelistEdit;
357 if( $wgRawHtml && $wgWhitelistEdit ) {
358 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
359 foreach( $html_content as $marker => $content ) {
360 if ($render ) {
361 # Raw and unchecked for validity.
362 $html_content[$marker] = $content;
363 } else {
364 $html_content[$marker] = '<html>'.$content.'</html>';
365 }
366 }
367 }
368
369 # nowiki
370 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
371 foreach( $nowiki_content as $marker => $content ) {
372 if( $render ){
373 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
374 } else {
375 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
376 }
377 }
378
379 # math
380 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
381 foreach( $math_content as $marker => $content ){
382 if( $render ) {
383 if( $this->mOptions->getUseTeX() ) {
384 $math_content[$marker] = renderMath( $content );
385 } else {
386 $math_content[$marker] = '&lt;math&gt;'.$content.'&lt;math&gt;';
387 }
388 } else {
389 $math_content[$marker] = '<math>'.$content.'</math>';
390 }
391 }
392
393 # pre
394 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
395 foreach( $pre_content as $marker => $content ){
396 if( $render ){
397 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
398 } else {
399 $pre_content[$marker] = '<pre>'.$content.'</pre>';
400 }
401 }
402
403 # gallery
404 $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
405 foreach( $gallery_content as $marker => $content ) {
406 require_once( 'ImageGallery.php' );
407 if ( $render ) {
408 $gallery_content[$marker] = Parser::renderImageGallery( $content );
409 } else {
410 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
411 }
412 }
413
414 # Comments
415 if($stripcomments) {
416 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
417 foreach( $comment_content as $marker => $content ){
418 $comment_content[$marker] = '<!--'.$content.'-->';
419 }
420 }
421
422 # Extensions
423 foreach ( $this->mTagHooks as $tag => $callback ) {
424 $ext_content[$tag] = array();
425 $text = Parser::extractTagsAndParams( $tag, $text, $ext_content[$tag],
426 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
427 foreach( $ext_content[$tag] as $marker => $content ) {
428 $full_tag = $ext_tags[$tag][$marker];
429 $params = $ext_params[$tag][$marker];
430 if ( $render ) {
431 $ext_content[$tag][$marker] = $callback( $content, $params );
432 } else {
433 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
434 }
435 }
436 }
437
438 # Merge state with the pre-existing state, if there is one
439 if ( $state ) {
440 $state['html'] = $state['html'] + $html_content;
441 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
442 $state['math'] = $state['math'] + $math_content;
443 $state['pre'] = $state['pre'] + $pre_content;
444 $state['comment'] = $state['comment'] + $comment_content;
445 $state['gallery'] = $state['gallery'] + $gallery_content;
446
447 foreach( $ext_content as $tag => $array ) {
448 if ( array_key_exists( $tag, $state ) ) {
449 $state[$tag] = $state[$tag] + $array;
450 }
451 }
452 } else {
453 $state = array(
454 'html' => $html_content,
455 'nowiki' => $nowiki_content,
456 'math' => $math_content,
457 'pre' => $pre_content,
458 'comment' => $comment_content,
459 'gallery' => $gallery_content,
460 ) + $ext_content;
461 }
462 return $text;
463 }
464
465 /**
466 * restores pre, math, and hiero removed by strip()
467 *
468 * always call unstripNoWiki() after this one
469 * @access private
470 */
471 function unstrip( $text, &$state ) {
472 # Must expand in reverse order, otherwise nested tags will be corrupted
473 $contentDict = end( $state );
474 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
475 if( key($state) != 'nowiki' && key($state) != 'html') {
476 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
477 $text = str_replace( key( $contentDict ), $content, $text );
478 }
479 }
480 }
481
482 return $text;
483 }
484
485 /**
486 * always call this after unstrip() to preserve the order
487 *
488 * @access private
489 */
490 function unstripNoWiki( $text, &$state ) {
491 # Must expand in reverse order, otherwise nested tags will be corrupted
492 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
493 $text = str_replace( key( $state['nowiki'] ), $content, $text );
494 }
495
496 global $wgRawHtml;
497 if ($wgRawHtml) {
498 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
499 $text = str_replace( key( $state['html'] ), $content, $text );
500 }
501 }
502
503 return $text;
504 }
505
506 /**
507 * Add an item to the strip state
508 * Returns the unique tag which must be inserted into the stripped text
509 * The tag will be replaced with the original text in unstrip()
510 *
511 * @access private
512 */
513 function insertStripItem( $text, &$state ) {
514 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
515 if ( !$state ) {
516 $state = array(
517 'html' => array(),
518 'nowiki' => array(),
519 'math' => array(),
520 'pre' => array()
521 );
522 }
523 $state['item'][$rnd] = $text;
524 return $rnd;
525 }
526
527 /**
528 * Interface with html tidy, used if $wgUseTidy = true.
529 * If tidy isn't able to correct the markup, the original will be
530 * returned in all its glory with a warning comment appended.
531 *
532 * Either the external tidy program or the in-process tidy extension
533 * will be used depending on availability. Override the default
534 * $wgTidyInternal setting to disable the internal if it's not working.
535 *
536 * @param string $text Hideous HTML input
537 * @return string Corrected HTML output
538 * @access public
539 * @static
540 */
541 function tidy( $text ) {
542 global $wgTidyInternal;
543 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
544 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
545 '<head><title>test</title></head><body>'.$text.'</body></html>';
546 if( $wgTidyInternal ) {
547 $correctedtext = Parser::internalTidy( $wrappedtext );
548 } else {
549 $correctedtext = Parser::externalTidy( $wrappedtext );
550 }
551 if( is_null( $correctedtext ) ) {
552 wfDebug( "Tidy error detected!\n" );
553 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
554 }
555 return $correctedtext;
556 }
557
558 /**
559 * Spawn an external HTML tidy process and get corrected markup back from it.
560 *
561 * @access private
562 * @static
563 */
564 function externalTidy( $text ) {
565 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
566 $fname = 'Parser::externalTidy';
567 wfProfileIn( $fname );
568
569 $cleansource = '';
570 $opts = ' -utf8';
571
572 $descriptorspec = array(
573 0 => array('pipe', 'r'),
574 1 => array('pipe', 'w'),
575 2 => array('file', '/dev/null', 'a')
576 );
577 $pipes = array();
578 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
579 if (is_resource($process)) {
580 fwrite($pipes[0], $text);
581 fclose($pipes[0]);
582 while (!feof($pipes[1])) {
583 $cleansource .= fgets($pipes[1], 1024);
584 }
585 fclose($pipes[1]);
586 proc_close($process);
587 }
588
589 wfProfileOut( $fname );
590
591 if( $cleansource == '' && $text != '') {
592 // Some kind of error happened, so we couldn't get the corrected text.
593 // Just give up; we'll use the source text and append a warning.
594 return null;
595 } else {
596 return $cleansource;
597 }
598 }
599
600 /**
601 * Use the HTML tidy PECL extension to use the tidy library in-process,
602 * saving the overhead of spawning a new process. Currently written to
603 * the PHP 4.3.x version of the extension, may not work on PHP 5.
604 *
605 * 'pear install tidy' should be able to compile the extension module.
606 *
607 * @access private
608 * @static
609 */
610 function internalTidy( $text ) {
611 global $wgTidyConf;
612 $fname = 'Parser::internalTidy';
613 wfProfileIn( $fname );
614
615 tidy_load_config( $wgTidyConf );
616 tidy_set_encoding( 'utf8' );
617 tidy_parse_string( $text );
618 tidy_clean_repair();
619 if( tidy_get_status() == 2 ) {
620 // 2 is magic number for fatal error
621 // http://www.php.net/manual/en/function.tidy-get-status.php
622 $cleansource = null;
623 } else {
624 $cleansource = tidy_get_output();
625 }
626 wfProfileOut( $fname );
627 return $cleansource;
628 }
629
630 /**
631 * parse the wiki syntax used to render tables
632 *
633 * @access private
634 */
635 function doTableStuff ( $t ) {
636 $fname = 'Parser::doTableStuff';
637 wfProfileIn( $fname );
638
639 $t = explode ( "\n" , $t ) ;
640 $td = array () ; # Is currently a td tag open?
641 $ltd = array () ; # Was it TD or TH?
642 $tr = array () ; # Is currently a tr tag open?
643 $ltr = array () ; # tr attributes
644 $indent_level = 0; # indent level of the table
645 foreach ( $t AS $k => $x )
646 {
647 $x = trim ( $x ) ;
648 $fc = substr ( $x , 0 , 1 ) ;
649 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
650 $indent_level = strlen( $matches[1] );
651 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
652 '<table' . Sanitizer::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
653 array_push ( $td , false ) ;
654 array_push ( $ltd , '' ) ;
655 array_push ( $tr , false ) ;
656 array_push ( $ltr , '' ) ;
657 }
658 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
659 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
660 $z = "</table>" . substr ( $x , 2);
661 $l = array_pop ( $ltd ) ;
662 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
663 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
664 array_pop ( $ltr ) ;
665 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
666 }
667 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
668 $x = substr ( $x , 1 ) ;
669 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
670 $z = '' ;
671 $l = array_pop ( $ltd ) ;
672 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
673 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
674 array_pop ( $ltr ) ;
675 $t[$k] = $z ;
676 array_push ( $tr , false ) ;
677 array_push ( $td , false ) ;
678 array_push ( $ltd , '' ) ;
679 array_push ( $ltr , Sanitizer::fixTagAttributes ( $x, 'tr' ) ) ;
680 }
681 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
682 # $x is a table row
683 if ( '|+' == substr ( $x , 0 , 2 ) ) {
684 $fc = '+' ;
685 $x = substr ( $x , 1 ) ;
686 }
687 $after = substr ( $x , 1 ) ;
688 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
689 $after = explode ( '||' , $after ) ;
690 $t[$k] = '' ;
691
692 # Loop through each table cell
693 foreach ( $after AS $theline )
694 {
695 $z = '' ;
696 if ( $fc != '+' )
697 {
698 $tra = array_pop ( $ltr ) ;
699 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
700 array_push ( $tr , true ) ;
701 array_push ( $ltr , '' ) ;
702 }
703
704 $l = array_pop ( $ltd ) ;
705 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
706 if ( $fc == '|' ) $l = 'td' ;
707 else if ( $fc == '!' ) $l = 'th' ;
708 else if ( $fc == '+' ) $l = 'caption' ;
709 else $l = '' ;
710 array_push ( $ltd , $l ) ;
711
712 # Cell parameters
713 $y = explode ( '|' , $theline , 2 ) ;
714 # Note that a '|' inside an invalid link should not
715 # be mistaken as delimiting cell parameters
716 if ( strpos( $y[0], '[[' ) !== false ) {
717 $y = array ($theline);
718 }
719 if ( count ( $y ) == 1 )
720 $y = "{$z}<{$l}>{$y[0]}" ;
721 else $y = $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($y[0], $l).">{$y[1]}" ;
722 $t[$k] .= $y ;
723 array_push ( $td , true ) ;
724 }
725 }
726 }
727
728 # Closing open td, tr && table
729 while ( count ( $td ) > 0 )
730 {
731 if ( array_pop ( $td ) ) $t[] = '</td>' ;
732 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
733 $t[] = '</table>' ;
734 }
735
736 $t = implode ( "\n" , $t ) ;
737 wfProfileOut( $fname );
738 return $t ;
739 }
740
741 /**
742 * Helper function for parse() that transforms wiki markup into
743 * HTML. Only called for $mOutputType == OT_HTML.
744 *
745 * @access private
746 */
747 function internalParse( $text ) {
748 global $wgContLang;
749 $args = array();
750 $isMain = true;
751 $fname = 'Parser::internalParse';
752 wfProfileIn( $fname );
753
754 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ) );
755 $text = $this->replaceVariables( $text, $args );
756
757 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
758
759 $text = $this->doHeadings( $text );
760 if($this->mOptions->getUseDynamicDates()) {
761 $df =& DateFormatter::getInstance();
762 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
763 }
764 $text = $this->doAllQuotes( $text );
765 $text = $this->replaceInternalLinks( $text );
766 $text = $this->replaceExternalLinks( $text );
767
768 # replaceInternalLinks may sometimes leave behind
769 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
770 $text = str_replace("http-noparse://","http://",$text);
771
772 $text = $this->doMagicLinks( $text );
773 $text = $this->doTableStuff( $text );
774 $text = $this->formatHeadings( $text, $isMain );
775
776 wfProfileOut( $fname );
777 return $text;
778 }
779
780 /**
781 * Replace special strings like "ISBN xxx" and "RFC xxx" with
782 * magic external links.
783 *
784 * @access private
785 */
786 function &doMagicLinks( &$text ) {
787 $text = $this->magicISBN( $text );
788 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
789 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
790 return $text;
791 }
792
793 /**
794 * Parse ^^ tokens and return html
795 *
796 * @access private
797 */
798 function doExponent( $text ) {
799 $fname = 'Parser::doExponent';
800 wfProfileIn( $fname );
801 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
802 wfProfileOut( $fname );
803 return $text;
804 }
805
806 /**
807 * Parse headers and return html
808 *
809 * @access private
810 */
811 function doHeadings( $text ) {
812 $fname = 'Parser::doHeadings';
813 wfProfileIn( $fname );
814 for ( $i = 6; $i >= 1; --$i ) {
815 $h = substr( '======', 0, $i );
816 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
817 "<h{$i}>\\1</h{$i}>\\2", $text );
818 }
819 wfProfileOut( $fname );
820 return $text;
821 }
822
823 /**
824 * Replace single quotes with HTML markup
825 * @access private
826 * @return string the altered text
827 */
828 function doAllQuotes( $text ) {
829 $fname = 'Parser::doAllQuotes';
830 wfProfileIn( $fname );
831 $outtext = '';
832 $lines = explode( "\n", $text );
833 foreach ( $lines as $line ) {
834 $outtext .= $this->doQuotes ( $line ) . "\n";
835 }
836 $outtext = substr($outtext, 0,-1);
837 wfProfileOut( $fname );
838 return $outtext;
839 }
840
841 /**
842 * Helper function for doAllQuotes()
843 * @access private
844 */
845 function doQuotes( $text ) {
846 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
847 if ( count( $arr ) == 1 )
848 return $text;
849 else
850 {
851 # First, do some preliminary work. This may shift some apostrophes from
852 # being mark-up to being text. It also counts the number of occurrences
853 # of bold and italics mark-ups.
854 $i = 0;
855 $numbold = 0;
856 $numitalics = 0;
857 foreach ( $arr as $r )
858 {
859 if ( ( $i % 2 ) == 1 )
860 {
861 # If there are ever four apostrophes, assume the first is supposed to
862 # be text, and the remaining three constitute mark-up for bold text.
863 if ( strlen( $arr[$i] ) == 4 )
864 {
865 $arr[$i-1] .= "'";
866 $arr[$i] = "'''";
867 }
868 # If there are more than 5 apostrophes in a row, assume they're all
869 # text except for the last 5.
870 else if ( strlen( $arr[$i] ) > 5 )
871 {
872 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
873 $arr[$i] = "'''''";
874 }
875 # Count the number of occurrences of bold and italics mark-ups.
876 # We are not counting sequences of five apostrophes.
877 if ( strlen( $arr[$i] ) == 2 ) $numitalics++; else
878 if ( strlen( $arr[$i] ) == 3 ) $numbold++; else
879 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
880 }
881 $i++;
882 }
883
884 # If there is an odd number of both bold and italics, it is likely
885 # that one of the bold ones was meant to be an apostrophe followed
886 # by italics. Which one we cannot know for certain, but it is more
887 # likely to be one that has a single-letter word before it.
888 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
889 {
890 $i = 0;
891 $firstsingleletterword = -1;
892 $firstmultiletterword = -1;
893 $firstspace = -1;
894 foreach ( $arr as $r )
895 {
896 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
897 {
898 $x1 = substr ($arr[$i-1], -1);
899 $x2 = substr ($arr[$i-1], -2, 1);
900 if ($x1 == ' ') {
901 if ($firstspace == -1) $firstspace = $i;
902 } else if ($x2 == ' ') {
903 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
904 } else {
905 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
906 }
907 }
908 $i++;
909 }
910
911 # If there is a single-letter word, use it!
912 if ($firstsingleletterword > -1)
913 {
914 $arr [ $firstsingleletterword ] = "''";
915 $arr [ $firstsingleletterword-1 ] .= "'";
916 }
917 # If not, but there's a multi-letter word, use that one.
918 else if ($firstmultiletterword > -1)
919 {
920 $arr [ $firstmultiletterword ] = "''";
921 $arr [ $firstmultiletterword-1 ] .= "'";
922 }
923 # ... otherwise use the first one that has neither.
924 # (notice that it is possible for all three to be -1 if, for example,
925 # there is only one pentuple-apostrophe in the line)
926 else if ($firstspace > -1)
927 {
928 $arr [ $firstspace ] = "''";
929 $arr [ $firstspace-1 ] .= "'";
930 }
931 }
932
933 # Now let's actually convert our apostrophic mush to HTML!
934 $output = '';
935 $buffer = '';
936 $state = '';
937 $i = 0;
938 foreach ($arr as $r)
939 {
940 if (($i % 2) == 0)
941 {
942 if ($state == 'both')
943 $buffer .= $r;
944 else
945 $output .= $r;
946 }
947 else
948 {
949 if (strlen ($r) == 2)
950 {
951 if ($state == 'i')
952 { $output .= '</i>'; $state = ''; }
953 else if ($state == 'bi')
954 { $output .= '</i>'; $state = 'b'; }
955 else if ($state == 'ib')
956 { $output .= '</b></i><b>'; $state = 'b'; }
957 else if ($state == 'both')
958 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
959 else # $state can be 'b' or ''
960 { $output .= '<i>'; $state .= 'i'; }
961 }
962 else if (strlen ($r) == 3)
963 {
964 if ($state == 'b')
965 { $output .= '</b>'; $state = ''; }
966 else if ($state == 'bi')
967 { $output .= '</i></b><i>'; $state = 'i'; }
968 else if ($state == 'ib')
969 { $output .= '</b>'; $state = 'i'; }
970 else if ($state == 'both')
971 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
972 else # $state can be 'i' or ''
973 { $output .= '<b>'; $state .= 'b'; }
974 }
975 else if (strlen ($r) == 5)
976 {
977 if ($state == 'b')
978 { $output .= '</b><i>'; $state = 'i'; }
979 else if ($state == 'i')
980 { $output .= '</i><b>'; $state = 'b'; }
981 else if ($state == 'bi')
982 { $output .= '</i></b>'; $state = ''; }
983 else if ($state == 'ib')
984 { $output .= '</b></i>'; $state = ''; }
985 else if ($state == 'both')
986 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
987 else # ($state == '')
988 { $buffer = ''; $state = 'both'; }
989 }
990 }
991 $i++;
992 }
993 # Now close all remaining tags. Notice that the order is important.
994 if ($state == 'b' || $state == 'ib')
995 $output .= '</b>';
996 if ($state == 'i' || $state == 'bi' || $state == 'ib')
997 $output .= '</i>';
998 if ($state == 'bi')
999 $output .= '</b>';
1000 if ($state == 'both')
1001 $output .= '<b><i>'.$buffer.'</i></b>';
1002 return $output;
1003 }
1004 }
1005
1006 /**
1007 * Replace external links
1008 *
1009 * Note: this is all very hackish and the order of execution matters a lot.
1010 * Make sure to run maintenance/parserTests.php if you change this code.
1011 *
1012 * @access private
1013 */
1014 function replaceExternalLinks( $text ) {
1015 global $wgContLang;
1016 $fname = 'Parser::replaceExternalLinks';
1017 wfProfileIn( $fname );
1018
1019 $sk =& $this->mOptions->getSkin();
1020
1021 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1022
1023 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1024
1025 $i = 0;
1026 while ( $i<count( $bits ) ) {
1027 $url = $bits[$i++];
1028 $protocol = $bits[$i++];
1029 $text = $bits[$i++];
1030 $trail = $bits[$i++];
1031
1032 # The characters '<' and '>' (which were escaped by
1033 # removeHTMLtags()) should not be included in
1034 # URLs, per RFC 2396.
1035 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1036 $text = substr($url, $m2[0][1]) . ' ' . $text;
1037 $url = substr($url, 0, $m2[0][1]);
1038 }
1039
1040 # If the link text is an image URL, replace it with an <img> tag
1041 # This happened by accident in the original parser, but some people used it extensively
1042 $img = $this->maybeMakeExternalImage( $text );
1043 if ( $img !== false ) {
1044 $text = $img;
1045 }
1046
1047 $dtrail = '';
1048
1049 # Set linktype for CSS - if URL==text, link is essentially free
1050 $linktype = ($text == $url) ? 'free' : 'text';
1051
1052 # No link text, e.g. [http://domain.tld/some.link]
1053 if ( $text == '' ) {
1054 # Autonumber if allowed
1055 if ( strpos( HTTP_PROTOCOLS, $protocol ) !== false ) {
1056 $text = '[' . ++$this->mAutonumber . ']';
1057 $linktype = 'autonumber';
1058 } else {
1059 # Otherwise just use the URL
1060 $text = htmlspecialchars( $url );
1061 $linktype = 'free';
1062 }
1063 } else {
1064 # Have link text, e.g. [http://domain.tld/some.link text]s
1065 # Check for trail
1066 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1067 }
1068
1069 $text = $wgContLang->markNoConversion($text);
1070
1071 # Replace &amp; from obsolete syntax with &.
1072 # All HTML entities will be escaped by makeExternalLink()
1073 # or maybeMakeExternalImage()
1074 $url = str_replace( '&amp;', '&', $url );
1075
1076 # Process the trail (i.e. everything after this link up until start of the next link),
1077 # replacing any non-bracketed links
1078 $trail = $this->replaceFreeExternalLinks( $trail );
1079
1080
1081 # Use the encoded URL
1082 # This means that users can paste URLs directly into the text
1083 # Funny characters like &ouml; aren't valid in URLs anyway
1084 # This was changed in August 2004
1085 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1086 }
1087
1088 wfProfileOut( $fname );
1089 return $s;
1090 }
1091
1092 /**
1093 * Replace anything that looks like a URL with a link
1094 * @access private
1095 */
1096 function replaceFreeExternalLinks( $text ) {
1097 global $wgContLang;
1098 $fname = 'Parser::replaceFreeExternalLinks';
1099 wfProfileIn( $fname );
1100
1101 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1102 $s = array_shift( $bits );
1103 $i = 0;
1104
1105 $sk =& $this->mOptions->getSkin();
1106
1107 while ( $i < count( $bits ) ){
1108 $protocol = $bits[$i++];
1109 $remainder = $bits[$i++];
1110
1111 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1112 # Found some characters after the protocol that look promising
1113 $url = $protocol . $m[1];
1114 $trail = $m[2];
1115
1116 # The characters '<' and '>' (which were escaped by
1117 # removeHTMLtags()) should not be included in
1118 # URLs, per RFC 2396.
1119 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1120 $trail = substr($url, $m2[0][1]) . $trail;
1121 $url = substr($url, 0, $m2[0][1]);
1122 }
1123
1124 # Move trailing punctuation to $trail
1125 $sep = ',;\.:!?';
1126 # If there is no left bracket, then consider right brackets fair game too
1127 if ( strpos( $url, '(' ) === false ) {
1128 $sep .= ')';
1129 }
1130
1131 $numSepChars = strspn( strrev( $url ), $sep );
1132 if ( $numSepChars ) {
1133 $trail = substr( $url, -$numSepChars ) . $trail;
1134 $url = substr( $url, 0, -$numSepChars );
1135 }
1136
1137 # Replace &amp; from obsolete syntax with &.
1138 # All HTML entities will be escaped by makeExternalLink()
1139 # or maybeMakeExternalImage()
1140 $url = str_replace( '&amp;', '&', $url );
1141
1142 # Is this an external image?
1143 $text = $this->maybeMakeExternalImage( $url );
1144 if ( $text === false ) {
1145 # Not an image, make a link
1146 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1147 }
1148 $s .= $text . $trail;
1149 } else {
1150 $s .= $protocol . $remainder;
1151 }
1152 }
1153 wfProfileOut();
1154 return $s;
1155 }
1156
1157 /**
1158 * make an image if it's allowed
1159 * @access private
1160 */
1161 function maybeMakeExternalImage( $url ) {
1162 $sk =& $this->mOptions->getSkin();
1163 $text = false;
1164 if ( $this->mOptions->getAllowExternalImages() ) {
1165 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1166 # Image found
1167 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1168 }
1169 }
1170 return $text;
1171 }
1172
1173 /**
1174 * Process [[ ]] wikilinks
1175 *
1176 * @access private
1177 */
1178 function replaceInternalLinks( $s ) {
1179 global $wgContLang, $wgLinkCache;
1180 static $fname = 'Parser::replaceInternalLinks' ;
1181
1182 wfProfileIn( $fname );
1183
1184 wfProfileIn( $fname.'-setup' );
1185 static $tc = FALSE;
1186 # the % is needed to support urlencoded titles as well
1187 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1188
1189 $sk =& $this->mOptions->getSkin();
1190
1191 #split the entire text string on occurences of [[
1192 $a = explode( '[[', ' ' . $s );
1193 #get the first element (all text up to first [[), and remove the space we added
1194 $s = array_shift( $a );
1195 $s = substr( $s, 1 );
1196
1197 # Match a link having the form [[namespace:link|alternate]]trail
1198 static $e1 = FALSE;
1199 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1200 # Match cases where there is no "]]", which might still be images
1201 static $e1_img = FALSE;
1202 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1203 # Match the end of a line for a word that's not followed by whitespace,
1204 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1205 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1206
1207 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1208
1209 if( is_null( $this->mTitle ) ) {
1210 wfDebugDieBacktrace( 'nooo' );
1211 }
1212 $nottalk = !$this->mTitle->isTalkPage();
1213
1214 if ( $useLinkPrefixExtension ) {
1215 if ( preg_match( $e2, $s, $m ) ) {
1216 $first_prefix = $m[2];
1217 $s = $m[1];
1218 } else {
1219 $first_prefix = false;
1220 }
1221 } else {
1222 $prefix = '';
1223 }
1224
1225 $selflink = $this->mTitle->getPrefixedText();
1226 wfProfileOut( $fname.'-setup' );
1227
1228 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1229 $useSubpages = $this->areSubpagesAllowed();
1230
1231 # Loop for each link
1232 for ($k = 0; isset( $a[$k] ); $k++) {
1233 $line = $a[$k];
1234 if ( $useLinkPrefixExtension ) {
1235 wfProfileIn( $fname.'-prefixhandling' );
1236 if ( preg_match( $e2, $s, $m ) ) {
1237 $prefix = $m[2];
1238 $s = $m[1];
1239 } else {
1240 $prefix='';
1241 }
1242 # first link
1243 if($first_prefix) {
1244 $prefix = $first_prefix;
1245 $first_prefix = false;
1246 }
1247 wfProfileOut( $fname.'-prefixhandling' );
1248 }
1249
1250 $might_be_img = false;
1251
1252 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1253 $text = $m[2];
1254 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1255 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1256 # the real problem is with the $e1 regex
1257 # See bug 1300.
1258 #
1259 # Still some problems for cases where the ] is meant to be outside punctuation,
1260 # and no image is in sight. See bug 2095.
1261 #
1262 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1263 $text .= ']'; # so that replaceExternalLinks($text) works later
1264 $m[3] = $n[1];
1265 }
1266 # fix up urlencoded title texts
1267 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1268 $trail = $m[3];
1269 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1270 $might_be_img = true;
1271 $text = $m[2];
1272 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1273 $trail = "";
1274 } else { # Invalid form; output directly
1275 $s .= $prefix . '[[' . $line ;
1276 continue;
1277 }
1278
1279 # Don't allow internal links to pages containing
1280 # PROTO: where PROTO is a valid URL protocol; these
1281 # should be external links.
1282 if (preg_match('/^(\b(?:'.URL_PROTOCOLS.'):)/', $m[1])) {
1283 $s .= $prefix . '[[' . $line ;
1284 continue;
1285 }
1286
1287 # Make subpage if necessary
1288 if( $useSubpages ) {
1289 $link = $this->maybeDoSubpageLink( $m[1], $text );
1290 } else {
1291 $link = $m[1];
1292 }
1293
1294 $noforce = (substr($m[1], 0, 1) != ':');
1295 if (!$noforce) {
1296 # Strip off leading ':'
1297 $link = substr($link, 1);
1298 }
1299
1300 $nt =& Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1301 if( !$nt ) {
1302 $s .= $prefix . '[[' . $line;
1303 continue;
1304 }
1305
1306 #check other language variants of the link
1307 #if the article does not exist
1308 if( $checkVariantLink
1309 && $nt->getArticleID() == 0 ) {
1310 $wgContLang->findVariantLink($link, $nt);
1311 }
1312
1313 $ns = $nt->getNamespace();
1314 $iw = $nt->getInterWiki();
1315
1316 if ($might_be_img) { # if this is actually an invalid link
1317 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1318 $found = false;
1319 while (isset ($a[$k+1]) ) {
1320 #look at the next 'line' to see if we can close it there
1321 $next_line = array_shift(array_splice( $a, $k + 1, 1) );
1322 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1323 # the first ]] closes the inner link, the second the image
1324 $found = true;
1325 $text .= '[[' . $m[1];
1326 $trail = $m[2];
1327 break;
1328 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1329 #if there's exactly one ]] that's fine, we'll keep looking
1330 $text .= '[[' . $m[0];
1331 } else {
1332 #if $next_line is invalid too, we need look no further
1333 $text .= '[[' . $next_line;
1334 break;
1335 }
1336 }
1337 if ( !$found ) {
1338 # we couldn't find the end of this imageLink, so output it raw
1339 #but don't ignore what might be perfectly normal links in the text we've examined
1340 $text = $this->replaceInternalLinks($text);
1341 $s .= $prefix . '[[' . $link . '|' . $text;
1342 # note: no $trail, because without an end, there *is* no trail
1343 continue;
1344 }
1345 } else { #it's not an image, so output it raw
1346 $s .= $prefix . '[[' . $link . '|' . $text;
1347 # note: no $trail, because without an end, there *is* no trail
1348 continue;
1349 }
1350 }
1351
1352 $wasblank = ( '' == $text );
1353 if( $wasblank ) $text = $link;
1354
1355
1356 # Link not escaped by : , create the various objects
1357 if( $noforce ) {
1358
1359 # Interwikis
1360 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1361 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1362 $s = rtrim($s . "\n");
1363 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1364 continue;
1365 }
1366
1367 if ( $ns == NS_IMAGE ) {
1368 wfProfileIn( "$fname-image" );
1369 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1370 # recursively parse links inside the image caption
1371 # actually, this will parse them in any other parameters, too,
1372 # but it might be hard to fix that, and it doesn't matter ATM
1373 $text = $this->replaceExternalLinks($text);
1374 $text = $this->replaceInternalLinks($text);
1375
1376 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1377 $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
1378 $wgLinkCache->addImageLinkObj( $nt );
1379
1380 wfProfileOut( "$fname-image" );
1381 continue;
1382 }
1383 wfProfileOut( "$fname-image" );
1384
1385 }
1386
1387 if ( $ns == NS_CATEGORY ) {
1388 wfProfileIn( "$fname-category" );
1389 $t = $wgContLang->convert($nt->getText());
1390 $s = rtrim($s . "\n"); # bug 87
1391
1392 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1393 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1394 $wgLinkCache->resume();
1395
1396 if ( $wasblank ) {
1397 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1398 $sortkey = $this->mTitle->getText();
1399 } else {
1400 $sortkey = $this->mTitle->getPrefixedText();
1401 }
1402 } else {
1403 $sortkey = $text;
1404 }
1405 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1406 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1407 $this->mOutput->addCategoryLink( $t );
1408
1409 /**
1410 * Strip the whitespace Category links produce, see bug 87
1411 * @todo We might want to use trim($tmp, "\n") here.
1412 */
1413 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1414
1415 wfProfileOut( "$fname-category" );
1416 continue;
1417 }
1418 }
1419
1420 if( ( $nt->getPrefixedText() === $selflink ) &&
1421 ( $nt->getFragment() === '' ) ) {
1422 # Self-links are handled specially; generally de-link and change to bold.
1423 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1424 continue;
1425 }
1426
1427 # Special and Media are pseudo-namespaces; no pages actually exist in them
1428 if( $ns == NS_MEDIA ) {
1429 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1430 $wgLinkCache->addImageLinkObj( $nt );
1431 continue;
1432 } elseif( $ns == NS_SPECIAL ) {
1433 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1434 continue;
1435 }
1436 if ( $nt->isAlwaysKnown() ) {
1437 $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
1438 } else {
1439 /**
1440 * Add a link placeholder
1441 * Later, this will be replaced by a real link, after the existence or
1442 * non-existence of all the links is known
1443 */
1444 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1445 }
1446 }
1447 wfProfileOut( $fname );
1448 return $s;
1449 }
1450
1451 /**
1452 * Make a link placeholder. The text returned can be later resolved to a real link with
1453 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1454 * parsing of interwiki links, and secondly to allow all extistence checks and
1455 * article length checks (for stub links) to be bundled into a single query.
1456 *
1457 */
1458 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1459 if ( ! is_object($nt) ) {
1460 # Fail gracefully
1461 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1462 } else {
1463 # Separate the link trail from the rest of the link
1464 list( $inside, $trail ) = Linker::splitTrail( $trail );
1465
1466 if ( $nt->isExternal() ) {
1467 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1468 $this->mInterwikiLinkHolders['titles'][] =& $nt;
1469 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1470 } else {
1471 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1472 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1473 $this->mLinkHolders['queries'][] = $query;
1474 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1475 $this->mLinkHolders['titles'][] =& $nt;
1476
1477 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1478 }
1479 }
1480 return $retVal;
1481 }
1482
1483 /**
1484 * Return true if subpage links should be expanded on this page.
1485 * @return bool
1486 */
1487 function areSubpagesAllowed() {
1488 # Some namespaces don't allow subpages
1489 global $wgNamespacesWithSubpages;
1490 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1491 }
1492
1493 /**
1494 * Handle link to subpage if necessary
1495 * @param string $target the source of the link
1496 * @param string &$text the link text, modified as necessary
1497 * @return string the full name of the link
1498 * @access private
1499 */
1500 function maybeDoSubpageLink($target, &$text) {
1501 # Valid link forms:
1502 # Foobar -- normal
1503 # :Foobar -- override special treatment of prefix (images, language links)
1504 # /Foobar -- convert to CurrentPage/Foobar
1505 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1506 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1507 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1508
1509 $fname = 'Parser::maybeDoSubpageLink';
1510 wfProfileIn( $fname );
1511 $ret = $target; # default return value is no change
1512
1513 # Some namespaces don't allow subpages,
1514 # so only perform processing if subpages are allowed
1515 if( $this->areSubpagesAllowed() ) {
1516 # Look at the first character
1517 if( $target != '' && $target{0} == '/' ) {
1518 # / at end means we don't want the slash to be shown
1519 if( substr( $target, -1, 1 ) == '/' ) {
1520 $target = substr( $target, 1, -1 );
1521 $noslash = $target;
1522 } else {
1523 $noslash = substr( $target, 1 );
1524 }
1525
1526 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1527 if( '' === $text ) {
1528 $text = $target;
1529 } # this might be changed for ugliness reasons
1530 } else {
1531 # check for .. subpage backlinks
1532 $dotdotcount = 0;
1533 $nodotdot = $target;
1534 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1535 ++$dotdotcount;
1536 $nodotdot = substr( $nodotdot, 3 );
1537 }
1538 if($dotdotcount > 0) {
1539 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1540 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1541 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1542 # / at the end means don't show full path
1543 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1544 $nodotdot = substr( $nodotdot, 0, -1 );
1545 if( '' === $text ) {
1546 $text = $nodotdot;
1547 }
1548 }
1549 $nodotdot = trim( $nodotdot );
1550 if( $nodotdot != '' ) {
1551 $ret .= '/' . $nodotdot;
1552 }
1553 }
1554 }
1555 }
1556 }
1557
1558 wfProfileOut( $fname );
1559 return $ret;
1560 }
1561
1562 /**#@+
1563 * Used by doBlockLevels()
1564 * @access private
1565 */
1566 /* private */ function closeParagraph() {
1567 $result = '';
1568 if ( '' != $this->mLastSection ) {
1569 $result = '</' . $this->mLastSection . ">\n";
1570 }
1571 $this->mInPre = false;
1572 $this->mLastSection = '';
1573 return $result;
1574 }
1575 # getCommon() returns the length of the longest common substring
1576 # of both arguments, starting at the beginning of both.
1577 #
1578 /* private */ function getCommon( $st1, $st2 ) {
1579 $fl = strlen( $st1 );
1580 $shorter = strlen( $st2 );
1581 if ( $fl < $shorter ) { $shorter = $fl; }
1582
1583 for ( $i = 0; $i < $shorter; ++$i ) {
1584 if ( $st1{$i} != $st2{$i} ) { break; }
1585 }
1586 return $i;
1587 }
1588 # These next three functions open, continue, and close the list
1589 # element appropriate to the prefix character passed into them.
1590 #
1591 /* private */ function openList( $char ) {
1592 $result = $this->closeParagraph();
1593
1594 if ( '*' == $char ) { $result .= '<ul><li>'; }
1595 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1596 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1597 else if ( ';' == $char ) {
1598 $result .= '<dl><dt>';
1599 $this->mDTopen = true;
1600 }
1601 else { $result = '<!-- ERR 1 -->'; }
1602
1603 return $result;
1604 }
1605
1606 /* private */ function nextItem( $char ) {
1607 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1608 else if ( ':' == $char || ';' == $char ) {
1609 $close = '</dd>';
1610 if ( $this->mDTopen ) { $close = '</dt>'; }
1611 if ( ';' == $char ) {
1612 $this->mDTopen = true;
1613 return $close . '<dt>';
1614 } else {
1615 $this->mDTopen = false;
1616 return $close . '<dd>';
1617 }
1618 }
1619 return '<!-- ERR 2 -->';
1620 }
1621
1622 /* private */ function closeList( $char ) {
1623 if ( '*' == $char ) { $text = '</li></ul>'; }
1624 else if ( '#' == $char ) { $text = '</li></ol>'; }
1625 else if ( ':' == $char ) {
1626 if ( $this->mDTopen ) {
1627 $this->mDTopen = false;
1628 $text = '</dt></dl>';
1629 } else {
1630 $text = '</dd></dl>';
1631 }
1632 }
1633 else { return '<!-- ERR 3 -->'; }
1634 return $text."\n";
1635 }
1636 /**#@-*/
1637
1638 /**
1639 * Make lists from lines starting with ':', '*', '#', etc.
1640 *
1641 * @access private
1642 * @return string the lists rendered as HTML
1643 */
1644 function doBlockLevels( $text, $linestart ) {
1645 $fname = 'Parser::doBlockLevels';
1646 wfProfileIn( $fname );
1647
1648 # Parsing through the text line by line. The main thing
1649 # happening here is handling of block-level elements p, pre,
1650 # and making lists from lines starting with * # : etc.
1651 #
1652 $textLines = explode( "\n", $text );
1653
1654 $lastPrefix = $output = '';
1655 $this->mDTopen = $inBlockElem = false;
1656 $prefixLength = 0;
1657 $paragraphStack = false;
1658
1659 if ( !$linestart ) {
1660 $output .= array_shift( $textLines );
1661 }
1662 foreach ( $textLines as $oLine ) {
1663 $lastPrefixLength = strlen( $lastPrefix );
1664 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1665 $preOpenMatch = preg_match('/<pre/i', $oLine );
1666 if ( !$this->mInPre ) {
1667 # Multiple prefixes may abut each other for nested lists.
1668 $prefixLength = strspn( $oLine, '*#:;' );
1669 $pref = substr( $oLine, 0, $prefixLength );
1670
1671 # eh?
1672 $pref2 = str_replace( ';', ':', $pref );
1673 $t = substr( $oLine, $prefixLength );
1674 $this->mInPre = !empty($preOpenMatch);
1675 } else {
1676 # Don't interpret any other prefixes in preformatted text
1677 $prefixLength = 0;
1678 $pref = $pref2 = '';
1679 $t = $oLine;
1680 }
1681
1682 # List generation
1683 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1684 # Same as the last item, so no need to deal with nesting or opening stuff
1685 $output .= $this->nextItem( substr( $pref, -1 ) );
1686 $paragraphStack = false;
1687
1688 if ( substr( $pref, -1 ) == ';') {
1689 # The one nasty exception: definition lists work like this:
1690 # ; title : definition text
1691 # So we check for : in the remainder text to split up the
1692 # title and definition, without b0rking links.
1693 $term = $t2 = '';
1694 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1695 $t = $t2;
1696 $output .= $term . $this->nextItem( ':' );
1697 }
1698 }
1699 } elseif( $prefixLength || $lastPrefixLength ) {
1700 # Either open or close a level...
1701 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1702 $paragraphStack = false;
1703
1704 while( $commonPrefixLength < $lastPrefixLength ) {
1705 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1706 --$lastPrefixLength;
1707 }
1708 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1709 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1710 }
1711 while ( $prefixLength > $commonPrefixLength ) {
1712 $char = substr( $pref, $commonPrefixLength, 1 );
1713 $output .= $this->openList( $char );
1714
1715 if ( ';' == $char ) {
1716 # FIXME: This is dupe of code above
1717 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1718 $t = $t2;
1719 $output .= $term . $this->nextItem( ':' );
1720 }
1721 }
1722 ++$commonPrefixLength;
1723 }
1724 $lastPrefix = $pref2;
1725 }
1726 if( 0 == $prefixLength ) {
1727 wfProfileIn( "$fname-paragraph" );
1728 # No prefix (not in list)--go to paragraph mode
1729 $uniq_prefix = UNIQ_PREFIX;
1730 // XXX: use a stack for nestable elements like span, table and div
1731 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1732 $closematch = preg_match(
1733 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1734 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1735 if ( $openmatch or $closematch ) {
1736 $paragraphStack = false;
1737 $output .= $this->closeParagraph();
1738 if($preOpenMatch and !$preCloseMatch) {
1739 $this->mInPre = true;
1740 }
1741 if ( $closematch ) {
1742 $inBlockElem = false;
1743 } else {
1744 $inBlockElem = true;
1745 }
1746 } else if ( !$inBlockElem && !$this->mInPre ) {
1747 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1748 // pre
1749 if ($this->mLastSection != 'pre') {
1750 $paragraphStack = false;
1751 $output .= $this->closeParagraph().'<pre>';
1752 $this->mLastSection = 'pre';
1753 }
1754 $t = substr( $t, 1 );
1755 } else {
1756 // paragraph
1757 if ( '' == trim($t) ) {
1758 if ( $paragraphStack ) {
1759 $output .= $paragraphStack.'<br />';
1760 $paragraphStack = false;
1761 $this->mLastSection = 'p';
1762 } else {
1763 if ($this->mLastSection != 'p' ) {
1764 $output .= $this->closeParagraph();
1765 $this->mLastSection = '';
1766 $paragraphStack = '<p>';
1767 } else {
1768 $paragraphStack = '</p><p>';
1769 }
1770 }
1771 } else {
1772 if ( $paragraphStack ) {
1773 $output .= $paragraphStack;
1774 $paragraphStack = false;
1775 $this->mLastSection = 'p';
1776 } else if ($this->mLastSection != 'p') {
1777 $output .= $this->closeParagraph().'<p>';
1778 $this->mLastSection = 'p';
1779 }
1780 }
1781 }
1782 }
1783 wfProfileOut( "$fname-paragraph" );
1784 }
1785 if ($paragraphStack === false) {
1786 $output .= $t."\n";
1787 }
1788 }
1789 while ( $prefixLength ) {
1790 $output .= $this->closeList( $pref2{$prefixLength-1} );
1791 --$prefixLength;
1792 }
1793 if ( '' != $this->mLastSection ) {
1794 $output .= '</' . $this->mLastSection . '>';
1795 $this->mLastSection = '';
1796 }
1797
1798 wfProfileOut( $fname );
1799 return $output;
1800 }
1801
1802 /**
1803 * Split up a string on ':', ignoring any occurences inside
1804 * <a>..</a> or <span>...</span>
1805 * @param string $str the string to split
1806 * @param string &$before set to everything before the ':'
1807 * @param string &$after set to everything after the ':'
1808 * return string the position of the ':', or false if none found
1809 */
1810 function findColonNoLinks($str, &$before, &$after) {
1811 # I wonder if we should make this count all tags, not just <a>
1812 # and <span>. That would prevent us from matching a ':' that
1813 # comes in the middle of italics other such formatting....
1814 # -- Wil
1815 $fname = 'Parser::findColonNoLinks';
1816 wfProfileIn( $fname );
1817 $pos = 0;
1818 do {
1819 $colon = strpos($str, ':', $pos);
1820
1821 if ($colon !== false) {
1822 $before = substr($str, 0, $colon);
1823 $after = substr($str, $colon + 1);
1824
1825 # Skip any ':' within <a> or <span> pairs
1826 $a = substr_count($before, '<a');
1827 $s = substr_count($before, '<span');
1828 $ca = substr_count($before, '</a>');
1829 $cs = substr_count($before, '</span>');
1830
1831 if ($a <= $ca and $s <= $cs) {
1832 # Tags are balanced before ':'; ok
1833 break;
1834 }
1835 $pos = $colon + 1;
1836 }
1837 } while ($colon !== false);
1838 wfProfileOut( $fname );
1839 return $colon;
1840 }
1841
1842 /**
1843 * Return value of a magic variable (like PAGENAME)
1844 *
1845 * @access private
1846 */
1847 function getVariableValue( $index ) {
1848 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1849
1850 /**
1851 * Some of these require message or data lookups and can be
1852 * expensive to check many times.
1853 */
1854 static $varCache = array();
1855 if( isset( $varCache[$index] ) ) return $varCache[$index];
1856
1857 switch ( $index ) {
1858 case MAG_CURRENTMONTH:
1859 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1860 case MAG_CURRENTMONTHNAME:
1861 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1862 case MAG_CURRENTMONTHNAMEGEN:
1863 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1864 case MAG_CURRENTMONTHABBREV:
1865 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1866 case MAG_CURRENTDAY:
1867 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1868 case MAG_PAGENAME:
1869 return $this->mTitle->getText();
1870 case MAG_PAGENAMEE:
1871 return $this->mTitle->getPartialURL();
1872 case MAG_REVISIONID:
1873 return $wgArticle->getRevIdFetched();
1874 case MAG_NAMESPACE:
1875 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1876 return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1877 case MAG_CURRENTDAYNAME:
1878 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1879 case MAG_CURRENTYEAR:
1880 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1881 case MAG_CURRENTTIME:
1882 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1883 case MAG_CURRENTWEEK:
1884 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1885 case MAG_CURRENTDOW:
1886 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1887 case MAG_NUMBEROFARTICLES:
1888 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1889 case MAG_SITENAME:
1890 return $wgSitename;
1891 case MAG_SERVER:
1892 return $wgServer;
1893 default:
1894 return NULL;
1895 }
1896 }
1897
1898 /**
1899 * initialise the magic variables (like CURRENTMONTHNAME)
1900 *
1901 * @access private
1902 */
1903 function initialiseVariables() {
1904 $fname = 'Parser::initialiseVariables';
1905 wfProfileIn( $fname );
1906 global $wgVariableIDs;
1907 $this->mVariables = array();
1908 foreach ( $wgVariableIDs as $id ) {
1909 $mw =& MagicWord::get( $id );
1910 $mw->addToArray( $this->mVariables, $id );
1911 }
1912 wfProfileOut( $fname );
1913 }
1914
1915 /**
1916 * Replace magic variables, templates, and template arguments
1917 * with the appropriate text. Templates are substituted recursively,
1918 * taking care to avoid infinite loops.
1919 *
1920 * Note that the substitution depends on value of $mOutputType:
1921 * OT_WIKI: only {{subst:}} templates
1922 * OT_MSG: only magic variables
1923 * OT_HTML: all templates and magic variables
1924 *
1925 * @param string $tex The text to transform
1926 * @param array $args Key-value pairs representing template parameters to substitute
1927 * @access private
1928 */
1929 function replaceVariables( $text, $args = array() ) {
1930
1931 # Prevent too big inclusions
1932 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
1933 return $text;
1934 }
1935
1936 $fname = 'Parser::replaceVariables';
1937 wfProfileIn( $fname );
1938
1939 $titleChars = Title::legalChars();
1940
1941 # This function is called recursively. To keep track of arguments we need a stack:
1942 array_push( $this->mArgStack, $args );
1943
1944 # Variable substitution
1945 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1946
1947 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
1948 # Argument substitution
1949 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1950 }
1951 # Template substitution
1952 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1953 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1954
1955 array_pop( $this->mArgStack );
1956
1957 wfProfileOut( $fname );
1958 return $text;
1959 }
1960
1961 /**
1962 * Replace magic variables
1963 * @access private
1964 */
1965 function variableSubstitution( $matches ) {
1966 $fname = 'parser::variableSubstitution';
1967 $varname = $matches[1];
1968 wfProfileIn( $fname );
1969 if ( !$this->mVariables ) {
1970 $this->initialiseVariables();
1971 }
1972 $skip = false;
1973 if ( $this->mOutputType == OT_WIKI ) {
1974 # Do only magic variables prefixed by SUBST
1975 $mwSubst =& MagicWord::get( MAG_SUBST );
1976 if (!$mwSubst->matchStartAndRemove( $varname ))
1977 $skip = true;
1978 # Note that if we don't substitute the variable below,
1979 # we don't remove the {{subst:}} magic word, in case
1980 # it is a template rather than a magic variable.
1981 }
1982 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
1983 $id = $this->mVariables[$varname];
1984 $text = $this->getVariableValue( $id );
1985 $this->mOutput->mContainsOldMagic = true;
1986 } else {
1987 $text = $matches[0];
1988 }
1989 wfProfileOut( $fname );
1990 return $text;
1991 }
1992
1993 # Split template arguments
1994 function getTemplateArgs( $argsString ) {
1995 if ( $argsString === '' ) {
1996 return array();
1997 }
1998
1999 $args = explode( '|', substr( $argsString, 1 ) );
2000
2001 # If any of the arguments contains a '[[' but no ']]', it needs to be
2002 # merged with the next arg because the '|' character between belongs
2003 # to the link syntax and not the template parameter syntax.
2004 $argc = count($args);
2005
2006 for ( $i = 0; $i < $argc-1; $i++ ) {
2007 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2008 $args[$i] .= '|'.$args[$i+1];
2009 array_splice($args, $i+1, 1);
2010 $i--;
2011 $argc--;
2012 }
2013 }
2014
2015 return $args;
2016 }
2017
2018 /**
2019 * Return the text of a template, after recursively
2020 * replacing any variables or templates within the template.
2021 *
2022 * @param array $matches The parts of the template
2023 * $matches[1]: the title, i.e. the part before the |
2024 * $matches[2]: the parameters (including a leading |), if any
2025 * @return string the text of the template
2026 * @access private
2027 */
2028 function braceSubstitution( $matches ) {
2029 global $wgLinkCache, $wgContLang;
2030 $fname = 'Parser::braceSubstitution';
2031 wfProfileIn( $fname );
2032
2033 $found = false;
2034 $nowiki = false;
2035 $noparse = false;
2036
2037 $title = NULL;
2038
2039 # Need to know if the template comes at the start of a line,
2040 # to treat the beginning of the template like the beginning
2041 # of a line for tables and block-level elements.
2042 $linestart = $matches[1];
2043
2044 # $part1 is the bit before the first |, and must contain only title characters
2045 # $args is a list of arguments, starting from index 0, not including $part1
2046
2047 $part1 = $matches[2];
2048 # If the third subpattern matched anything, it will start with |
2049
2050 $args = $this->getTemplateArgs($matches[3]);
2051 $argc = count( $args );
2052
2053 # Don't parse {{{}}} because that's only for template arguments
2054 if ( $linestart === '{' ) {
2055 $text = $matches[0];
2056 $found = true;
2057 $noparse = true;
2058 }
2059
2060 # SUBST
2061 if ( !$found ) {
2062 $mwSubst =& MagicWord::get( MAG_SUBST );
2063 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2064 # One of two possibilities is true:
2065 # 1) Found SUBST but not in the PST phase
2066 # 2) Didn't find SUBST and in the PST phase
2067 # In either case, return without further processing
2068 $text = $matches[0];
2069 $found = true;
2070 $noparse = true;
2071 }
2072 }
2073
2074 # MSG, MSGNW and INT
2075 if ( !$found ) {
2076 # Check for MSGNW:
2077 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2078 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2079 $nowiki = true;
2080 }
2081
2082 # int: is the wikitext equivalent of wfMsg()
2083 $mwInt =& MagicWord::get( MAG_INT );
2084 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2085 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2086 $text = $linestart . wfMsgReal( $part1, $args, true );
2087 $found = true;
2088 }
2089 }
2090
2091 # msg: is the wikitext equivalent of wfMsgForContent()
2092 $mwMsg =& MagicWord::get( MAG_MSG );
2093 if ( $mwMsg->matchStartAndRemove( $part1 ) ) {
2094 if ( $this->incrementIncludeCount( 'msg:'.$part1 ) ) {
2095 $text = $linestart . wfMsgReal( $part1, $args, true, true );
2096 $found = true;
2097 }
2098 }
2099 }
2100
2101 # NS
2102 if ( !$found ) {
2103 # Check for NS: (namespace expansion)
2104 $mwNs = MagicWord::get( MAG_NS );
2105 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2106 if ( intval( $part1 ) ) {
2107 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2108 $found = true;
2109 } else {
2110 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2111 if ( !is_null( $index ) ) {
2112 $text = $linestart . $wgContLang->getNsText( $index );
2113 $found = true;
2114 }
2115 }
2116 }
2117 }
2118
2119 # LOCALURL and LOCALURLE
2120 if ( !$found ) {
2121 $mwLocal = MagicWord::get( MAG_LOCALURL );
2122 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
2123
2124 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2125 $func = 'getLocalURL';
2126 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2127 $func = 'escapeLocalURL';
2128 } else {
2129 $func = '';
2130 }
2131
2132 if ( $func !== '' ) {
2133 $title = Title::newFromText( $part1 );
2134 if ( !is_null( $title ) ) {
2135 if ( $argc > 0 ) {
2136 $text = $linestart . $title->$func( $args[0] );
2137 } else {
2138 $text = $linestart . $title->$func();
2139 }
2140 $found = true;
2141 }
2142 }
2143 }
2144
2145 # GRAMMAR
2146 if ( !$found && $argc == 1 ) {
2147 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2148 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2149 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2150 $found = true;
2151 }
2152 }
2153
2154 # Template table test
2155
2156 # Did we encounter this template already? If yes, it is in the cache
2157 # and we need to check for loops.
2158 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
2159 $found = true;
2160
2161 # Infinite loop test
2162 if ( isset( $this->mTemplatePath[$part1] ) ) {
2163 $noparse = true;
2164 $found = true;
2165 $text = $linestart .
2166 "\{\{$part1}}" .
2167 '<!-- WARNING: template loop detected -->';
2168 wfDebug( "$fname: template loop broken at '$part1'\n" );
2169 } else {
2170 # set $text to cached message.
2171 $text = $linestart . $this->mTemplates[$part1];
2172 }
2173 }
2174
2175 # Load from database
2176 $replaceHeadings = false;
2177 $isHTML = false;
2178 $lastPathLevel = $this->mTemplatePath;
2179 if ( !$found ) {
2180 $ns = NS_TEMPLATE;
2181 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2182 if ($subpage !== '') {
2183 $ns = $this->mTitle->getNamespace();
2184 }
2185 $title = Title::newFromText( $part1, $ns );
2186 if ( !is_null( $title ) && !$title->isExternal() ) {
2187 # Check for excessive inclusion
2188 $dbk = $title->getPrefixedDBkey();
2189 if ( $this->incrementIncludeCount( $dbk ) ) {
2190 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2191 # Capture special page output
2192 $text = SpecialPage::capturePath( $title );
2193 if ( $text && !is_object( $text ) ) {
2194 $found = true;
2195 $noparse = true;
2196 $isHTML = true;
2197 $this->mOutput->setCacheTime( -1 );
2198 }
2199 } else {
2200 $article = new Article( $title );
2201 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2202 if ( $articleContent !== false ) {
2203 $found = true;
2204 $text = $articleContent;
2205 $replaceHeadings = true;
2206 }
2207 }
2208 }
2209
2210 # If the title is valid but undisplayable, make a link to it
2211 if ( $this->mOutputType == OT_HTML && !$found ) {
2212 $text = '[['.$title->getPrefixedText().']]';
2213 $found = true;
2214 }
2215
2216 # Template cache array insertion
2217 if( $found ) {
2218 $this->mTemplates[$part1] = $text;
2219 $text = $linestart . $text;
2220 }
2221 }
2222 }
2223
2224 # Recursive parsing, escaping and link table handling
2225 # Only for HTML output
2226 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2227 $text = wfEscapeWikiText( $text );
2228 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2229 # Clean up argument array
2230 $assocArgs = array();
2231 $index = 1;
2232 foreach( $args as $arg ) {
2233 $eqpos = strpos( $arg, '=' );
2234 if ( $eqpos === false ) {
2235 $assocArgs[$index++] = $arg;
2236 } else {
2237 $name = trim( substr( $arg, 0, $eqpos ) );
2238 $value = trim( substr( $arg, $eqpos+1 ) );
2239 if ( $value === false ) {
2240 $value = '';
2241 }
2242 if ( $name !== false ) {
2243 $assocArgs[$name] = $value;
2244 }
2245 }
2246 }
2247
2248 # Add a new element to the templace recursion path
2249 $this->mTemplatePath[$part1] = 1;
2250
2251 if( $this->mOutputType == OT_HTML ) {
2252 $text = $this->strip( $text, $this->mStripState );
2253 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2254 }
2255 $text = $this->replaceVariables( $text, $assocArgs );
2256
2257 # Resume the link cache and register the inclusion as a link
2258 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2259 $wgLinkCache->addLinkObj( $title );
2260 }
2261
2262 # If the template begins with a table or block-level
2263 # element, it should be treated as beginning a new line.
2264 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2265 $text = "\n" . $text;
2266 }
2267 }
2268 # Prune lower levels off the recursion check path
2269 $this->mTemplatePath = $lastPathLevel;
2270
2271 if ( !$found ) {
2272 wfProfileOut( $fname );
2273 return $matches[0];
2274 } else {
2275 if ( $isHTML ) {
2276 # Replace raw HTML by a placeholder
2277 # Add a blank line preceding, to prevent it from mucking up
2278 # immediately preceding headings
2279 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2280 } else {
2281 # replace ==section headers==
2282 # XXX this needs to go away once we have a better parser.
2283 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2284 if( !is_null( $title ) )
2285 $encodedname = base64_encode($title->getPrefixedDBkey());
2286 else
2287 $encodedname = base64_encode("");
2288 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2289 PREG_SPLIT_DELIM_CAPTURE);
2290 $text = '';
2291 $nsec = 0;
2292 for( $i = 0; $i < count($m); $i += 2 ) {
2293 $text .= $m[$i];
2294 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2295 $hl = $m[$i + 1];
2296 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2297 $text .= $hl;
2298 continue;
2299 }
2300 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2301 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2302 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2303
2304 $nsec++;
2305 }
2306 }
2307 }
2308 }
2309
2310 # Prune lower levels off the recursion check path
2311 $this->mTemplatePath = $lastPathLevel;
2312
2313 if ( !$found ) {
2314 wfProfileOut( $fname );
2315 return $matches[0];
2316 } else {
2317 wfProfileOut( $fname );
2318 return $text;
2319 }
2320 }
2321
2322 /**
2323 * Triple brace replacement -- used for template arguments
2324 * @access private
2325 */
2326 function argSubstitution( $matches ) {
2327 $arg = trim( $matches[1] );
2328 $text = $matches[0];
2329 $inputArgs = end( $this->mArgStack );
2330
2331 if ( array_key_exists( $arg, $inputArgs ) ) {
2332 $text = $inputArgs[$arg];
2333 }
2334
2335 return $text;
2336 }
2337
2338 /**
2339 * Returns true if the function is allowed to include this entity
2340 * @access private
2341 */
2342 function incrementIncludeCount( $dbk ) {
2343 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2344 $this->mIncludeCount[$dbk] = 0;
2345 }
2346 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2347 return true;
2348 } else {
2349 return false;
2350 }
2351 }
2352
2353 /**
2354 * This function accomplishes several tasks:
2355 * 1) Auto-number headings if that option is enabled
2356 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2357 * 3) Add a Table of contents on the top for users who have enabled the option
2358 * 4) Auto-anchor headings
2359 *
2360 * It loops through all headlines, collects the necessary data, then splits up the
2361 * string and re-inserts the newly formatted headlines.
2362 *
2363 * @param string $text
2364 * @param boolean $isMain
2365 * @access private
2366 */
2367 function formatHeadings( $text, $isMain=true ) {
2368 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2369
2370 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2371 $doShowToc = true;
2372 $forceTocHere = false;
2373 if( !$this->mTitle->userCanEdit() ) {
2374 $showEditLink = 0;
2375 } else {
2376 $showEditLink = $this->mOptions->getEditSection();
2377 }
2378
2379 # Inhibit editsection links if requested in the page
2380 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2381 if( $esw->matchAndRemove( $text ) ) {
2382 $showEditLink = 0;
2383 }
2384 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2385 # do not add TOC
2386 $mw =& MagicWord::get( MAG_NOTOC );
2387 if( $mw->matchAndRemove( $text ) ) {
2388 $doShowToc = false;
2389 }
2390
2391 # Get all headlines for numbering them and adding funky stuff like [edit]
2392 # links - this is for later, but we need the number of headlines right now
2393 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2394
2395 # if there are fewer than 4 headlines in the article, do not show TOC
2396 if( $numMatches < 4 ) {
2397 $doShowToc = false;
2398 }
2399
2400 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2401 # override above conditions and always show TOC at that place
2402
2403 $mw =& MagicWord::get( MAG_TOC );
2404 if($mw->match( $text ) ) {
2405 $doShowToc = true;
2406 $forceTocHere = true;
2407 } else {
2408 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2409 # override above conditions and always show TOC above first header
2410 $mw =& MagicWord::get( MAG_FORCETOC );
2411 if ($mw->matchAndRemove( $text ) ) {
2412 $doShowToc = true;
2413 }
2414 }
2415
2416 # Never ever show TOC if no headers
2417 if( $numMatches < 1 ) {
2418 $doShowToc = false;
2419 }
2420
2421 # We need this to perform operations on the HTML
2422 $sk =& $this->mOptions->getSkin();
2423
2424 # headline counter
2425 $headlineCount = 0;
2426 $sectionCount = 0; # headlineCount excluding template sections
2427
2428 # Ugh .. the TOC should have neat indentation levels which can be
2429 # passed to the skin functions. These are determined here
2430 $toc = '';
2431 $full = '';
2432 $head = array();
2433 $sublevelCount = array();
2434 $levelCount = array();
2435 $toclevel = 0;
2436 $level = 0;
2437 $prevlevel = 0;
2438 $toclevel = 0;
2439 $prevtoclevel = 0;
2440
2441 foreach( $matches[3] as $headline ) {
2442 $istemplate = 0;
2443 $templatetitle = '';
2444 $templatesection = 0;
2445 $numbering = '';
2446
2447 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2448 $istemplate = 1;
2449 $templatetitle = base64_decode($mat[1]);
2450 $templatesection = 1 + (int)base64_decode($mat[2]);
2451 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2452 }
2453
2454 if( $toclevel ) {
2455 $prevlevel = $level;
2456 $prevtoclevel = $toclevel;
2457 }
2458 $level = $matches[1][$headlineCount];
2459
2460 if( $doNumberHeadings || $doShowToc ) {
2461
2462 if ( $level > $prevlevel ) {
2463 # Increase TOC level
2464 $toclevel++;
2465 $sublevelCount[$toclevel] = 0;
2466 $toc .= $sk->tocIndent();
2467 }
2468 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2469 # Decrease TOC level, find level to jump to
2470
2471 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2472 # Can only go down to level 1
2473 $toclevel = 1;
2474 } else {
2475 for ($i = $toclevel; $i > 0; $i--) {
2476 if ( $levelCount[$i] == $level ) {
2477 # Found last matching level
2478 $toclevel = $i;
2479 break;
2480 }
2481 elseif ( $levelCount[$i] < $level ) {
2482 # Found first matching level below current level
2483 $toclevel = $i + 1;
2484 break;
2485 }
2486 }
2487 }
2488
2489 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2490 }
2491 else {
2492 # No change in level, end TOC line
2493 $toc .= $sk->tocLineEnd();
2494 }
2495
2496 $levelCount[$toclevel] = $level;
2497
2498 # count number of headlines for each level
2499 @$sublevelCount[$toclevel]++;
2500 $dot = 0;
2501 for( $i = 1; $i <= $toclevel; $i++ ) {
2502 if( !empty( $sublevelCount[$i] ) ) {
2503 if( $dot ) {
2504 $numbering .= '.';
2505 }
2506 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2507 $dot = 1;
2508 }
2509 }
2510 }
2511
2512 # The canonized header is a version of the header text safe to use for links
2513 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2514 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2515 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2516
2517 # Remove link placeholders by the link text.
2518 # <!--LINK number-->
2519 # turns into
2520 # link text with suffix
2521 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2522 "\$this->mLinkHolders['texts'][\$1]",
2523 $canonized_headline );
2524 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2525 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2526 $canonized_headline );
2527
2528 # strip out HTML
2529 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2530 $tocline = trim( $canonized_headline );
2531 $canonized_headline = urlencode( Sanitizer::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2532 $replacearray = array(
2533 '%3A' => ':',
2534 '%' => '.'
2535 );
2536 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2537 $refers[$headlineCount] = $canonized_headline;
2538
2539 # count how many in assoc. array so we can track dupes in anchors
2540 @$refers[$canonized_headline]++;
2541 $refcount[$headlineCount]=$refers[$canonized_headline];
2542
2543 # Don't number the heading if it is the only one (looks silly)
2544 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2545 # the two are different if the line contains a link
2546 $headline=$numbering . ' ' . $headline;
2547 }
2548
2549 # Create the anchor for linking from the TOC to the section
2550 $anchor = $canonized_headline;
2551 if($refcount[$headlineCount] > 1 ) {
2552 $anchor .= '_' . $refcount[$headlineCount];
2553 }
2554 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2555 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2556 }
2557 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2558 if ( empty( $head[$headlineCount] ) ) {
2559 $head[$headlineCount] = '';
2560 }
2561 if( $istemplate )
2562 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2563 else
2564 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2565 }
2566
2567 # give headline the correct <h#> tag
2568 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2569
2570 $headlineCount++;
2571 if( !$istemplate )
2572 $sectionCount++;
2573 }
2574
2575 if( $doShowToc ) {
2576 $toc .= $sk->tocUnindent( $toclevel - 1 );
2577 $toc = $sk->tocList( $toc );
2578 }
2579
2580 # split up and insert constructed headlines
2581
2582 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2583 $i = 0;
2584
2585 foreach( $blocks as $block ) {
2586 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2587 # This is the [edit] link that appears for the top block of text when
2588 # section editing is enabled
2589
2590 # Disabled because it broke block formatting
2591 # For example, a bullet point in the top line
2592 # $full .= $sk->editSectionLink(0);
2593 }
2594 $full .= $block;
2595 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2596 # Top anchor now in skin
2597 $full = $full.$toc;
2598 }
2599
2600 if( !empty( $head[$i] ) ) {
2601 $full .= $head[$i];
2602 }
2603 $i++;
2604 }
2605 if($forceTocHere) {
2606 $mw =& MagicWord::get( MAG_TOC );
2607 return $mw->replace( $toc, $full );
2608 } else {
2609 return $full;
2610 }
2611 }
2612
2613 /**
2614 * Return an HTML link for the "ISBN 123456" text
2615 * @access private
2616 */
2617 function magicISBN( $text ) {
2618 $fname = 'Parser::magicISBN';
2619 wfProfileIn( $fname );
2620
2621 $a = split( 'ISBN ', ' '.$text );
2622 if ( count ( $a ) < 2 ) {
2623 wfProfileOut( $fname );
2624 return $text;
2625 }
2626 $text = substr( array_shift( $a ), 1);
2627 $valid = '0123456789-Xx';
2628
2629 foreach ( $a as $x ) {
2630 $isbn = $blank = '' ;
2631 while ( ' ' == $x{0} ) {
2632 $blank .= ' ';
2633 $x = substr( $x, 1 );
2634 }
2635 if ( $x == '' ) { # blank isbn
2636 $text .= "ISBN $blank";
2637 continue;
2638 }
2639 while ( strstr( $valid, $x{0} ) != false ) {
2640 $isbn .= $x{0};
2641 $x = substr( $x, 1 );
2642 }
2643 $num = str_replace( '-', '', $isbn );
2644 $num = str_replace( ' ', '', $num );
2645 $num = str_replace( 'x', 'X', $num );
2646
2647 if ( '' == $num ) {
2648 $text .= "ISBN $blank$x";
2649 } else {
2650 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2651 $text .= '<a href="' .
2652 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2653 "\" class=\"internal\">ISBN $isbn</a>";
2654 $text .= $x;
2655 }
2656 }
2657 wfProfileOut( $fname );
2658 return $text;
2659 }
2660
2661 /**
2662 * Return an HTML link for the "RFC 1234" text
2663 *
2664 * @access private
2665 * @param string $text Text to be processed
2666 * @param string $keyword Magic keyword to use (default RFC)
2667 * @param string $urlmsg Interface message to use (default rfcurl)
2668 * @return string
2669 */
2670 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2671
2672 $valid = '0123456789';
2673 $internal = false;
2674
2675 $a = split( $keyword, ' '.$text );
2676 if ( count ( $a ) < 2 ) {
2677 return $text;
2678 }
2679 $text = substr( array_shift( $a ), 1);
2680
2681 /* Check if keyword is preceed by [[.
2682 * This test is made here cause of the array_shift above
2683 * that prevent the test to be done in the foreach.
2684 */
2685 if ( substr( $text, -2 ) == '[[' ) {
2686 $internal = true;
2687 }
2688
2689 foreach ( $a as $x ) {
2690 /* token might be empty if we have RFC RFC 1234 */
2691 if ( $x=='' ) {
2692 $text.=$keyword;
2693 continue;
2694 }
2695
2696 $id = $blank = '' ;
2697
2698 /** remove and save whitespaces in $blank */
2699 while ( $x{0} == ' ' ) {
2700 $blank .= ' ';
2701 $x = substr( $x, 1 );
2702 }
2703
2704 /** remove and save the rfc number in $id */
2705 while ( strstr( $valid, $x{0} ) != false ) {
2706 $id .= $x{0};
2707 $x = substr( $x, 1 );
2708 }
2709
2710 if ( $id == '' ) {
2711 /* call back stripped spaces*/
2712 $text .= $keyword.$blank.$x;
2713 } elseif( $internal ) {
2714 /* normal link */
2715 $text .= $keyword.$id.$x;
2716 } else {
2717 /* build the external link*/
2718 $url = wfMsg( $urlmsg, $id);
2719 $sk =& $this->mOptions->getSkin();
2720 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2721 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2722 }
2723
2724 /* Check if the next RFC keyword is preceed by [[ */
2725 $internal = ( substr($x,-2) == '[[' );
2726 }
2727 return $text;
2728 }
2729
2730 /**
2731 * Transform wiki markup when saving a page by doing \r\n -> \n
2732 * conversion, substitting signatures, {{subst:}} templates, etc.
2733 *
2734 * @param string $text the text to transform
2735 * @param Title &$title the Title object for the current article
2736 * @param User &$user the User object describing the current user
2737 * @param ParserOptions $options parsing options
2738 * @param bool $clearState whether to clear the parser state first
2739 * @return string the altered wiki markup
2740 * @access public
2741 */
2742 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2743 $this->mOptions = $options;
2744 $this->mTitle =& $title;
2745 $this->mOutputType = OT_WIKI;
2746
2747 if ( $clearState ) {
2748 $this->clearState();
2749 }
2750
2751 $stripState = false;
2752 $pairs = array(
2753 "\r\n" => "\n",
2754 );
2755 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2756 $text = $this->strip( $text, $stripState, false );
2757 $text = $this->pstPass2( $text, $user );
2758 $text = $this->unstrip( $text, $stripState );
2759 $text = $this->unstripNoWiki( $text, $stripState );
2760 return $text;
2761 }
2762
2763 /**
2764 * Pre-save transform helper function
2765 * @access private
2766 */
2767 function pstPass2( $text, &$user ) {
2768 global $wgContLang, $wgLocaltimezone;
2769
2770 # Variable replacement
2771 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2772 $text = $this->replaceVariables( $text );
2773
2774 # Signatures
2775 #
2776 $n = $user->getName();
2777 $k = $user->getOption( 'nickname' );
2778 if ( '' == $k ) { $k = $n; }
2779 if ( isset( $wgLocaltimezone ) ) {
2780 $oldtz = getenv( 'TZ' );
2781 putenv( 'TZ='.$wgLocaltimezone );
2782 }
2783
2784 /* Note: This is the timestamp saved as hardcoded wikitext to
2785 * the database, we use $wgContLang here in order to give
2786 * everyone the same signiture and use the default one rather
2787 * than the one selected in each users preferences.
2788 */
2789 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2790 ' (' . date( 'T' ) . ')';
2791 if ( isset( $wgLocaltimezone ) ) {
2792 putenv( 'TZ='.$oldtz );
2793 }
2794
2795 if( $user->getOption( 'fancysig' ) ) {
2796 $sigText = $k;
2797 } else {
2798 $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
2799 }
2800 $text = preg_replace( '/~~~~~/', $d, $text );
2801 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2802 $text = preg_replace( '/~~~/', $sigText, $text );
2803
2804 # Context links: [[|name]] and [[name (context)|]]
2805 #
2806 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2807 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2808 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2809 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2810
2811 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2812 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2813 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2814 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2815 $context = '';
2816 $t = $this->mTitle->getText();
2817 if ( preg_match( $conpat, $t, $m ) ) {
2818 $context = $m[2];
2819 }
2820 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2821 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2822 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2823
2824 if ( '' == $context ) {
2825 $text = preg_replace( $p2, '[[\\1]]', $text );
2826 } else {
2827 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2828 }
2829
2830 # Trim trailing whitespace
2831 # MAG_END (__END__) tag allows for trailing
2832 # whitespace to be deliberately included
2833 $text = rtrim( $text );
2834 $mw =& MagicWord::get( MAG_END );
2835 $mw->matchAndRemove( $text );
2836
2837 return $text;
2838 }
2839
2840 /**
2841 * Set up some variables which are usually set up in parse()
2842 * so that an external function can call some class members with confidence
2843 * @access public
2844 */
2845 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2846 $this->mTitle =& $title;
2847 $this->mOptions = $options;
2848 $this->mOutputType = $outputType;
2849 if ( $clearState ) {
2850 $this->clearState();
2851 }
2852 }
2853
2854 /**
2855 * Transform a MediaWiki message by replacing magic variables.
2856 *
2857 * @param string $text the text to transform
2858 * @param ParserOptions $options options
2859 * @return string the text with variables substituted
2860 * @access public
2861 */
2862 function transformMsg( $text, $options ) {
2863 global $wgTitle;
2864 static $executing = false;
2865
2866 # Guard against infinite recursion
2867 if ( $executing ) {
2868 return $text;
2869 }
2870 $executing = true;
2871
2872 $this->mTitle = $wgTitle;
2873 $this->mOptions = $options;
2874 $this->mOutputType = OT_MSG;
2875 $this->clearState();
2876 $text = $this->replaceVariables( $text );
2877
2878 $executing = false;
2879 return $text;
2880 }
2881
2882 /**
2883 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2884 * Callback will be called with the text within
2885 * Transform and return the text within
2886 * @access public
2887 */
2888 function setHook( $tag, $callback ) {
2889 $oldVal = @$this->mTagHooks[$tag];
2890 $this->mTagHooks[$tag] = $callback;
2891 return $oldVal;
2892 }
2893
2894 /**
2895 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2896 * Placeholders created in Skin::makeLinkObj()
2897 * Returns an array of links found, indexed by PDBK:
2898 * 0 - broken
2899 * 1 - normal link
2900 * 2 - stub
2901 * $options is a bit field, RLH_FOR_UPDATE to select for update
2902 */
2903 function replaceLinkHolders( &$text, $options = 0 ) {
2904 global $wgUser, $wgLinkCache;
2905 global $wgOutputReplace;
2906
2907 $fname = 'Parser::replaceLinkHolders';
2908 wfProfileIn( $fname );
2909
2910 $pdbks = array();
2911 $colours = array();
2912 $sk = $this->mOptions->getSkin();
2913
2914 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
2915 wfProfileIn( $fname.'-check' );
2916 $dbr =& wfGetDB( DB_SLAVE );
2917 $page = $dbr->tableName( 'page' );
2918 $threshold = $wgUser->getOption('stubthreshold');
2919
2920 # Sort by namespace
2921 asort( $this->mLinkHolders['namespaces'] );
2922
2923 # Generate query
2924 $query = false;
2925 foreach ( $this->mLinkHolders['namespaces'] as $key => $val ) {
2926 # Make title object
2927 $title = $this->mLinkHolders['titles'][$key];
2928
2929 # Skip invalid entries.
2930 # Result will be ugly, but prevents crash.
2931 if ( is_null( $title ) ) {
2932 continue;
2933 }
2934 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2935
2936 # Check if it's in the link cache already
2937 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2938 $colours[$pdbk] = 1;
2939 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2940 $colours[$pdbk] = 0;
2941 } else {
2942 # Not in the link cache, add it to the query
2943 if ( !isset( $current ) ) {
2944 $current = $val;
2945 $query = "SELECT page_id, page_namespace, page_title";
2946 if ( $threshold > 0 ) {
2947 $query .= ', page_len, page_is_redirect';
2948 }
2949 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2950 } elseif ( $current != $val ) {
2951 $current = $val;
2952 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2953 } else {
2954 $query .= ', ';
2955 }
2956
2957 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
2958 }
2959 }
2960 if ( $query ) {
2961 $query .= '))';
2962 if ( $options & RLH_FOR_UPDATE ) {
2963 $query .= ' FOR UPDATE';
2964 }
2965
2966 $res = $dbr->query( $query, $fname );
2967
2968 # Fetch data and form into an associative array
2969 # non-existent = broken
2970 # 1 = known
2971 # 2 = stub
2972 while ( $s = $dbr->fetchObject($res) ) {
2973 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
2974 $pdbk = $title->getPrefixedDBkey();
2975 $wgLinkCache->addGoodLinkObj( $s->page_id, $title );
2976
2977 if ( $threshold > 0 ) {
2978 $size = $s->page_len;
2979 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
2980 $colours[$pdbk] = 1;
2981 } else {
2982 $colours[$pdbk] = 2;
2983 }
2984 } else {
2985 $colours[$pdbk] = 1;
2986 }
2987 }
2988 }
2989 wfProfileOut( $fname.'-check' );
2990
2991 # Construct search and replace arrays
2992 wfProfileIn( $fname.'-construct' );
2993 $wgOutputReplace = array();
2994 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
2995 $pdbk = $pdbks[$key];
2996 $searchkey = "<!--LINK $key-->";
2997 $title = $this->mLinkHolders['titles'][$key];
2998 if ( empty( $colours[$pdbk] ) ) {
2999 $wgLinkCache->addBadLinkObj( $title );
3000 $colours[$pdbk] = 0;
3001 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3002 $this->mLinkHolders['texts'][$key],
3003 $this->mLinkHolders['queries'][$key] );
3004 } elseif ( $colours[$pdbk] == 1 ) {
3005 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3006 $this->mLinkHolders['texts'][$key],
3007 $this->mLinkHolders['queries'][$key] );
3008 } elseif ( $colours[$pdbk] == 2 ) {
3009 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3010 $this->mLinkHolders['texts'][$key],
3011 $this->mLinkHolders['queries'][$key] );
3012 }
3013 }
3014 wfProfileOut( $fname.'-construct' );
3015
3016 # Do the thing
3017 wfProfileIn( $fname.'-replace' );
3018
3019 $text = preg_replace_callback(
3020 '/(<!--LINK .*?-->)/',
3021 "wfOutputReplaceMatches",
3022 $text);
3023
3024 wfProfileOut( $fname.'-replace' );
3025 }
3026
3027 # Now process interwiki link holders
3028 # This is quite a bit simpler than internal links
3029 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3030 wfProfileIn( $fname.'-interwiki' );
3031 # Make interwiki link HTML
3032 $wgOutputReplace = array();
3033 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3034 $title = $this->mInterwikiLinkHolders['titles'][$key];
3035 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3036 }
3037
3038 $text = preg_replace_callback(
3039 '/<!--IWLINK (.*?)-->/',
3040 "wfOutputReplaceMatches",
3041 $text );
3042 wfProfileOut( $fname.'-interwiki' );
3043 }
3044
3045 wfProfileOut( $fname );
3046 return $colours;
3047 }
3048
3049 /**
3050 * Replace <!--LINK--> link placeholders with plain text of links
3051 * (not HTML-formatted).
3052 * @param string $text
3053 * @return string
3054 */
3055 function replaceLinkHoldersText( $text ) {
3056 global $wgUser, $wgLinkCache;
3057 global $wgOutputReplace;
3058
3059 $fname = 'Parser::replaceLinkHoldersText';
3060 wfProfileIn( $fname );
3061
3062 $text = preg_replace_callback(
3063 '/<!--(LINK|IWLINK) (.*?)-->/',
3064 array( &$this, 'replaceLinkHoldersTextCallback' ),
3065 $text );
3066
3067 wfProfileOut( $fname );
3068 return $text;
3069 }
3070
3071 /**
3072 * @param array $matches
3073 * @return string
3074 * @access private
3075 */
3076 function replaceLinkHoldersTextCallback( $matches ) {
3077 $type = $matches[1];
3078 $key = $matches[2];
3079 if( $type == 'LINK' ) {
3080 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3081 return $this->mLinkHolders['texts'][$key];
3082 }
3083 } elseif( $type == 'IWLINK' ) {
3084 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3085 return $this->mInterwikiLinkHolders['texts'][$key];
3086 }
3087 }
3088 return $matches[0];
3089 }
3090
3091 /**
3092 * Renders an image gallery from a text with one line per image.
3093 * text labels may be given by using |-style alternative text. E.g.
3094 * Image:one.jpg|The number "1"
3095 * Image:tree.jpg|A tree
3096 * given as text will return the HTML of a gallery with two images,
3097 * labeled 'The number "1"' and
3098 * 'A tree'.
3099 *
3100 * @static
3101 */
3102 function renderImageGallery( $text ) {
3103 # Setup the parser
3104 global $wgUser, $wgParser, $wgTitle;
3105 $parserOptions = ParserOptions::newFromUser( $wgUser );
3106
3107 global $wgLinkCache;
3108 $ig = new ImageGallery();
3109 $ig->setShowBytes( false );
3110 $ig->setShowFilename( false );
3111 $lines = explode( "\n", $text );
3112
3113 foreach ( $lines as $line ) {
3114 # match lines like these:
3115 # Image:someimage.jpg|This is some image
3116 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3117 # Skip empty lines
3118 if ( count( $matches ) == 0 ) {
3119 continue;
3120 }
3121 $nt = Title::newFromURL( $matches[1] );
3122 if( is_null( $nt ) ) {
3123 # Bogus title. Ignore these so we don't bomb out later.
3124 continue;
3125 }
3126 if ( isset( $matches[3] ) ) {
3127 $label = $matches[3];
3128 } else {
3129 $label = '';
3130 }
3131
3132 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
3133 $html = $html->mText;
3134
3135 $ig->add( new Image( $nt ), $html );
3136 $wgLinkCache->addImageLinkObj( $nt );
3137 }
3138 return $ig->toHTML();
3139 }
3140
3141 /**
3142 * Parse image options text and use it to make an image
3143 */
3144 function makeImage( &$nt, $options ) {
3145 global $wgContLang, $wgUseImageResize;
3146 global $wgUser, $wgThumbLimits;
3147
3148 $align = '';
3149
3150 # Check if the options text is of the form "options|alt text"
3151 # Options are:
3152 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3153 # * left no resizing, just left align. label is used for alt= only
3154 # * right same, but right aligned
3155 # * none same, but not aligned
3156 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3157 # * center center the image
3158 # * framed Keep original image size, no magnify-button.
3159
3160 $part = explode( '|', $options);
3161
3162 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3163 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3164 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3165 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3166 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3167 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3168 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3169 $caption = '';
3170
3171 $width = $height = $framed = $thumb = false;
3172 $manual_thumb = "" ;
3173
3174 foreach( $part as $key => $val ) {
3175 $val_parts = explode ( "=" , $val , 2 ) ;
3176 $left_part = array_shift ( $val_parts ) ;
3177 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3178 $thumb=true;
3179 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3180 # use manually specified thumbnail
3181 $thumb=true;
3182 $manual_thumb = array_shift ( $val_parts ) ;
3183 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3184 # remember to set an alignment, don't render immediately
3185 $align = 'right';
3186 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3187 # remember to set an alignment, don't render immediately
3188 $align = 'left';
3189 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3190 # remember to set an alignment, don't render immediately
3191 $align = 'center';
3192 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3193 # remember to set an alignment, don't render immediately
3194 $align = 'none';
3195 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3196 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3197 # $match is the image width in pixels
3198 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3199 $width = intval( $m[1] );
3200 $height = intval( $m[2] );
3201 } else {
3202 $width = intval($match);
3203 }
3204 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3205 $framed=true;
3206 } else {
3207 $caption = $val;
3208 }
3209 }
3210 # Strip bad stuff out of the alt text
3211 $alt = $this->replaceLinkHoldersText( $caption );
3212 $alt = Sanitizer::stripAllTags( $alt );
3213
3214 # Linker does the rest
3215 $sk =& $this->mOptions->getSkin();
3216 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3217 }
3218 }
3219
3220 /**
3221 * @todo document
3222 * @package MediaWiki
3223 */
3224 class ParserOutput
3225 {
3226 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3227 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3228 var $mVersion; # Compatibility check
3229 var $mTitleText; # title text of the chosen language variant
3230
3231 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3232 $containsOldMagic = false, $titletext = '' )
3233 {
3234 $this->mText = $text;
3235 $this->mLanguageLinks = $languageLinks;
3236 $this->mCategoryLinks = $categoryLinks;
3237 $this->mContainsOldMagic = $containsOldMagic;
3238 $this->mCacheTime = '';
3239 $this->mVersion = MW_PARSER_VERSION;
3240 $this->mTitleText = $titletext;
3241 }
3242
3243 function getText() { return $this->mText; }
3244 function getLanguageLinks() { return $this->mLanguageLinks; }
3245 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
3246 function getCacheTime() { return $this->mCacheTime; }
3247 function getTitleText() { return $this->mTitleText; }
3248 function containsOldMagic() { return $this->mContainsOldMagic; }
3249 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3250 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3251 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
3252 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3253 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3254 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3255
3256 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
3257
3258 function merge( $other ) {
3259 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3260 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3261 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3262 }
3263
3264 /**
3265 * Return true if this cached output object predates the global or
3266 * per-article cache invalidation timestamps, or if it comes from
3267 * an incompatible older version.
3268 *
3269 * @param string $touched the affected article's last touched timestamp
3270 * @return bool
3271 * @access public
3272 */
3273 function expired( $touched ) {
3274 global $wgCacheEpoch;
3275 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3276 $this->getCacheTime() <= $touched ||
3277 $this->getCacheTime() <= $wgCacheEpoch ||
3278 !isset( $this->mVersion ) ||
3279 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3280 }
3281 }
3282
3283 /**
3284 * Set options of the Parser
3285 * @todo document
3286 * @package MediaWiki
3287 */
3288 class ParserOptions
3289 {
3290 # All variables are private
3291 var $mUseTeX; # Use texvc to expand <math> tags
3292 var $mUseDynamicDates; # Use DateFormatter to format dates
3293 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3294 var $mAllowExternalImages; # Allow external images inline
3295 var $mSkin; # Reference to the preferred skin
3296 var $mDateFormat; # Date format index
3297 var $mEditSection; # Create "edit section" links
3298 var $mNumberHeadings; # Automatically number headings
3299 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3300
3301 function getUseTeX() { return $this->mUseTeX; }
3302 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3303 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3304 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3305 function getSkin() { return $this->mSkin; }
3306 function getDateFormat() { return $this->mDateFormat; }
3307 function getEditSection() { return $this->mEditSection; }
3308 function getNumberHeadings() { return $this->mNumberHeadings; }
3309 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3310
3311
3312 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3313 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3314 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3315 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3316 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3317 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3318 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3319 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3320
3321 function setSkin( &$x ) { $this->mSkin =& $x; }
3322
3323 function ParserOptions() {
3324 global $wgUser;
3325 $this->initialiseFromUser( $wgUser );
3326 }
3327
3328 /**
3329 * Get parser options
3330 * @static
3331 */
3332 function newFromUser( &$user ) {
3333 $popts = new ParserOptions;
3334 $popts->initialiseFromUser( $user );
3335 return $popts;
3336 }
3337
3338 /** Get user options */
3339 function initialiseFromUser( &$userInput ) {
3340 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3341 $wgAllowSpecialInclusion;
3342 $fname = 'ParserOptions::initialiseFromUser';
3343 wfProfileIn( $fname );
3344 if ( !$userInput ) {
3345 $user = new User;
3346 $user->setLoaded( true );
3347 } else {
3348 $user =& $userInput;
3349 }
3350
3351 $this->mUseTeX = $wgUseTeX;
3352 $this->mUseDynamicDates = $wgUseDynamicDates;
3353 $this->mInterwikiMagic = $wgInterwikiMagic;
3354 $this->mAllowExternalImages = $wgAllowExternalImages;
3355 wfProfileIn( $fname.'-skin' );
3356 $this->mSkin =& $user->getSkin();
3357 wfProfileOut( $fname.'-skin' );
3358 $this->mDateFormat = $user->getOption( 'date' );
3359 $this->mEditSection = $user->getOption( 'editsection' );
3360 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3361 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
3362 wfProfileOut( $fname );
3363 }
3364 }
3365
3366 /**
3367 * Callback function used by Parser::replaceLinkHolders()
3368 * to substitute link placeholders.
3369 */
3370 function &wfOutputReplaceMatches( $matches ) {
3371 global $wgOutputReplace;
3372 return $wgOutputReplace[$matches[1]];
3373 }
3374
3375 /**
3376 * Return the total number of articles
3377 */
3378 function wfNumberOfArticles() {
3379 global $wgNumberOfArticles;
3380
3381 wfLoadSiteStats();
3382 return $wgNumberOfArticles;
3383 }
3384
3385 /**
3386 * Get various statistics from the database
3387 * @private
3388 */
3389 function wfLoadSiteStats() {
3390 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3391 $fname = 'wfLoadSiteStats';
3392
3393 if ( -1 != $wgNumberOfArticles ) return;
3394 $dbr =& wfGetDB( DB_SLAVE );
3395 $s = $dbr->selectRow( 'site_stats',
3396 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3397 array( 'ss_row_id' => 1 ), $fname
3398 );
3399
3400 if ( $s === false ) {
3401 return;
3402 } else {
3403 $wgTotalViews = $s->ss_total_views;
3404 $wgTotalEdits = $s->ss_total_edits;
3405 $wgNumberOfArticles = $s->ss_good_articles;
3406 }
3407 }
3408
3409 /**
3410 * Escape html tags
3411 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3412 *
3413 * @param string $in Text that might contain HTML tags
3414 * @return string Escaped string
3415 */
3416 function wfEscapeHTMLTagsOnly( $in ) {
3417 return str_replace(
3418 array( '"', '>', '<' ),
3419 array( '&quot;', '&gt;', '&lt;' ),
3420 $in );
3421 }
3422
3423 ?>