quotes. Nice "require" in a foreach() need a fix ;)
[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 # the position of the convert() call should not be changed. it
211 # assumes that the links are all replaces and the only thing left
212 # is the <nowiki> mark.
213 $text = $wgContLang->convert($text);
214 $this->mOutput->setTitleText($wgContLang->getParsedTitle());
215
216 $text = $this->unstripNoWiki( $text, $this->mStripState );
217
218 $text = Sanitizer::normalizeCharReferences( $text );
219 global $wgUseTidy;
220 if ($wgUseTidy) {
221 $text = Parser::tidy($text);
222 }
223
224 $this->mOutput->setText( $text );
225 wfProfileOut( $fname );
226 return $this->mOutput;
227 }
228
229 /**
230 * Get a random string
231 *
232 * @access private
233 * @static
234 */
235 function getRandomString() {
236 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
237 }
238
239 /**
240 * Replaces all occurrences of <$tag>content</$tag> in the text
241 * with a random marker and returns the new text. the output parameter
242 * $content will be an associative array filled with data on the form
243 * $unique_marker => content.
244 *
245 * If $content is already set, the additional entries will be appended
246 * If $tag is set to STRIP_COMMENTS, the function will extract
247 * <!-- HTML comments -->
248 *
249 * @access private
250 * @static
251 */
252 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
253 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
254 if ( !$content ) {
255 $content = array( );
256 }
257 $n = 1;
258 $stripped = '';
259
260 if ( !$tags ) {
261 $tags = array( );
262 }
263
264 if ( !$params ) {
265 $params = array( );
266 }
267
268 if( $tag == STRIP_COMMENTS ) {
269 $start = '/<!--()/';
270 $end = '/-->/';
271 } else {
272 $start = "/<$tag(\\s+[^>]*|\\s*)>/i";
273 $end = "/<\\/$tag\\s*>/i";
274 }
275
276 while ( '' != $text ) {
277 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
278 $stripped .= $p[0];
279 if( count( $p ) < 3 ) {
280 break;
281 }
282 $attributes = $p[1];
283 $inside = $p[2];
284
285 $marker = $rnd . sprintf('%08X', $n++);
286 $stripped .= $marker;
287
288 $tags[$marker] = "<$tag$attributes>";
289 $params[$marker] = Sanitizer::decodeTagAttributes( $attributes );
290
291 $q = preg_split( $end, $inside, 2 );
292 $content[$marker] = $q[0];
293 if( count( $q ) < 1 ) {
294 # No end tag -- let it run out to the end of the text.
295 break;
296 } else {
297 $text = $q[1];
298 }
299 }
300 return $stripped;
301 }
302
303 /**
304 * Wrapper function for extractTagsAndParams
305 * for cases where $tags and $params isn't needed
306 * i.e. where tags will never have params, like <nowiki>
307 *
308 * @access private
309 * @static
310 */
311 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
312 $dummy_tags = array();
313 $dummy_params = array();
314
315 return Parser::extractTagsAndParams( $tag, $text, $content,
316 $dummy_tags, $dummy_params, $uniq_prefix );
317 }
318
319 /**
320 * Strips and renders nowiki, pre, math, hiero
321 * If $render is set, performs necessary rendering operations on plugins
322 * Returns the text, and fills an array with data needed in unstrip()
323 * If the $state is already a valid strip state, it adds to the state
324 *
325 * @param bool $stripcomments when set, HTML comments <!-- like this -->
326 * will be stripped in addition to other tags. This is important
327 * for section editing, where these comments cause confusion when
328 * counting the sections in the wikisource
329 *
330 * @access private
331 */
332 function strip( $text, &$state, $stripcomments = false ) {
333 $render = ($this->mOutputType == OT_HTML);
334 $html_content = array();
335 $nowiki_content = array();
336 $math_content = array();
337 $pre_content = array();
338 $comment_content = array();
339 $ext_content = array();
340 $ext_tags = array();
341 $ext_params = array();
342 $gallery_content = array();
343
344 # Replace any instances of the placeholders
345 $uniq_prefix = UNIQ_PREFIX;
346 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
347
348 # html
349 global $wgRawHtml;
350 if( $wgRawHtml ) {
351 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
352 foreach( $html_content as $marker => $content ) {
353 if ($render ) {
354 # Raw and unchecked for validity.
355 $html_content[$marker] = $content;
356 } else {
357 $html_content[$marker] = '<html>'.$content.'</html>';
358 }
359 }
360 }
361
362 # nowiki
363 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
364 foreach( $nowiki_content as $marker => $content ) {
365 if( $render ){
366 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
367 } else {
368 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
369 }
370 }
371
372 # math
373 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
374 foreach( $math_content as $marker => $content ){
375 if( $render ) {
376 if( $this->mOptions->getUseTeX() ) {
377 $math_content[$marker] = renderMath( $content );
378 } else {
379 $math_content[$marker] = '&lt;math&gt;'.$content.'&lt;math&gt;';
380 }
381 } else {
382 $math_content[$marker] = '<math>'.$content.'</math>';
383 }
384 }
385
386 # pre
387 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
388 foreach( $pre_content as $marker => $content ){
389 if( $render ){
390 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
391 } else {
392 $pre_content[$marker] = '<pre>'.$content.'</pre>';
393 }
394 }
395
396 # gallery
397 $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
398 foreach( $gallery_content as $marker => $content ) {
399 require_once( 'ImageGallery.php' ); // FIXME require in a foreach ?
400 if ( $render ) {
401 $gallery_content[$marker] = Parser::renderImageGallery( $content );
402 } else {
403 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
404 }
405 }
406
407 # Comments
408 if($stripcomments) {
409 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
410 foreach( $comment_content as $marker => $content ){
411 $comment_content[$marker] = '<!--'.$content.'-->';
412 }
413 }
414
415 # Extensions
416 foreach ( $this->mTagHooks as $tag => $callback ) {
417 $ext_content[$tag] = array();
418 $text = Parser::extractTagsAndParams( $tag, $text, $ext_content[$tag],
419 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
420 foreach( $ext_content[$tag] as $marker => $content ) {
421 $full_tag = $ext_tags[$tag][$marker];
422 $params = $ext_params[$tag][$marker];
423 if ( $render ) {
424 $ext_content[$tag][$marker] = $callback( $content, $params );
425 } else {
426 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
427 }
428 }
429 }
430
431 # Merge state with the pre-existing state, if there is one
432 if ( $state ) {
433 $state['html'] = $state['html'] + $html_content;
434 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
435 $state['math'] = $state['math'] + $math_content;
436 $state['pre'] = $state['pre'] + $pre_content;
437 $state['comment'] = $state['comment'] + $comment_content;
438 $state['gallery'] = $state['gallery'] + $gallery_content;
439
440 foreach( $ext_content as $tag => $array ) {
441 if ( array_key_exists( $tag, $state ) ) {
442 $state[$tag] = $state[$tag] + $array;
443 }
444 }
445 } else {
446 $state = array(
447 'html' => $html_content,
448 'nowiki' => $nowiki_content,
449 'math' => $math_content,
450 'pre' => $pre_content,
451 'comment' => $comment_content,
452 'gallery' => $gallery_content,
453 ) + $ext_content;
454 }
455 return $text;
456 }
457
458 /**
459 * restores pre, math, and hiero removed by strip()
460 *
461 * always call unstripNoWiki() after this one
462 * @access private
463 */
464 function unstrip( $text, &$state ) {
465 # Must expand in reverse order, otherwise nested tags will be corrupted
466 $contentDict = end( $state );
467 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
468 if( key($state) != 'nowiki' && key($state) != 'html') {
469 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
470 $text = str_replace( key( $contentDict ), $content, $text );
471 }
472 }
473 }
474
475 return $text;
476 }
477
478 /**
479 * always call this after unstrip() to preserve the order
480 *
481 * @access private
482 */
483 function unstripNoWiki( $text, &$state ) {
484 # Must expand in reverse order, otherwise nested tags will be corrupted
485 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
486 $text = str_replace( key( $state['nowiki'] ), $content, $text );
487 }
488
489 global $wgRawHtml;
490 if ($wgRawHtml) {
491 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
492 $text = str_replace( key( $state['html'] ), $content, $text );
493 }
494 }
495
496 return $text;
497 }
498
499 /**
500 * Add an item to the strip state
501 * Returns the unique tag which must be inserted into the stripped text
502 * The tag will be replaced with the original text in unstrip()
503 *
504 * @access private
505 */
506 function insertStripItem( $text, &$state ) {
507 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
508 if ( !$state ) {
509 $state = array(
510 'html' => array(),
511 'nowiki' => array(),
512 'math' => array(),
513 'pre' => array()
514 );
515 }
516 $state['item'][$rnd] = $text;
517 return $rnd;
518 }
519
520 /**
521 * Interface with html tidy, used if $wgUseTidy = true.
522 * If tidy isn't able to correct the markup, the original will be
523 * returned in all its glory with a warning comment appended.
524 *
525 * Either the external tidy program or the in-process tidy extension
526 * will be used depending on availability. Override the default
527 * $wgTidyInternal setting to disable the internal if it's not working.
528 *
529 * @param string $text Hideous HTML input
530 * @return string Corrected HTML output
531 * @access public
532 * @static
533 */
534 function tidy( $text ) {
535 global $wgTidyInternal;
536 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
537 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
538 '<head><title>test</title></head><body>'.$text.'</body></html>';
539 if( $wgTidyInternal ) {
540 $correctedtext = Parser::internalTidy( $wrappedtext );
541 } else {
542 $correctedtext = Parser::externalTidy( $wrappedtext );
543 }
544 if( is_null( $correctedtext ) ) {
545 wfDebug( "Tidy error detected!\n" );
546 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
547 }
548 return $correctedtext;
549 }
550
551 /**
552 * Spawn an external HTML tidy process and get corrected markup back from it.
553 *
554 * @access private
555 * @static
556 */
557 function externalTidy( $text ) {
558 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
559 $fname = 'Parser::externalTidy';
560 wfProfileIn( $fname );
561
562 $cleansource = '';
563 $opts = ' -utf8';
564
565 $descriptorspec = array(
566 0 => array('pipe', 'r'),
567 1 => array('pipe', 'w'),
568 2 => array('file', '/dev/null', 'a')
569 );
570 $pipes = array();
571 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
572 if (is_resource($process)) {
573 fwrite($pipes[0], $text);
574 fclose($pipes[0]);
575 while (!feof($pipes[1])) {
576 $cleansource .= fgets($pipes[1], 1024);
577 }
578 fclose($pipes[1]);
579 proc_close($process);
580 }
581
582 wfProfileOut( $fname );
583
584 if( $cleansource == '' && $text != '') {
585 // Some kind of error happened, so we couldn't get the corrected text.
586 // Just give up; we'll use the source text and append a warning.
587 return null;
588 } else {
589 return $cleansource;
590 }
591 }
592
593 /**
594 * Use the HTML tidy PECL extension to use the tidy library in-process,
595 * saving the overhead of spawning a new process. Currently written to
596 * the PHP 4.3.x version of the extension, may not work on PHP 5.
597 *
598 * 'pear install tidy' should be able to compile the extension module.
599 *
600 * @access private
601 * @static
602 */
603 function internalTidy( $text ) {
604 global $wgTidyConf;
605 $fname = 'Parser::internalTidy';
606 wfProfileIn( $fname );
607
608 tidy_load_config( $wgTidyConf );
609 tidy_set_encoding( 'utf8' );
610 tidy_parse_string( $text );
611 tidy_clean_repair();
612 if( tidy_get_status() == 2 ) {
613 // 2 is magic number for fatal error
614 // http://www.php.net/manual/en/function.tidy-get-status.php
615 $cleansource = null;
616 } else {
617 $cleansource = tidy_get_output();
618 }
619 wfProfileOut( $fname );
620 return $cleansource;
621 }
622
623 /**
624 * parse the wiki syntax used to render tables
625 *
626 * @access private
627 */
628 function doTableStuff ( $t ) {
629 $fname = 'Parser::doTableStuff';
630 wfProfileIn( $fname );
631
632 $t = explode ( "\n" , $t ) ;
633 $td = array () ; # Is currently a td tag open?
634 $ltd = array () ; # Was it TD or TH?
635 $tr = array () ; # Is currently a tr tag open?
636 $ltr = array () ; # tr attributes
637 $indent_level = 0; # indent level of the table
638 foreach ( $t AS $k => $x )
639 {
640 $x = trim ( $x ) ;
641 $fc = substr ( $x , 0 , 1 ) ;
642 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
643 $indent_level = strlen( $matches[1] );
644 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
645 '<table' . Sanitizer::fixTagAttributes ( $matches[2], 'table' ) . '>' ;
646 array_push ( $td , false ) ;
647 array_push ( $ltd , '' ) ;
648 array_push ( $tr , false ) ;
649 array_push ( $ltr , '' ) ;
650 }
651 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
652 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
653 $z = "</table>" . substr ( $x , 2);
654 $l = array_pop ( $ltd ) ;
655 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
656 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
657 array_pop ( $ltr ) ;
658 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
659 }
660 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
661 $x = substr ( $x , 1 ) ;
662 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
663 $z = '' ;
664 $l = array_pop ( $ltd ) ;
665 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
666 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
667 array_pop ( $ltr ) ;
668 $t[$k] = $z ;
669 array_push ( $tr , false ) ;
670 array_push ( $td , false ) ;
671 array_push ( $ltd , '' ) ;
672 array_push ( $ltr , Sanitizer::fixTagAttributes ( $x, 'tr' ) ) ;
673 }
674 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
675 # $x is a table row
676 if ( '|+' == substr ( $x , 0 , 2 ) ) {
677 $fc = '+' ;
678 $x = substr ( $x , 1 ) ;
679 }
680 $after = substr ( $x , 1 ) ;
681 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
682 $after = explode ( '||' , $after ) ;
683 $t[$k] = '' ;
684
685 # Loop through each table cell
686 foreach ( $after AS $theline )
687 {
688 $z = '' ;
689 if ( $fc != '+' )
690 {
691 $tra = array_pop ( $ltr ) ;
692 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
693 array_push ( $tr , true ) ;
694 array_push ( $ltr , '' ) ;
695 }
696
697 $l = array_pop ( $ltd ) ;
698 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
699 if ( $fc == '|' ) $l = 'td' ;
700 else if ( $fc == '!' ) $l = 'th' ;
701 else if ( $fc == '+' ) $l = 'caption' ;
702 else $l = '' ;
703 array_push ( $ltd , $l ) ;
704
705 # Cell parameters
706 $y = explode ( '|' , $theline , 2 ) ;
707 # Note that a '|' inside an invalid link should not
708 # be mistaken as delimiting cell parameters
709 if ( strpos( $y[0], '[[' ) !== false ) {
710 $y = array ($theline);
711 }
712 if ( count ( $y ) == 1 )
713 $y = "{$z}<{$l}>{$y[0]}" ;
714 else $y = $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($y[0], $l).">{$y[1]}" ;
715 $t[$k] .= $y ;
716 array_push ( $td , true ) ;
717 }
718 }
719 }
720
721 # Closing open td, tr && table
722 while ( count ( $td ) > 0 )
723 {
724 if ( array_pop ( $td ) ) $t[] = '</td>' ;
725 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
726 $t[] = '</table>' ;
727 }
728
729 $t = implode ( "\n" , $t ) ;
730 wfProfileOut( $fname );
731 return $t ;
732 }
733
734 /**
735 * Helper function for parse() that transforms wiki markup into
736 * HTML. Only called for $mOutputType == OT_HTML.
737 *
738 * @access private
739 */
740 function internalParse( $text ) {
741 global $wgContLang;
742 $args = array();
743 $isMain = true;
744 $fname = 'Parser::internalParse';
745 wfProfileIn( $fname );
746
747 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ) );
748 $text = $this->replaceVariables( $text, $args );
749
750 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
751
752 $text = $this->doHeadings( $text );
753 if($this->mOptions->getUseDynamicDates()) {
754 $df =& DateFormatter::getInstance();
755 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
756 }
757 $text = $this->doAllQuotes( $text );
758 $text = $this->replaceInternalLinks( $text );
759 $text = $this->replaceExternalLinks( $text );
760
761 # replaceInternalLinks may sometimes leave behind
762 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
763 $text = str_replace("http-noparse://","http://",$text);
764
765 $text = $this->doMagicLinks( $text );
766 $text = $this->doTableStuff( $text );
767 $text = $this->formatHeadings( $text, $isMain );
768
769 wfProfileOut( $fname );
770 return $text;
771 }
772
773 /**
774 * Replace special strings like "ISBN xxx" and "RFC xxx" with
775 * magic external links.
776 *
777 * @access private
778 */
779 function &doMagicLinks( &$text ) {
780 $text = $this->magicISBN( $text );
781 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
782 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
783 return $text;
784 }
785
786 /**
787 * Parse ^^ tokens and return html
788 *
789 * @access private
790 */
791 function doExponent( $text ) {
792 $fname = 'Parser::doExponent';
793 wfProfileIn( $fname );
794 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
795 wfProfileOut( $fname );
796 return $text;
797 }
798
799 /**
800 * Parse headers and return html
801 *
802 * @access private
803 */
804 function doHeadings( $text ) {
805 $fname = 'Parser::doHeadings';
806 wfProfileIn( $fname );
807 for ( $i = 6; $i >= 1; --$i ) {
808 $h = substr( '======', 0, $i );
809 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
810 "<h{$i}>\\1</h{$i}>\\2", $text );
811 }
812 wfProfileOut( $fname );
813 return $text;
814 }
815
816 /**
817 * Replace single quotes with HTML markup
818 * @access private
819 * @return string the altered text
820 */
821 function doAllQuotes( $text ) {
822 $fname = 'Parser::doAllQuotes';
823 wfProfileIn( $fname );
824 $outtext = '';
825 $lines = explode( "\n", $text );
826 foreach ( $lines as $line ) {
827 $outtext .= $this->doQuotes ( $line ) . "\n";
828 }
829 $outtext = substr($outtext, 0,-1);
830 wfProfileOut( $fname );
831 return $outtext;
832 }
833
834 /**
835 * Helper function for doAllQuotes()
836 * @access private
837 */
838 function doQuotes( $text ) {
839 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
840 if ( count( $arr ) == 1 )
841 return $text;
842 else
843 {
844 # First, do some preliminary work. This may shift some apostrophes from
845 # being mark-up to being text. It also counts the number of occurrences
846 # of bold and italics mark-ups.
847 $i = 0;
848 $numbold = 0;
849 $numitalics = 0;
850 foreach ( $arr as $r )
851 {
852 if ( ( $i % 2 ) == 1 )
853 {
854 # If there are ever four apostrophes, assume the first is supposed to
855 # be text, and the remaining three constitute mark-up for bold text.
856 if ( strlen( $arr[$i] ) == 4 )
857 {
858 $arr[$i-1] .= "'";
859 $arr[$i] = "'''";
860 }
861 # If there are more than 5 apostrophes in a row, assume they're all
862 # text except for the last 5.
863 else if ( strlen( $arr[$i] ) > 5 )
864 {
865 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
866 $arr[$i] = "'''''";
867 }
868 # Count the number of occurrences of bold and italics mark-ups.
869 # We are not counting sequences of five apostrophes.
870 if ( strlen( $arr[$i] ) == 2 ) $numitalics++; else
871 if ( strlen( $arr[$i] ) == 3 ) $numbold++; else
872 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
873 }
874 $i++;
875 }
876
877 # If there is an odd number of both bold and italics, it is likely
878 # that one of the bold ones was meant to be an apostrophe followed
879 # by italics. Which one we cannot know for certain, but it is more
880 # likely to be one that has a single-letter word before it.
881 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
882 {
883 $i = 0;
884 $firstsingleletterword = -1;
885 $firstmultiletterword = -1;
886 $firstspace = -1;
887 foreach ( $arr as $r )
888 {
889 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
890 {
891 $x1 = substr ($arr[$i-1], -1);
892 $x2 = substr ($arr[$i-1], -2, 1);
893 if ($x1 == ' ') {
894 if ($firstspace == -1) $firstspace = $i;
895 } else if ($x2 == ' ') {
896 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
897 } else {
898 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
899 }
900 }
901 $i++;
902 }
903
904 # If there is a single-letter word, use it!
905 if ($firstsingleletterword > -1)
906 {
907 $arr [ $firstsingleletterword ] = "''";
908 $arr [ $firstsingleletterword-1 ] .= "'";
909 }
910 # If not, but there's a multi-letter word, use that one.
911 else if ($firstmultiletterword > -1)
912 {
913 $arr [ $firstmultiletterword ] = "''";
914 $arr [ $firstmultiletterword-1 ] .= "'";
915 }
916 # ... otherwise use the first one that has neither.
917 # (notice that it is possible for all three to be -1 if, for example,
918 # there is only one pentuple-apostrophe in the line)
919 else if ($firstspace > -1)
920 {
921 $arr [ $firstspace ] = "''";
922 $arr [ $firstspace-1 ] .= "'";
923 }
924 }
925
926 # Now let's actually convert our apostrophic mush to HTML!
927 $output = '';
928 $buffer = '';
929 $state = '';
930 $i = 0;
931 foreach ($arr as $r)
932 {
933 if (($i % 2) == 0)
934 {
935 if ($state == 'both')
936 $buffer .= $r;
937 else
938 $output .= $r;
939 }
940 else
941 {
942 if (strlen ($r) == 2)
943 {
944 if ($state == 'i')
945 { $output .= '</i>'; $state = ''; }
946 else if ($state == 'bi')
947 { $output .= '</i>'; $state = 'b'; }
948 else if ($state == 'ib')
949 { $output .= '</b></i><b>'; $state = 'b'; }
950 else if ($state == 'both')
951 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
952 else # $state can be 'b' or ''
953 { $output .= '<i>'; $state .= 'i'; }
954 }
955 else if (strlen ($r) == 3)
956 {
957 if ($state == 'b')
958 { $output .= '</b>'; $state = ''; }
959 else if ($state == 'bi')
960 { $output .= '</i></b><i>'; $state = 'i'; }
961 else if ($state == 'ib')
962 { $output .= '</b>'; $state = 'i'; }
963 else if ($state == 'both')
964 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
965 else # $state can be 'i' or ''
966 { $output .= '<b>'; $state .= 'b'; }
967 }
968 else if (strlen ($r) == 5)
969 {
970 if ($state == 'b')
971 { $output .= '</b><i>'; $state = 'i'; }
972 else if ($state == 'i')
973 { $output .= '</i><b>'; $state = 'b'; }
974 else if ($state == 'bi')
975 { $output .= '</i></b>'; $state = ''; }
976 else if ($state == 'ib')
977 { $output .= '</b></i>'; $state = ''; }
978 else if ($state == 'both')
979 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
980 else # ($state == '')
981 { $buffer = ''; $state = 'both'; }
982 }
983 }
984 $i++;
985 }
986 # Now close all remaining tags. Notice that the order is important.
987 if ($state == 'b' || $state == 'ib')
988 $output .= '</b>';
989 if ($state == 'i' || $state == 'bi' || $state == 'ib')
990 $output .= '</i>';
991 if ($state == 'bi')
992 $output .= '</b>';
993 if ($state == 'both')
994 $output .= '<b><i>'.$buffer.'</i></b>';
995 return $output;
996 }
997 }
998
999 /**
1000 * Replace external links
1001 *
1002 * Note: this is all very hackish and the order of execution matters a lot.
1003 * Make sure to run maintenance/parserTests.php if you change this code.
1004 *
1005 * @access private
1006 */
1007 function replaceExternalLinks( $text ) {
1008 global $wgContLang;
1009 $fname = 'Parser::replaceExternalLinks';
1010 wfProfileIn( $fname );
1011
1012 $sk =& $this->mOptions->getSkin();
1013
1014 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1015
1016 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1017
1018 $i = 0;
1019 while ( $i<count( $bits ) ) {
1020 $url = $bits[$i++];
1021 $protocol = $bits[$i++];
1022 $text = $bits[$i++];
1023 $trail = $bits[$i++];
1024
1025 # The characters '<' and '>' (which were escaped by
1026 # removeHTMLtags()) should not be included in
1027 # URLs, per RFC 2396.
1028 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1029 $text = substr($url, $m2[0][1]) . ' ' . $text;
1030 $url = substr($url, 0, $m2[0][1]);
1031 }
1032
1033 # If the link text is an image URL, replace it with an <img> tag
1034 # This happened by accident in the original parser, but some people used it extensively
1035 $img = $this->maybeMakeExternalImage( $text );
1036 if ( $img !== false ) {
1037 $text = $img;
1038 }
1039
1040 $dtrail = '';
1041
1042 # Set linktype for CSS - if URL==text, link is essentially free
1043 $linktype = ($text == $url) ? 'free' : 'text';
1044
1045 # No link text, e.g. [http://domain.tld/some.link]
1046 if ( $text == '' ) {
1047 # Autonumber if allowed
1048 if ( strpos( HTTP_PROTOCOLS, $protocol ) !== false ) {
1049 $text = '[' . ++$this->mAutonumber . ']';
1050 $linktype = 'autonumber';
1051 } else {
1052 # Otherwise just use the URL
1053 $text = htmlspecialchars( $url );
1054 $linktype = 'free';
1055 }
1056 } else {
1057 # Have link text, e.g. [http://domain.tld/some.link text]s
1058 # Check for trail
1059 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1060 }
1061
1062 $text = $wgContLang->markNoConversion($text);
1063
1064 # Replace &amp; from obsolete syntax with &.
1065 # All HTML entities will be escaped by makeExternalLink()
1066 # or maybeMakeExternalImage()
1067 $url = str_replace( '&amp;', '&', $url );
1068
1069 # Process the trail (i.e. everything after this link up until start of the next link),
1070 # replacing any non-bracketed links
1071 $trail = $this->replaceFreeExternalLinks( $trail );
1072
1073
1074 # Use the encoded URL
1075 # This means that users can paste URLs directly into the text
1076 # Funny characters like &ouml; aren't valid in URLs anyway
1077 # This was changed in August 2004
1078 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1079 }
1080
1081 wfProfileOut( $fname );
1082 return $s;
1083 }
1084
1085 /**
1086 * Replace anything that looks like a URL with a link
1087 * @access private
1088 */
1089 function replaceFreeExternalLinks( $text ) {
1090 global $wgContLang;
1091 $fname = 'Parser::replaceFreeExternalLinks';
1092 wfProfileIn( $fname );
1093
1094 $bits = preg_split( '/(\b(?:'.URL_PROTOCOLS.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1095 $s = array_shift( $bits );
1096 $i = 0;
1097
1098 $sk =& $this->mOptions->getSkin();
1099
1100 while ( $i < count( $bits ) ){
1101 $protocol = $bits[$i++];
1102 $remainder = $bits[$i++];
1103
1104 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1105 # Found some characters after the protocol that look promising
1106 $url = $protocol . $m[1];
1107 $trail = $m[2];
1108
1109 # The characters '<' and '>' (which were escaped by
1110 # removeHTMLtags()) should not be included in
1111 # URLs, per RFC 2396.
1112 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1113 $trail = substr($url, $m2[0][1]) . $trail;
1114 $url = substr($url, 0, $m2[0][1]);
1115 }
1116
1117 # Move trailing punctuation to $trail
1118 $sep = ',;\.:!?';
1119 # If there is no left bracket, then consider right brackets fair game too
1120 if ( strpos( $url, '(' ) === false ) {
1121 $sep .= ')';
1122 }
1123
1124 $numSepChars = strspn( strrev( $url ), $sep );
1125 if ( $numSepChars ) {
1126 $trail = substr( $url, -$numSepChars ) . $trail;
1127 $url = substr( $url, 0, -$numSepChars );
1128 }
1129
1130 # Replace &amp; from obsolete syntax with &.
1131 # All HTML entities will be escaped by makeExternalLink()
1132 # or maybeMakeExternalImage()
1133 $url = str_replace( '&amp;', '&', $url );
1134
1135 # Is this an external image?
1136 $text = $this->maybeMakeExternalImage( $url );
1137 if ( $text === false ) {
1138 # Not an image, make a link
1139 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1140 }
1141 $s .= $text . $trail;
1142 } else {
1143 $s .= $protocol . $remainder;
1144 }
1145 }
1146 wfProfileOut();
1147 return $s;
1148 }
1149
1150 /**
1151 * make an image if it's allowed
1152 * @access private
1153 */
1154 function maybeMakeExternalImage( $url ) {
1155 $sk =& $this->mOptions->getSkin();
1156 $text = false;
1157 if ( $this->mOptions->getAllowExternalImages() ) {
1158 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1159 # Image found
1160 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1161 }
1162 }
1163 return $text;
1164 }
1165
1166 /**
1167 * Process [[ ]] wikilinks
1168 *
1169 * @access private
1170 */
1171 function replaceInternalLinks( $s ) {
1172 global $wgContLang, $wgLinkCache;
1173 static $fname = 'Parser::replaceInternalLinks' ;
1174
1175 wfProfileIn( $fname );
1176
1177 wfProfileIn( $fname.'-setup' );
1178 static $tc = FALSE;
1179 # the % is needed to support urlencoded titles as well
1180 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1181
1182 $sk =& $this->mOptions->getSkin();
1183
1184 #split the entire text string on occurences of [[
1185 $a = explode( '[[', ' ' . $s );
1186 #get the first element (all text up to first [[), and remove the space we added
1187 $s = array_shift( $a );
1188 $s = substr( $s, 1 );
1189
1190 # Match a link having the form [[namespace:link|alternate]]trail
1191 static $e1 = FALSE;
1192 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1193 # Match cases where there is no "]]", which might still be images
1194 static $e1_img = FALSE;
1195 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1196 # Match the end of a line for a word that's not followed by whitespace,
1197 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1198 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1199
1200 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1201
1202 if( is_null( $this->mTitle ) ) {
1203 wfDebugDieBacktrace( 'nooo' );
1204 }
1205 $nottalk = !$this->mTitle->isTalkPage();
1206
1207 if ( $useLinkPrefixExtension ) {
1208 if ( preg_match( $e2, $s, $m ) ) {
1209 $first_prefix = $m[2];
1210 $s = $m[1];
1211 } else {
1212 $first_prefix = false;
1213 }
1214 } else {
1215 $prefix = '';
1216 }
1217
1218 $selflink = $this->mTitle->getPrefixedText();
1219 wfProfileOut( $fname.'-setup' );
1220
1221 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1222 $useSubpages = $this->areSubpagesAllowed();
1223
1224 # Loop for each link
1225 for ($k = 0; isset( $a[$k] ); $k++) {
1226 $line = $a[$k];
1227 if ( $useLinkPrefixExtension ) {
1228 wfProfileIn( $fname.'-prefixhandling' );
1229 if ( preg_match( $e2, $s, $m ) ) {
1230 $prefix = $m[2];
1231 $s = $m[1];
1232 } else {
1233 $prefix='';
1234 }
1235 # first link
1236 if($first_prefix) {
1237 $prefix = $first_prefix;
1238 $first_prefix = false;
1239 }
1240 wfProfileOut( $fname.'-prefixhandling' );
1241 }
1242
1243 $might_be_img = false;
1244
1245 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1246 $text = $m[2];
1247 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1248 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1249 # the real problem is with the $e1 regex
1250 # See bug 1300.
1251 #
1252 # Still some problems for cases where the ] is meant to be outside punctuation,
1253 # and no image is in sight. See bug 2095.
1254 #
1255 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1256 $text .= ']'; # so that replaceExternalLinks($text) works later
1257 $m[3] = $n[1];
1258 }
1259 # fix up urlencoded title texts
1260 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1261 $trail = $m[3];
1262 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1263 $might_be_img = true;
1264 $text = $m[2];
1265 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1266 $trail = "";
1267 } else { # Invalid form; output directly
1268 $s .= $prefix . '[[' . $line ;
1269 continue;
1270 }
1271
1272 # Don't allow internal links to pages containing
1273 # PROTO: where PROTO is a valid URL protocol; these
1274 # should be external links.
1275 if (preg_match('/^(\b(?:'.URL_PROTOCOLS.'):)/', $m[1])) {
1276 $s .= $prefix . '[[' . $line ;
1277 continue;
1278 }
1279
1280 # Make subpage if necessary
1281 if( $useSubpages ) {
1282 $link = $this->maybeDoSubpageLink( $m[1], $text );
1283 } else {
1284 $link = $m[1];
1285 }
1286
1287 $noforce = (substr($m[1], 0, 1) != ':');
1288 if (!$noforce) {
1289 # Strip off leading ':'
1290 $link = substr($link, 1);
1291 }
1292
1293 $nt =& Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1294 if( !$nt ) {
1295 $s .= $prefix . '[[' . $line;
1296 continue;
1297 }
1298
1299 #check other language variants of the link
1300 #if the article does not exist
1301 if( $checkVariantLink
1302 && $nt->getArticleID() == 0 ) {
1303 $wgContLang->findVariantLink($link, $nt);
1304 }
1305
1306 $ns = $nt->getNamespace();
1307 $iw = $nt->getInterWiki();
1308
1309 if ($might_be_img) { # if this is actually an invalid link
1310 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1311 $found = false;
1312 while (isset ($a[$k+1]) ) {
1313 #look at the next 'line' to see if we can close it there
1314 $next_line = array_shift(array_splice( $a, $k + 1, 1) );
1315 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1316 # the first ]] closes the inner link, the second the image
1317 $found = true;
1318 $text .= '[[' . $m[1];
1319 $trail = $m[2];
1320 break;
1321 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1322 #if there's exactly one ]] that's fine, we'll keep looking
1323 $text .= '[[' . $m[0];
1324 } else {
1325 #if $next_line is invalid too, we need look no further
1326 $text .= '[[' . $next_line;
1327 break;
1328 }
1329 }
1330 if ( !$found ) {
1331 # we couldn't find the end of this imageLink, so output it raw
1332 #but don't ignore what might be perfectly normal links in the text we've examined
1333 $text = $this->replaceInternalLinks($text);
1334 $s .= $prefix . '[[' . $link . '|' . $text;
1335 # note: no $trail, because without an end, there *is* no trail
1336 continue;
1337 }
1338 } else { #it's not an image, so output it raw
1339 $s .= $prefix . '[[' . $link . '|' . $text;
1340 # note: no $trail, because without an end, there *is* no trail
1341 continue;
1342 }
1343 }
1344
1345 $wasblank = ( '' == $text );
1346 if( $wasblank ) $text = $link;
1347
1348
1349 # Link not escaped by : , create the various objects
1350 if( $noforce ) {
1351
1352 # Interwikis
1353 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1354 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1355 $s = rtrim($s . "\n");
1356 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1357 continue;
1358 }
1359
1360 if ( $ns == NS_IMAGE ) {
1361 wfProfileIn( "$fname-image" );
1362 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1363 # recursively parse links inside the image caption
1364 # actually, this will parse them in any other parameters, too,
1365 # but it might be hard to fix that, and it doesn't matter ATM
1366 $text = $this->replaceExternalLinks($text);
1367 $text = $this->replaceInternalLinks($text);
1368
1369 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1370 $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
1371 $wgLinkCache->addImageLinkObj( $nt );
1372
1373 wfProfileOut( "$fname-image" );
1374 continue;
1375 }
1376 wfProfileOut( "$fname-image" );
1377
1378 }
1379
1380 if ( $ns == NS_CATEGORY ) {
1381 wfProfileIn( "$fname-category" );
1382 $t = $wgContLang->convert($nt->getText());
1383 $s = rtrim($s . "\n"); # bug 87
1384
1385 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1386 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1387 $wgLinkCache->resume();
1388
1389 if ( $wasblank ) {
1390 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1391 $sortkey = $this->mTitle->getText();
1392 } else {
1393 $sortkey = $this->mTitle->getPrefixedText();
1394 }
1395 } else {
1396 $sortkey = $text;
1397 }
1398 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1399 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1400 $this->mOutput->addCategoryLink( $t );
1401
1402 /**
1403 * Strip the whitespace Category links produce, see bug 87
1404 * @todo We might want to use trim($tmp, "\n") here.
1405 */
1406 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1407
1408 wfProfileOut( "$fname-category" );
1409 continue;
1410 }
1411 }
1412
1413 if( ( $nt->getPrefixedText() === $selflink ) &&
1414 ( $nt->getFragment() === '' ) ) {
1415 # Self-links are handled specially; generally de-link and change to bold.
1416 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1417 continue;
1418 }
1419
1420 # Special and Media are pseudo-namespaces; no pages actually exist in them
1421 if( $ns == NS_MEDIA ) {
1422 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1423 $wgLinkCache->addImageLinkObj( $nt );
1424 continue;
1425 } elseif( $ns == NS_SPECIAL ) {
1426 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1427 continue;
1428 }
1429 if( !$nt->isExternal() && $nt->isAlwaysKnown() ) {
1430 /**
1431 * Skip lookups for special pages and self-links.
1432 * External interwiki links are not included here because
1433 * the HTTP urls would break output in the next parse step;
1434 * they will have placeholders kept.
1435 */
1436 $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
1437 } else {
1438 /**
1439 * Add a link placeholder
1440 * Later, this will be replaced by a real link, after the existence or
1441 * non-existence of all the links is known
1442 */
1443 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1444 }
1445 }
1446 wfProfileOut( $fname );
1447 return $s;
1448 }
1449
1450 /**
1451 * Make a link placeholder. The text returned can be later resolved to a real link with
1452 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1453 * parsing of interwiki links, and secondly to allow all extistence checks and
1454 * article length checks (for stub links) to be bundled into a single query.
1455 *
1456 */
1457 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1458 if ( ! is_object($nt) ) {
1459 # Fail gracefully
1460 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1461 } else {
1462 # Separate the link trail from the rest of the link
1463 list( $inside, $trail ) = Linker::splitTrail( $trail );
1464
1465 if ( $nt->isExternal() ) {
1466 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1467 $this->mInterwikiLinkHolders['titles'][] = $nt;
1468 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1469 } else {
1470 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1471 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1472 $this->mLinkHolders['queries'][] = $query;
1473 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1474 $this->mLinkHolders['titles'][] = $nt;
1475
1476 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1477 }
1478 }
1479 return $retVal;
1480 }
1481
1482 /**
1483 * Return true if subpage links should be expanded on this page.
1484 * @return bool
1485 */
1486 function areSubpagesAllowed() {
1487 # Some namespaces don't allow subpages
1488 global $wgNamespacesWithSubpages;
1489 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1490 }
1491
1492 /**
1493 * Handle link to subpage if necessary
1494 * @param string $target the source of the link
1495 * @param string &$text the link text, modified as necessary
1496 * @return string the full name of the link
1497 * @access private
1498 */
1499 function maybeDoSubpageLink($target, &$text) {
1500 # Valid link forms:
1501 # Foobar -- normal
1502 # :Foobar -- override special treatment of prefix (images, language links)
1503 # /Foobar -- convert to CurrentPage/Foobar
1504 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1505 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1506 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1507
1508 $fname = 'Parser::maybeDoSubpageLink';
1509 wfProfileIn( $fname );
1510 $ret = $target; # default return value is no change
1511
1512 # Some namespaces don't allow subpages,
1513 # so only perform processing if subpages are allowed
1514 if( $this->areSubpagesAllowed() ) {
1515 # Look at the first character
1516 if( $target != '' && $target{0} == '/' ) {
1517 # / at end means we don't want the slash to be shown
1518 if( substr( $target, -1, 1 ) == '/' ) {
1519 $target = substr( $target, 1, -1 );
1520 $noslash = $target;
1521 } else {
1522 $noslash = substr( $target, 1 );
1523 }
1524
1525 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1526 if( '' === $text ) {
1527 $text = $target;
1528 } # this might be changed for ugliness reasons
1529 } else {
1530 # check for .. subpage backlinks
1531 $dotdotcount = 0;
1532 $nodotdot = $target;
1533 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1534 ++$dotdotcount;
1535 $nodotdot = substr( $nodotdot, 3 );
1536 }
1537 if($dotdotcount > 0) {
1538 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1539 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1540 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1541 # / at the end means don't show full path
1542 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1543 $nodotdot = substr( $nodotdot, 0, -1 );
1544 if( '' === $text ) {
1545 $text = $nodotdot;
1546 }
1547 }
1548 $nodotdot = trim( $nodotdot );
1549 if( $nodotdot != '' ) {
1550 $ret .= '/' . $nodotdot;
1551 }
1552 }
1553 }
1554 }
1555 }
1556
1557 wfProfileOut( $fname );
1558 return $ret;
1559 }
1560
1561 /**#@+
1562 * Used by doBlockLevels()
1563 * @access private
1564 */
1565 /* private */ function closeParagraph() {
1566 $result = '';
1567 if ( '' != $this->mLastSection ) {
1568 $result = '</' . $this->mLastSection . ">\n";
1569 }
1570 $this->mInPre = false;
1571 $this->mLastSection = '';
1572 return $result;
1573 }
1574 # getCommon() returns the length of the longest common substring
1575 # of both arguments, starting at the beginning of both.
1576 #
1577 /* private */ function getCommon( $st1, $st2 ) {
1578 $fl = strlen( $st1 );
1579 $shorter = strlen( $st2 );
1580 if ( $fl < $shorter ) { $shorter = $fl; }
1581
1582 for ( $i = 0; $i < $shorter; ++$i ) {
1583 if ( $st1{$i} != $st2{$i} ) { break; }
1584 }
1585 return $i;
1586 }
1587 # These next three functions open, continue, and close the list
1588 # element appropriate to the prefix character passed into them.
1589 #
1590 /* private */ function openList( $char ) {
1591 $result = $this->closeParagraph();
1592
1593 if ( '*' == $char ) { $result .= '<ul><li>'; }
1594 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1595 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1596 else if ( ';' == $char ) {
1597 $result .= '<dl><dt>';
1598 $this->mDTopen = true;
1599 }
1600 else { $result = '<!-- ERR 1 -->'; }
1601
1602 return $result;
1603 }
1604
1605 /* private */ function nextItem( $char ) {
1606 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1607 else if ( ':' == $char || ';' == $char ) {
1608 $close = '</dd>';
1609 if ( $this->mDTopen ) { $close = '</dt>'; }
1610 if ( ';' == $char ) {
1611 $this->mDTopen = true;
1612 return $close . '<dt>';
1613 } else {
1614 $this->mDTopen = false;
1615 return $close . '<dd>';
1616 }
1617 }
1618 return '<!-- ERR 2 -->';
1619 }
1620
1621 /* private */ function closeList( $char ) {
1622 if ( '*' == $char ) { $text = '</li></ul>'; }
1623 else if ( '#' == $char ) { $text = '</li></ol>'; }
1624 else if ( ':' == $char ) {
1625 if ( $this->mDTopen ) {
1626 $this->mDTopen = false;
1627 $text = '</dt></dl>';
1628 } else {
1629 $text = '</dd></dl>';
1630 }
1631 }
1632 else { return '<!-- ERR 3 -->'; }
1633 return $text."\n";
1634 }
1635 /**#@-*/
1636
1637 /**
1638 * Make lists from lines starting with ':', '*', '#', etc.
1639 *
1640 * @access private
1641 * @return string the lists rendered as HTML
1642 */
1643 function doBlockLevels( $text, $linestart ) {
1644 $fname = 'Parser::doBlockLevels';
1645 wfProfileIn( $fname );
1646
1647 # Parsing through the text line by line. The main thing
1648 # happening here is handling of block-level elements p, pre,
1649 # and making lists from lines starting with * # : etc.
1650 #
1651 $textLines = explode( "\n", $text );
1652
1653 $lastPrefix = $output = '';
1654 $this->mDTopen = $inBlockElem = false;
1655 $prefixLength = 0;
1656 $paragraphStack = false;
1657
1658 if ( !$linestart ) {
1659 $output .= array_shift( $textLines );
1660 }
1661 foreach ( $textLines as $oLine ) {
1662 $lastPrefixLength = strlen( $lastPrefix );
1663 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1664 $preOpenMatch = preg_match('/<pre/i', $oLine );
1665 if ( !$this->mInPre ) {
1666 # Multiple prefixes may abut each other for nested lists.
1667 $prefixLength = strspn( $oLine, '*#:;' );
1668 $pref = substr( $oLine, 0, $prefixLength );
1669
1670 # eh?
1671 $pref2 = str_replace( ';', ':', $pref );
1672 $t = substr( $oLine, $prefixLength );
1673 $this->mInPre = !empty($preOpenMatch);
1674 } else {
1675 # Don't interpret any other prefixes in preformatted text
1676 $prefixLength = 0;
1677 $pref = $pref2 = '';
1678 $t = $oLine;
1679 }
1680
1681 # List generation
1682 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1683 # Same as the last item, so no need to deal with nesting or opening stuff
1684 $output .= $this->nextItem( substr( $pref, -1 ) );
1685 $paragraphStack = false;
1686
1687 if ( substr( $pref, -1 ) == ';') {
1688 # The one nasty exception: definition lists work like this:
1689 # ; title : definition text
1690 # So we check for : in the remainder text to split up the
1691 # title and definition, without b0rking links.
1692 $term = $t2 = '';
1693 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1694 $t = $t2;
1695 $output .= $term . $this->nextItem( ':' );
1696 }
1697 }
1698 } elseif( $prefixLength || $lastPrefixLength ) {
1699 # Either open or close a level...
1700 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1701 $paragraphStack = false;
1702
1703 while( $commonPrefixLength < $lastPrefixLength ) {
1704 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1705 --$lastPrefixLength;
1706 }
1707 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1708 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1709 }
1710 while ( $prefixLength > $commonPrefixLength ) {
1711 $char = substr( $pref, $commonPrefixLength, 1 );
1712 $output .= $this->openList( $char );
1713
1714 if ( ';' == $char ) {
1715 # FIXME: This is dupe of code above
1716 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1717 $t = $t2;
1718 $output .= $term . $this->nextItem( ':' );
1719 }
1720 }
1721 ++$commonPrefixLength;
1722 }
1723 $lastPrefix = $pref2;
1724 }
1725 if( 0 == $prefixLength ) {
1726 wfProfileIn( "$fname-paragraph" );
1727 # No prefix (not in list)--go to paragraph mode
1728 $uniq_prefix = UNIQ_PREFIX;
1729 // XXX: use a stack for nestable elements like span, table and div
1730 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1731 $closematch = preg_match(
1732 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1733 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1734 if ( $openmatch or $closematch ) {
1735 $paragraphStack = false;
1736 $output .= $this->closeParagraph();
1737 if($preOpenMatch and !$preCloseMatch) {
1738 $this->mInPre = true;
1739 }
1740 if ( $closematch ) {
1741 $inBlockElem = false;
1742 } else {
1743 $inBlockElem = true;
1744 }
1745 } else if ( !$inBlockElem && !$this->mInPre ) {
1746 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1747 // pre
1748 if ($this->mLastSection != 'pre') {
1749 $paragraphStack = false;
1750 $output .= $this->closeParagraph().'<pre>';
1751 $this->mLastSection = 'pre';
1752 }
1753 $t = substr( $t, 1 );
1754 } else {
1755 // paragraph
1756 if ( '' == trim($t) ) {
1757 if ( $paragraphStack ) {
1758 $output .= $paragraphStack.'<br />';
1759 $paragraphStack = false;
1760 $this->mLastSection = 'p';
1761 } else {
1762 if ($this->mLastSection != 'p' ) {
1763 $output .= $this->closeParagraph();
1764 $this->mLastSection = '';
1765 $paragraphStack = '<p>';
1766 } else {
1767 $paragraphStack = '</p><p>';
1768 }
1769 }
1770 } else {
1771 if ( $paragraphStack ) {
1772 $output .= $paragraphStack;
1773 $paragraphStack = false;
1774 $this->mLastSection = 'p';
1775 } else if ($this->mLastSection != 'p') {
1776 $output .= $this->closeParagraph().'<p>';
1777 $this->mLastSection = 'p';
1778 }
1779 }
1780 }
1781 }
1782 wfProfileOut( "$fname-paragraph" );
1783 }
1784 if ($paragraphStack === false) {
1785 $output .= $t."\n";
1786 }
1787 }
1788 while ( $prefixLength ) {
1789 $output .= $this->closeList( $pref2{$prefixLength-1} );
1790 --$prefixLength;
1791 }
1792 if ( '' != $this->mLastSection ) {
1793 $output .= '</' . $this->mLastSection . '>';
1794 $this->mLastSection = '';
1795 }
1796
1797 wfProfileOut( $fname );
1798 return $output;
1799 }
1800
1801 /**
1802 * Split up a string on ':', ignoring any occurences inside
1803 * <a>..</a> or <span>...</span>
1804 * @param string $str the string to split
1805 * @param string &$before set to everything before the ':'
1806 * @param string &$after set to everything after the ':'
1807 * return string the position of the ':', or false if none found
1808 */
1809 function findColonNoLinks($str, &$before, &$after) {
1810 # I wonder if we should make this count all tags, not just <a>
1811 # and <span>. That would prevent us from matching a ':' that
1812 # comes in the middle of italics other such formatting....
1813 # -- Wil
1814 $fname = 'Parser::findColonNoLinks';
1815 wfProfileIn( $fname );
1816 $pos = 0;
1817 do {
1818 $colon = strpos($str, ':', $pos);
1819
1820 if ($colon !== false) {
1821 $before = substr($str, 0, $colon);
1822 $after = substr($str, $colon + 1);
1823
1824 # Skip any ':' within <a> or <span> pairs
1825 $a = substr_count($before, '<a');
1826 $s = substr_count($before, '<span');
1827 $ca = substr_count($before, '</a>');
1828 $cs = substr_count($before, '</span>');
1829
1830 if ($a <= $ca and $s <= $cs) {
1831 # Tags are balanced before ':'; ok
1832 break;
1833 }
1834 $pos = $colon + 1;
1835 }
1836 } while ($colon !== false);
1837 wfProfileOut( $fname );
1838 return $colon;
1839 }
1840
1841 /**
1842 * Return value of a magic variable (like PAGENAME)
1843 *
1844 * @access private
1845 */
1846 function getVariableValue( $index ) {
1847 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
1848
1849 /**
1850 * Some of these require message or data lookups and can be
1851 * expensive to check many times.
1852 */
1853 static $varCache = array();
1854 if( isset( $varCache[$index] ) ) return $varCache[$index];
1855
1856 switch ( $index ) {
1857 case MAG_CURRENTMONTH:
1858 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1859 case MAG_CURRENTMONTHNAME:
1860 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1861 case MAG_CURRENTMONTHNAMEGEN:
1862 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1863 case MAG_CURRENTMONTHABBREV:
1864 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1865 case MAG_CURRENTDAY:
1866 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1867 case MAG_PAGENAME:
1868 return $this->mTitle->getText();
1869 case MAG_PAGENAMEE:
1870 return $this->mTitle->getPartialURL();
1871 case MAG_REVISIONID:
1872 return $wgArticle->getRevIdFetched();
1873 case MAG_NAMESPACE:
1874 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1875 return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1876 case MAG_CURRENTDAYNAME:
1877 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1878 case MAG_CURRENTYEAR:
1879 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1880 case MAG_CURRENTTIME:
1881 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1882 case MAG_CURRENTWEEK:
1883 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1884 case MAG_CURRENTDOW:
1885 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1886 case MAG_NUMBEROFARTICLES:
1887 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1888 case MAG_NUMBEROFFILES:
1889 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1890 case MAG_SITENAME:
1891 return $wgSitename;
1892 case MAG_SERVER:
1893 return $wgServer;
1894 case MAG_SERVERNAME:
1895 return $wgServerName;
1896 case MAG_SCRIPTPATH:
1897 return $wgScriptPath;
1898 default:
1899 return NULL;
1900 }
1901 }
1902
1903 /**
1904 * initialise the magic variables (like CURRENTMONTHNAME)
1905 *
1906 * @access private
1907 */
1908 function initialiseVariables() {
1909 $fname = 'Parser::initialiseVariables';
1910 wfProfileIn( $fname );
1911 global $wgVariableIDs;
1912 $this->mVariables = array();
1913 foreach ( $wgVariableIDs as $id ) {
1914 $mw =& MagicWord::get( $id );
1915 $mw->addToArray( $this->mVariables, $id );
1916 }
1917 wfProfileOut( $fname );
1918 }
1919
1920 /**
1921 * Replace magic variables, templates, and template arguments
1922 * with the appropriate text. Templates are substituted recursively,
1923 * taking care to avoid infinite loops.
1924 *
1925 * Note that the substitution depends on value of $mOutputType:
1926 * OT_WIKI: only {{subst:}} templates
1927 * OT_MSG: only magic variables
1928 * OT_HTML: all templates and magic variables
1929 *
1930 * @param string $tex The text to transform
1931 * @param array $args Key-value pairs representing template parameters to substitute
1932 * @access private
1933 */
1934 function replaceVariables( $text, $args = array() ) {
1935
1936 # Prevent too big inclusions
1937 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
1938 return $text;
1939 }
1940
1941 $fname = 'Parser::replaceVariables';
1942 wfProfileIn( $fname );
1943
1944 $titleChars = Title::legalChars();
1945
1946 # This function is called recursively. To keep track of arguments we need a stack:
1947 array_push( $this->mArgStack, $args );
1948
1949 # Variable substitution
1950 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1951
1952 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
1953 # Argument substitution
1954 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1955 }
1956 # Template substitution
1957 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1958 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1959
1960 array_pop( $this->mArgStack );
1961
1962 wfProfileOut( $fname );
1963 return $text;
1964 }
1965
1966 /**
1967 * Replace magic variables
1968 * @access private
1969 */
1970 function variableSubstitution( $matches ) {
1971 $fname = 'parser::variableSubstitution';
1972 $varname = $matches[1];
1973 wfProfileIn( $fname );
1974 if ( !$this->mVariables ) {
1975 $this->initialiseVariables();
1976 }
1977 $skip = false;
1978 if ( $this->mOutputType == OT_WIKI ) {
1979 # Do only magic variables prefixed by SUBST
1980 $mwSubst =& MagicWord::get( MAG_SUBST );
1981 if (!$mwSubst->matchStartAndRemove( $varname ))
1982 $skip = true;
1983 # Note that if we don't substitute the variable below,
1984 # we don't remove the {{subst:}} magic word, in case
1985 # it is a template rather than a magic variable.
1986 }
1987 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
1988 $id = $this->mVariables[$varname];
1989 $text = $this->getVariableValue( $id );
1990 $this->mOutput->mContainsOldMagic = true;
1991 } else {
1992 $text = $matches[0];
1993 }
1994 wfProfileOut( $fname );
1995 return $text;
1996 }
1997
1998 # Split template arguments
1999 function getTemplateArgs( $argsString ) {
2000 if ( $argsString === '' ) {
2001 return array();
2002 }
2003
2004 $args = explode( '|', substr( $argsString, 1 ) );
2005
2006 # If any of the arguments contains a '[[' but no ']]', it needs to be
2007 # merged with the next arg because the '|' character between belongs
2008 # to the link syntax and not the template parameter syntax.
2009 $argc = count($args);
2010
2011 for ( $i = 0; $i < $argc-1; $i++ ) {
2012 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2013 $args[$i] .= '|'.$args[$i+1];
2014 array_splice($args, $i+1, 1);
2015 $i--;
2016 $argc--;
2017 }
2018 }
2019
2020 return $args;
2021 }
2022
2023 /**
2024 * Return the text of a template, after recursively
2025 * replacing any variables or templates within the template.
2026 *
2027 * @param array $matches The parts of the template
2028 * $matches[1]: the title, i.e. the part before the |
2029 * $matches[2]: the parameters (including a leading |), if any
2030 * @return string the text of the template
2031 * @access private
2032 */
2033 function braceSubstitution( $matches ) {
2034 global $wgLinkCache, $wgContLang;
2035 $fname = 'Parser::braceSubstitution';
2036 wfProfileIn( $fname );
2037
2038 $found = false;
2039 $nowiki = false;
2040 $noparse = false;
2041
2042 $title = NULL;
2043
2044 # Need to know if the template comes at the start of a line,
2045 # to treat the beginning of the template like the beginning
2046 # of a line for tables and block-level elements.
2047 $linestart = $matches[1];
2048
2049 # $part1 is the bit before the first |, and must contain only title characters
2050 # $args is a list of arguments, starting from index 0, not including $part1
2051
2052 $part1 = $matches[2];
2053 # If the third subpattern matched anything, it will start with |
2054
2055 $args = $this->getTemplateArgs($matches[3]);
2056 $argc = count( $args );
2057
2058 # Don't parse {{{}}} because that's only for template arguments
2059 if ( $linestart === '{' ) {
2060 $text = $matches[0];
2061 $found = true;
2062 $noparse = true;
2063 }
2064
2065 # SUBST
2066 if ( !$found ) {
2067 $mwSubst =& MagicWord::get( MAG_SUBST );
2068 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2069 # One of two possibilities is true:
2070 # 1) Found SUBST but not in the PST phase
2071 # 2) Didn't find SUBST and in the PST phase
2072 # In either case, return without further processing
2073 $text = $matches[0];
2074 $found = true;
2075 $noparse = true;
2076 }
2077 }
2078
2079 # MSG, MSGNW and INT
2080 if ( !$found ) {
2081 # Check for MSGNW:
2082 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2083 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2084 $nowiki = true;
2085 } else {
2086 # Remove obsolete MSG:
2087 $mwMsg =& MagicWord::get( MAG_MSG );
2088 $mwMsg->matchStartAndRemove( $part1 );
2089 }
2090
2091 # Check if it is an internal message
2092 $mwInt =& MagicWord::get( MAG_INT );
2093 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2094 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2095 $text = $linestart . wfMsgReal( $part1, $args, 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, $wgTitle;
3105 $parserOptions = ParserOptions::newFromUser( $wgUser );
3106 $localParser = new Parser();
3107
3108 global $wgLinkCache;
3109 $ig = new ImageGallery();
3110 $ig->setShowBytes( false );
3111 $ig->setShowFilename( false );
3112 $lines = explode( "\n", $text );
3113
3114 foreach ( $lines as $line ) {
3115 # match lines like these:
3116 # Image:someimage.jpg|This is some image
3117 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3118 # Skip empty lines
3119 if ( count( $matches ) == 0 ) {
3120 continue;
3121 }
3122 $nt = Title::newFromURL( $matches[1] );
3123 if( is_null( $nt ) ) {
3124 # Bogus title. Ignore these so we don't bomb out later.
3125 continue;
3126 }
3127 if ( isset( $matches[3] ) ) {
3128 $label = $matches[3];
3129 } else {
3130 $label = '';
3131 }
3132
3133 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3134 $html = $html->mText;
3135
3136 $ig->add( new Image( $nt ), $html );
3137 $wgLinkCache->addImageLinkObj( $nt );
3138 }
3139 return $ig->toHTML();
3140 }
3141
3142 /**
3143 * Parse image options text and use it to make an image
3144 */
3145 function makeImage( &$nt, $options ) {
3146 global $wgContLang, $wgUseImageResize;
3147 global $wgUser, $wgThumbLimits;
3148
3149 $align = '';
3150
3151 # Check if the options text is of the form "options|alt text"
3152 # Options are:
3153 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3154 # * left no resizing, just left align. label is used for alt= only
3155 # * right same, but right aligned
3156 # * none same, but not aligned
3157 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3158 # * center center the image
3159 # * framed Keep original image size, no magnify-button.
3160
3161 $part = explode( '|', $options);
3162
3163 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3164 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3165 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3166 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3167 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3168 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3169 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3170 $caption = '';
3171
3172 $width = $height = $framed = $thumb = false;
3173 $manual_thumb = '' ;
3174
3175 foreach( $part as $key => $val ) {
3176 $val_parts = explode ( '=' , $val , 2 ) ;
3177 $left_part = array_shift ( $val_parts ) ;
3178 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3179 $thumb=true;
3180 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3181 # use manually specified thumbnail
3182 $thumb=true;
3183 $manual_thumb = array_shift ( $val_parts ) ;
3184 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3185 # remember to set an alignment, don't render immediately
3186 $align = 'right';
3187 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3188 # remember to set an alignment, don't render immediately
3189 $align = 'left';
3190 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3191 # remember to set an alignment, don't render immediately
3192 $align = 'center';
3193 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3194 # remember to set an alignment, don't render immediately
3195 $align = 'none';
3196 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3197 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3198 # $match is the image width in pixels
3199 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3200 $width = intval( $m[1] );
3201 $height = intval( $m[2] );
3202 } else {
3203 $width = intval($match);
3204 }
3205 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3206 $framed=true;
3207 } else {
3208 $caption = $val;
3209 }
3210 }
3211 # Strip bad stuff out of the alt text
3212 $alt = $this->replaceLinkHoldersText( $caption );
3213 $alt = Sanitizer::stripAllTags( $alt );
3214
3215 # Linker does the rest
3216 $sk =& $this->mOptions->getSkin();
3217 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3218 }
3219 }
3220
3221 /**
3222 * @todo document
3223 * @package MediaWiki
3224 */
3225 class ParserOutput
3226 {
3227 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3228 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3229 var $mVersion; # Compatibility check
3230 var $mTitleText; # title text of the chosen language variant
3231
3232 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3233 $containsOldMagic = false, $titletext = '' )
3234 {
3235 $this->mText = $text;
3236 $this->mLanguageLinks = $languageLinks;
3237 $this->mCategoryLinks = $categoryLinks;
3238 $this->mContainsOldMagic = $containsOldMagic;
3239 $this->mCacheTime = '';
3240 $this->mVersion = MW_PARSER_VERSION;
3241 $this->mTitleText = $titletext;
3242 }
3243
3244 function getText() { return $this->mText; }
3245 function getLanguageLinks() { return $this->mLanguageLinks; }
3246 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
3247 function getCacheTime() { return $this->mCacheTime; }
3248 function getTitleText() { return $this->mTitleText; }
3249 function containsOldMagic() { return $this->mContainsOldMagic; }
3250 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3251 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3252 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
3253 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3254 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3255 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3256
3257 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
3258
3259 function merge( $other ) {
3260 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3261 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3262 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3263 }
3264
3265 /**
3266 * Return true if this cached output object predates the global or
3267 * per-article cache invalidation timestamps, or if it comes from
3268 * an incompatible older version.
3269 *
3270 * @param string $touched the affected article's last touched timestamp
3271 * @return bool
3272 * @access public
3273 */
3274 function expired( $touched ) {
3275 global $wgCacheEpoch;
3276 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3277 $this->getCacheTime() <= $touched ||
3278 $this->getCacheTime() <= $wgCacheEpoch ||
3279 !isset( $this->mVersion ) ||
3280 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3281 }
3282 }
3283
3284 /**
3285 * Set options of the Parser
3286 * @todo document
3287 * @package MediaWiki
3288 */
3289 class ParserOptions
3290 {
3291 # All variables are private
3292 var $mUseTeX; # Use texvc to expand <math> tags
3293 var $mUseDynamicDates; # Use DateFormatter to format dates
3294 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3295 var $mAllowExternalImages; # Allow external images inline
3296 var $mSkin; # Reference to the preferred skin
3297 var $mDateFormat; # Date format index
3298 var $mEditSection; # Create "edit section" links
3299 var $mNumberHeadings; # Automatically number headings
3300 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3301
3302 function getUseTeX() { return $this->mUseTeX; }
3303 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3304 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3305 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3306 function getSkin() { return $this->mSkin; }
3307 function getDateFormat() { return $this->mDateFormat; }
3308 function getEditSection() { return $this->mEditSection; }
3309 function getNumberHeadings() { return $this->mNumberHeadings; }
3310 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3311
3312
3313 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3314 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3315 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3316 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3317 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3318 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3319 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3320 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3321
3322 function setSkin( &$x ) { $this->mSkin =& $x; }
3323
3324 function ParserOptions() {
3325 global $wgUser;
3326 $this->initialiseFromUser( $wgUser );
3327 }
3328
3329 /**
3330 * Get parser options
3331 * @static
3332 */
3333 function newFromUser( &$user ) {
3334 $popts = new ParserOptions;
3335 $popts->initialiseFromUser( $user );
3336 return $popts;
3337 }
3338
3339 /** Get user options */
3340 function initialiseFromUser( &$userInput ) {
3341 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3342 $wgAllowSpecialInclusion;
3343 $fname = 'ParserOptions::initialiseFromUser';
3344 wfProfileIn( $fname );
3345 if ( !$userInput ) {
3346 $user = new User;
3347 $user->setLoaded( true );
3348 } else {
3349 $user =& $userInput;
3350 }
3351
3352 $this->mUseTeX = $wgUseTeX;
3353 $this->mUseDynamicDates = $wgUseDynamicDates;
3354 $this->mInterwikiMagic = $wgInterwikiMagic;
3355 $this->mAllowExternalImages = $wgAllowExternalImages;
3356 wfProfileIn( $fname.'-skin' );
3357 $this->mSkin =& $user->getSkin();
3358 wfProfileOut( $fname.'-skin' );
3359 $this->mDateFormat = $user->getOption( 'date' );
3360 $this->mEditSection = $user->getOption( 'editsection' );
3361 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3362 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
3363 wfProfileOut( $fname );
3364 }
3365 }
3366
3367 /**
3368 * Callback function used by Parser::replaceLinkHolders()
3369 * to substitute link placeholders.
3370 */
3371 function &wfOutputReplaceMatches( $matches ) {
3372 global $wgOutputReplace;
3373 return $wgOutputReplace[$matches[1]];
3374 }
3375
3376 /**
3377 * Return the total number of articles
3378 */
3379 function wfNumberOfArticles() {
3380 global $wgNumberOfArticles;
3381
3382 wfLoadSiteStats();
3383 return $wgNumberOfArticles;
3384 }
3385
3386 /**
3387 * Return the number of files
3388 */
3389 function wfNumberOfFiles() {
3390 $fname = 'Parser::wfNumberOfFiles';
3391
3392 wfProfileIn( $fname );
3393 $dbr =& wfGetDB( DB_SLAVE );
3394 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3395 wfProfileOut( $fname );
3396
3397 return $res;
3398 }
3399
3400 /**
3401 * Get various statistics from the database
3402 * @private
3403 */
3404 function wfLoadSiteStats() {
3405 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3406 $fname = 'wfLoadSiteStats';
3407
3408 if ( -1 != $wgNumberOfArticles ) return;
3409 $dbr =& wfGetDB( DB_SLAVE );
3410 $s = $dbr->selectRow( 'site_stats',
3411 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3412 array( 'ss_row_id' => 1 ), $fname
3413 );
3414
3415 if ( $s === false ) {
3416 return;
3417 } else {
3418 $wgTotalViews = $s->ss_total_views;
3419 $wgTotalEdits = $s->ss_total_edits;
3420 $wgNumberOfArticles = $s->ss_good_articles;
3421 }
3422 }
3423
3424 /**
3425 * Escape html tags
3426 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3427 *
3428 * @param string $in Text that might contain HTML tags
3429 * @return string Escaped string
3430 */
3431 function wfEscapeHTMLTagsOnly( $in ) {
3432 return str_replace(
3433 array( '"', '>', '<' ),
3434 array( '&quot;', '&gt;', '&lt;' ),
3435 $in );
3436 }
3437
3438 ?>