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