* (bug 2372) Fix rendering of empty-title inline interwiki links
[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 }
2087
2088 # int: is the wikitext equivalent of wfMsg()
2089 $mwInt =& MagicWord::get( MAG_INT );
2090 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2091 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2092 $text = $linestart . wfMsgReal( $part1, $args, true );
2093 $found = true;
2094 }
2095 }
2096
2097 # msg: is the wikitext equivalent of wfMsgForContent()
2098 $mwMsg =& MagicWord::get( MAG_MSG );
2099 if ( $mwMsg->matchStartAndRemove( $part1 ) ) {
2100 if ( $this->incrementIncludeCount( 'msg:'.$part1 ) ) {
2101 $text = $linestart . wfMsgReal( $part1, $args, true, true );
2102 $found = true;
2103 }
2104 }
2105 }
2106
2107 # NS
2108 if ( !$found ) {
2109 # Check for NS: (namespace expansion)
2110 $mwNs = MagicWord::get( MAG_NS );
2111 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2112 if ( intval( $part1 ) ) {
2113 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2114 $found = true;
2115 } else {
2116 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2117 if ( !is_null( $index ) ) {
2118 $text = $linestart . $wgContLang->getNsText( $index );
2119 $found = true;
2120 }
2121 }
2122 }
2123 }
2124
2125 # LOCALURL and LOCALURLE
2126 if ( !$found ) {
2127 $mwLocal = MagicWord::get( MAG_LOCALURL );
2128 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
2129
2130 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2131 $func = 'getLocalURL';
2132 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2133 $func = 'escapeLocalURL';
2134 } else {
2135 $func = '';
2136 }
2137
2138 if ( $func !== '' ) {
2139 $title = Title::newFromText( $part1 );
2140 if ( !is_null( $title ) ) {
2141 if ( $argc > 0 ) {
2142 $text = $linestart . $title->$func( $args[0] );
2143 } else {
2144 $text = $linestart . $title->$func();
2145 }
2146 $found = true;
2147 }
2148 }
2149 }
2150
2151 # GRAMMAR
2152 if ( !$found && $argc == 1 ) {
2153 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2154 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2155 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2156 $found = true;
2157 }
2158 }
2159
2160 # Template table test
2161
2162 # Did we encounter this template already? If yes, it is in the cache
2163 # and we need to check for loops.
2164 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
2165 $found = true;
2166
2167 # Infinite loop test
2168 if ( isset( $this->mTemplatePath[$part1] ) ) {
2169 $noparse = true;
2170 $found = true;
2171 $text = $linestart .
2172 "\{\{$part1}}" .
2173 '<!-- WARNING: template loop detected -->';
2174 wfDebug( "$fname: template loop broken at '$part1'\n" );
2175 } else {
2176 # set $text to cached message.
2177 $text = $linestart . $this->mTemplates[$part1];
2178 }
2179 }
2180
2181 # Load from database
2182 $replaceHeadings = false;
2183 $isHTML = false;
2184 $lastPathLevel = $this->mTemplatePath;
2185 if ( !$found ) {
2186 $ns = NS_TEMPLATE;
2187 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2188 if ($subpage !== '') {
2189 $ns = $this->mTitle->getNamespace();
2190 }
2191 $title = Title::newFromText( $part1, $ns );
2192 if ( !is_null( $title ) && !$title->isExternal() ) {
2193 # Check for excessive inclusion
2194 $dbk = $title->getPrefixedDBkey();
2195 if ( $this->incrementIncludeCount( $dbk ) ) {
2196 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2197 # Capture special page output
2198 $text = SpecialPage::capturePath( $title );
2199 if ( $text && !is_object( $text ) ) {
2200 $found = true;
2201 $noparse = true;
2202 $isHTML = true;
2203 $this->mOutput->setCacheTime( -1 );
2204 }
2205 } else {
2206 $article = new Article( $title );
2207 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2208 if ( $articleContent !== false ) {
2209 $found = true;
2210 $text = $articleContent;
2211 $replaceHeadings = true;
2212 }
2213 }
2214 }
2215
2216 # If the title is valid but undisplayable, make a link to it
2217 if ( $this->mOutputType == OT_HTML && !$found ) {
2218 $text = '[['.$title->getPrefixedText().']]';
2219 $found = true;
2220 }
2221
2222 # Template cache array insertion
2223 if( $found ) {
2224 $this->mTemplates[$part1] = $text;
2225 $text = $linestart . $text;
2226 }
2227 }
2228 }
2229
2230 # Recursive parsing, escaping and link table handling
2231 # Only for HTML output
2232 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2233 $text = wfEscapeWikiText( $text );
2234 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2235 # Clean up argument array
2236 $assocArgs = array();
2237 $index = 1;
2238 foreach( $args as $arg ) {
2239 $eqpos = strpos( $arg, '=' );
2240 if ( $eqpos === false ) {
2241 $assocArgs[$index++] = $arg;
2242 } else {
2243 $name = trim( substr( $arg, 0, $eqpos ) );
2244 $value = trim( substr( $arg, $eqpos+1 ) );
2245 if ( $value === false ) {
2246 $value = '';
2247 }
2248 if ( $name !== false ) {
2249 $assocArgs[$name] = $value;
2250 }
2251 }
2252 }
2253
2254 # Add a new element to the templace recursion path
2255 $this->mTemplatePath[$part1] = 1;
2256
2257 if( $this->mOutputType == OT_HTML ) {
2258 $text = $this->strip( $text, $this->mStripState );
2259 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2260 }
2261 $text = $this->replaceVariables( $text, $assocArgs );
2262
2263 # Resume the link cache and register the inclusion as a link
2264 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2265 $wgLinkCache->addLinkObj( $title );
2266 }
2267
2268 # If the template begins with a table or block-level
2269 # element, it should be treated as beginning a new line.
2270 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2271 $text = "\n" . $text;
2272 }
2273 }
2274 # Prune lower levels off the recursion check path
2275 $this->mTemplatePath = $lastPathLevel;
2276
2277 if ( !$found ) {
2278 wfProfileOut( $fname );
2279 return $matches[0];
2280 } else {
2281 if ( $isHTML ) {
2282 # Replace raw HTML by a placeholder
2283 # Add a blank line preceding, to prevent it from mucking up
2284 # immediately preceding headings
2285 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2286 } else {
2287 # replace ==section headers==
2288 # XXX this needs to go away once we have a better parser.
2289 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2290 if( !is_null( $title ) )
2291 $encodedname = base64_encode($title->getPrefixedDBkey());
2292 else
2293 $encodedname = base64_encode("");
2294 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2295 PREG_SPLIT_DELIM_CAPTURE);
2296 $text = '';
2297 $nsec = 0;
2298 for( $i = 0; $i < count($m); $i += 2 ) {
2299 $text .= $m[$i];
2300 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2301 $hl = $m[$i + 1];
2302 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2303 $text .= $hl;
2304 continue;
2305 }
2306 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2307 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2308 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2309
2310 $nsec++;
2311 }
2312 }
2313 }
2314 }
2315
2316 # Prune lower levels off the recursion check path
2317 $this->mTemplatePath = $lastPathLevel;
2318
2319 if ( !$found ) {
2320 wfProfileOut( $fname );
2321 return $matches[0];
2322 } else {
2323 wfProfileOut( $fname );
2324 return $text;
2325 }
2326 }
2327
2328 /**
2329 * Triple brace replacement -- used for template arguments
2330 * @access private
2331 */
2332 function argSubstitution( $matches ) {
2333 $arg = trim( $matches[1] );
2334 $text = $matches[0];
2335 $inputArgs = end( $this->mArgStack );
2336
2337 if ( array_key_exists( $arg, $inputArgs ) ) {
2338 $text = $inputArgs[$arg];
2339 }
2340
2341 return $text;
2342 }
2343
2344 /**
2345 * Returns true if the function is allowed to include this entity
2346 * @access private
2347 */
2348 function incrementIncludeCount( $dbk ) {
2349 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2350 $this->mIncludeCount[$dbk] = 0;
2351 }
2352 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2353 return true;
2354 } else {
2355 return false;
2356 }
2357 }
2358
2359 /**
2360 * This function accomplishes several tasks:
2361 * 1) Auto-number headings if that option is enabled
2362 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2363 * 3) Add a Table of contents on the top for users who have enabled the option
2364 * 4) Auto-anchor headings
2365 *
2366 * It loops through all headlines, collects the necessary data, then splits up the
2367 * string and re-inserts the newly formatted headlines.
2368 *
2369 * @param string $text
2370 * @param boolean $isMain
2371 * @access private
2372 */
2373 function formatHeadings( $text, $isMain=true ) {
2374 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2375
2376 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2377 $doShowToc = true;
2378 $forceTocHere = false;
2379 if( !$this->mTitle->userCanEdit() ) {
2380 $showEditLink = 0;
2381 } else {
2382 $showEditLink = $this->mOptions->getEditSection();
2383 }
2384
2385 # Inhibit editsection links if requested in the page
2386 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2387 if( $esw->matchAndRemove( $text ) ) {
2388 $showEditLink = 0;
2389 }
2390 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2391 # do not add TOC
2392 $mw =& MagicWord::get( MAG_NOTOC );
2393 if( $mw->matchAndRemove( $text ) ) {
2394 $doShowToc = false;
2395 }
2396
2397 # Get all headlines for numbering them and adding funky stuff like [edit]
2398 # links - this is for later, but we need the number of headlines right now
2399 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2400
2401 # if there are fewer than 4 headlines in the article, do not show TOC
2402 if( $numMatches < 4 ) {
2403 $doShowToc = false;
2404 }
2405
2406 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2407 # override above conditions and always show TOC at that place
2408
2409 $mw =& MagicWord::get( MAG_TOC );
2410 if($mw->match( $text ) ) {
2411 $doShowToc = true;
2412 $forceTocHere = true;
2413 } else {
2414 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2415 # override above conditions and always show TOC above first header
2416 $mw =& MagicWord::get( MAG_FORCETOC );
2417 if ($mw->matchAndRemove( $text ) ) {
2418 $doShowToc = true;
2419 }
2420 }
2421
2422 # Never ever show TOC if no headers
2423 if( $numMatches < 1 ) {
2424 $doShowToc = false;
2425 }
2426
2427 # We need this to perform operations on the HTML
2428 $sk =& $this->mOptions->getSkin();
2429
2430 # headline counter
2431 $headlineCount = 0;
2432 $sectionCount = 0; # headlineCount excluding template sections
2433
2434 # Ugh .. the TOC should have neat indentation levels which can be
2435 # passed to the skin functions. These are determined here
2436 $toc = '';
2437 $full = '';
2438 $head = array();
2439 $sublevelCount = array();
2440 $levelCount = array();
2441 $toclevel = 0;
2442 $level = 0;
2443 $prevlevel = 0;
2444 $toclevel = 0;
2445 $prevtoclevel = 0;
2446
2447 foreach( $matches[3] as $headline ) {
2448 $istemplate = 0;
2449 $templatetitle = '';
2450 $templatesection = 0;
2451 $numbering = '';
2452
2453 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2454 $istemplate = 1;
2455 $templatetitle = base64_decode($mat[1]);
2456 $templatesection = 1 + (int)base64_decode($mat[2]);
2457 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2458 }
2459
2460 if( $toclevel ) {
2461 $prevlevel = $level;
2462 $prevtoclevel = $toclevel;
2463 }
2464 $level = $matches[1][$headlineCount];
2465
2466 if( $doNumberHeadings || $doShowToc ) {
2467
2468 if ( $level > $prevlevel ) {
2469 # Increase TOC level
2470 $toclevel++;
2471 $sublevelCount[$toclevel] = 0;
2472 $toc .= $sk->tocIndent();
2473 }
2474 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2475 # Decrease TOC level, find level to jump to
2476
2477 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2478 # Can only go down to level 1
2479 $toclevel = 1;
2480 } else {
2481 for ($i = $toclevel; $i > 0; $i--) {
2482 if ( $levelCount[$i] == $level ) {
2483 # Found last matching level
2484 $toclevel = $i;
2485 break;
2486 }
2487 elseif ( $levelCount[$i] < $level ) {
2488 # Found first matching level below current level
2489 $toclevel = $i + 1;
2490 break;
2491 }
2492 }
2493 }
2494
2495 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2496 }
2497 else {
2498 # No change in level, end TOC line
2499 $toc .= $sk->tocLineEnd();
2500 }
2501
2502 $levelCount[$toclevel] = $level;
2503
2504 # count number of headlines for each level
2505 @$sublevelCount[$toclevel]++;
2506 $dot = 0;
2507 for( $i = 1; $i <= $toclevel; $i++ ) {
2508 if( !empty( $sublevelCount[$i] ) ) {
2509 if( $dot ) {
2510 $numbering .= '.';
2511 }
2512 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2513 $dot = 1;
2514 }
2515 }
2516 }
2517
2518 # The canonized header is a version of the header text safe to use for links
2519 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2520 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2521 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2522
2523 # Remove link placeholders by the link text.
2524 # <!--LINK number-->
2525 # turns into
2526 # link text with suffix
2527 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2528 "\$this->mLinkHolders['texts'][\$1]",
2529 $canonized_headline );
2530 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2531 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2532 $canonized_headline );
2533
2534 # strip out HTML
2535 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2536 $tocline = trim( $canonized_headline );
2537 $canonized_headline = urlencode( Sanitizer::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2538 $replacearray = array(
2539 '%3A' => ':',
2540 '%' => '.'
2541 );
2542 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2543 $refers[$headlineCount] = $canonized_headline;
2544
2545 # count how many in assoc. array so we can track dupes in anchors
2546 @$refers[$canonized_headline]++;
2547 $refcount[$headlineCount]=$refers[$canonized_headline];
2548
2549 # Don't number the heading if it is the only one (looks silly)
2550 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2551 # the two are different if the line contains a link
2552 $headline=$numbering . ' ' . $headline;
2553 }
2554
2555 # Create the anchor for linking from the TOC to the section
2556 $anchor = $canonized_headline;
2557 if($refcount[$headlineCount] > 1 ) {
2558 $anchor .= '_' . $refcount[$headlineCount];
2559 }
2560 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2561 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2562 }
2563 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2564 if ( empty( $head[$headlineCount] ) ) {
2565 $head[$headlineCount] = '';
2566 }
2567 if( $istemplate )
2568 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2569 else
2570 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2571 }
2572
2573 # give headline the correct <h#> tag
2574 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2575
2576 $headlineCount++;
2577 if( !$istemplate )
2578 $sectionCount++;
2579 }
2580
2581 if( $doShowToc ) {
2582 $toc .= $sk->tocUnindent( $toclevel - 1 );
2583 $toc = $sk->tocList( $toc );
2584 }
2585
2586 # split up and insert constructed headlines
2587
2588 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2589 $i = 0;
2590
2591 foreach( $blocks as $block ) {
2592 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2593 # This is the [edit] link that appears for the top block of text when
2594 # section editing is enabled
2595
2596 # Disabled because it broke block formatting
2597 # For example, a bullet point in the top line
2598 # $full .= $sk->editSectionLink(0);
2599 }
2600 $full .= $block;
2601 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2602 # Top anchor now in skin
2603 $full = $full.$toc;
2604 }
2605
2606 if( !empty( $head[$i] ) ) {
2607 $full .= $head[$i];
2608 }
2609 $i++;
2610 }
2611 if($forceTocHere) {
2612 $mw =& MagicWord::get( MAG_TOC );
2613 return $mw->replace( $toc, $full );
2614 } else {
2615 return $full;
2616 }
2617 }
2618
2619 /**
2620 * Return an HTML link for the "ISBN 123456" text
2621 * @access private
2622 */
2623 function magicISBN( $text ) {
2624 $fname = 'Parser::magicISBN';
2625 wfProfileIn( $fname );
2626
2627 $a = split( 'ISBN ', ' '.$text );
2628 if ( count ( $a ) < 2 ) {
2629 wfProfileOut( $fname );
2630 return $text;
2631 }
2632 $text = substr( array_shift( $a ), 1);
2633 $valid = '0123456789-Xx';
2634
2635 foreach ( $a as $x ) {
2636 $isbn = $blank = '' ;
2637 while ( ' ' == $x{0} ) {
2638 $blank .= ' ';
2639 $x = substr( $x, 1 );
2640 }
2641 if ( $x == '' ) { # blank isbn
2642 $text .= "ISBN $blank";
2643 continue;
2644 }
2645 while ( strstr( $valid, $x{0} ) != false ) {
2646 $isbn .= $x{0};
2647 $x = substr( $x, 1 );
2648 }
2649 $num = str_replace( '-', '', $isbn );
2650 $num = str_replace( ' ', '', $num );
2651 $num = str_replace( 'x', 'X', $num );
2652
2653 if ( '' == $num ) {
2654 $text .= "ISBN $blank$x";
2655 } else {
2656 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2657 $text .= '<a href="' .
2658 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2659 "\" class=\"internal\">ISBN $isbn</a>";
2660 $text .= $x;
2661 }
2662 }
2663 wfProfileOut( $fname );
2664 return $text;
2665 }
2666
2667 /**
2668 * Return an HTML link for the "RFC 1234" text
2669 *
2670 * @access private
2671 * @param string $text Text to be processed
2672 * @param string $keyword Magic keyword to use (default RFC)
2673 * @param string $urlmsg Interface message to use (default rfcurl)
2674 * @return string
2675 */
2676 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2677
2678 $valid = '0123456789';
2679 $internal = false;
2680
2681 $a = split( $keyword, ' '.$text );
2682 if ( count ( $a ) < 2 ) {
2683 return $text;
2684 }
2685 $text = substr( array_shift( $a ), 1);
2686
2687 /* Check if keyword is preceed by [[.
2688 * This test is made here cause of the array_shift above
2689 * that prevent the test to be done in the foreach.
2690 */
2691 if ( substr( $text, -2 ) == '[[' ) {
2692 $internal = true;
2693 }
2694
2695 foreach ( $a as $x ) {
2696 /* token might be empty if we have RFC RFC 1234 */
2697 if ( $x=='' ) {
2698 $text.=$keyword;
2699 continue;
2700 }
2701
2702 $id = $blank = '' ;
2703
2704 /** remove and save whitespaces in $blank */
2705 while ( $x{0} == ' ' ) {
2706 $blank .= ' ';
2707 $x = substr( $x, 1 );
2708 }
2709
2710 /** remove and save the rfc number in $id */
2711 while ( strstr( $valid, $x{0} ) != false ) {
2712 $id .= $x{0};
2713 $x = substr( $x, 1 );
2714 }
2715
2716 if ( $id == '' ) {
2717 /* call back stripped spaces*/
2718 $text .= $keyword.$blank.$x;
2719 } elseif( $internal ) {
2720 /* normal link */
2721 $text .= $keyword.$id.$x;
2722 } else {
2723 /* build the external link*/
2724 $url = wfMsg( $urlmsg, $id);
2725 $sk =& $this->mOptions->getSkin();
2726 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2727 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2728 }
2729
2730 /* Check if the next RFC keyword is preceed by [[ */
2731 $internal = ( substr($x,-2) == '[[' );
2732 }
2733 return $text;
2734 }
2735
2736 /**
2737 * Transform wiki markup when saving a page by doing \r\n -> \n
2738 * conversion, substitting signatures, {{subst:}} templates, etc.
2739 *
2740 * @param string $text the text to transform
2741 * @param Title &$title the Title object for the current article
2742 * @param User &$user the User object describing the current user
2743 * @param ParserOptions $options parsing options
2744 * @param bool $clearState whether to clear the parser state first
2745 * @return string the altered wiki markup
2746 * @access public
2747 */
2748 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2749 $this->mOptions = $options;
2750 $this->mTitle =& $title;
2751 $this->mOutputType = OT_WIKI;
2752
2753 if ( $clearState ) {
2754 $this->clearState();
2755 }
2756
2757 $stripState = false;
2758 $pairs = array(
2759 "\r\n" => "\n",
2760 );
2761 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2762 $text = $this->strip( $text, $stripState, false );
2763 $text = $this->pstPass2( $text, $user );
2764 $text = $this->unstrip( $text, $stripState );
2765 $text = $this->unstripNoWiki( $text, $stripState );
2766 return $text;
2767 }
2768
2769 /**
2770 * Pre-save transform helper function
2771 * @access private
2772 */
2773 function pstPass2( $text, &$user ) {
2774 global $wgContLang, $wgLocaltimezone;
2775
2776 # Variable replacement
2777 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2778 $text = $this->replaceVariables( $text );
2779
2780 # Signatures
2781 #
2782 $n = $user->getName();
2783 $k = $user->getOption( 'nickname' );
2784 if ( '' == $k ) { $k = $n; }
2785 if ( isset( $wgLocaltimezone ) ) {
2786 $oldtz = getenv( 'TZ' );
2787 putenv( 'TZ='.$wgLocaltimezone );
2788 }
2789
2790 /* Note: This is the timestamp saved as hardcoded wikitext to
2791 * the database, we use $wgContLang here in order to give
2792 * everyone the same signiture and use the default one rather
2793 * than the one selected in each users preferences.
2794 */
2795 $d = $wgContLang->timeanddate( wfTimestampNow(), false, false) .
2796 ' (' . date( 'T' ) . ')';
2797 if ( isset( $wgLocaltimezone ) ) {
2798 putenv( 'TZ='.$oldtz );
2799 }
2800
2801 if( $user->getOption( 'fancysig' ) ) {
2802 $sigText = $k;
2803 } else {
2804 $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
2805 }
2806 $text = preg_replace( '/~~~~~/', $d, $text );
2807 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2808 $text = preg_replace( '/~~~/', $sigText, $text );
2809
2810 # Context links: [[|name]] and [[name (context)|]]
2811 #
2812 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2813 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2814 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2815 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2816
2817 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2818 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2819 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2820 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2821 $context = '';
2822 $t = $this->mTitle->getText();
2823 if ( preg_match( $conpat, $t, $m ) ) {
2824 $context = $m[2];
2825 }
2826 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2827 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2828 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2829
2830 if ( '' == $context ) {
2831 $text = preg_replace( $p2, '[[\\1]]', $text );
2832 } else {
2833 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2834 }
2835
2836 # Trim trailing whitespace
2837 # MAG_END (__END__) tag allows for trailing
2838 # whitespace to be deliberately included
2839 $text = rtrim( $text );
2840 $mw =& MagicWord::get( MAG_END );
2841 $mw->matchAndRemove( $text );
2842
2843 return $text;
2844 }
2845
2846 /**
2847 * Set up some variables which are usually set up in parse()
2848 * so that an external function can call some class members with confidence
2849 * @access public
2850 */
2851 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2852 $this->mTitle =& $title;
2853 $this->mOptions = $options;
2854 $this->mOutputType = $outputType;
2855 if ( $clearState ) {
2856 $this->clearState();
2857 }
2858 }
2859
2860 /**
2861 * Transform a MediaWiki message by replacing magic variables.
2862 *
2863 * @param string $text the text to transform
2864 * @param ParserOptions $options options
2865 * @return string the text with variables substituted
2866 * @access public
2867 */
2868 function transformMsg( $text, $options ) {
2869 global $wgTitle;
2870 static $executing = false;
2871
2872 # Guard against infinite recursion
2873 if ( $executing ) {
2874 return $text;
2875 }
2876 $executing = true;
2877
2878 $this->mTitle = $wgTitle;
2879 $this->mOptions = $options;
2880 $this->mOutputType = OT_MSG;
2881 $this->clearState();
2882 $text = $this->replaceVariables( $text );
2883
2884 $executing = false;
2885 return $text;
2886 }
2887
2888 /**
2889 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2890 * Callback will be called with the text within
2891 * Transform and return the text within
2892 * @access public
2893 */
2894 function setHook( $tag, $callback ) {
2895 $oldVal = @$this->mTagHooks[$tag];
2896 $this->mTagHooks[$tag] = $callback;
2897 return $oldVal;
2898 }
2899
2900 /**
2901 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2902 * Placeholders created in Skin::makeLinkObj()
2903 * Returns an array of links found, indexed by PDBK:
2904 * 0 - broken
2905 * 1 - normal link
2906 * 2 - stub
2907 * $options is a bit field, RLH_FOR_UPDATE to select for update
2908 */
2909 function replaceLinkHolders( &$text, $options = 0 ) {
2910 global $wgUser, $wgLinkCache;
2911 global $wgOutputReplace;
2912
2913 $fname = 'Parser::replaceLinkHolders';
2914 wfProfileIn( $fname );
2915
2916 $pdbks = array();
2917 $colours = array();
2918 $sk = $this->mOptions->getSkin();
2919
2920 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
2921 wfProfileIn( $fname.'-check' );
2922 $dbr =& wfGetDB( DB_SLAVE );
2923 $page = $dbr->tableName( 'page' );
2924 $threshold = $wgUser->getOption('stubthreshold');
2925
2926 # Sort by namespace
2927 asort( $this->mLinkHolders['namespaces'] );
2928
2929 # Generate query
2930 $query = false;
2931 foreach ( $this->mLinkHolders['namespaces'] as $key => $val ) {
2932 # Make title object
2933 $title = $this->mLinkHolders['titles'][$key];
2934
2935 # Skip invalid entries.
2936 # Result will be ugly, but prevents crash.
2937 if ( is_null( $title ) ) {
2938 continue;
2939 }
2940 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2941
2942 # Check if it's in the link cache already
2943 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2944 $colours[$pdbk] = 1;
2945 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2946 $colours[$pdbk] = 0;
2947 } else {
2948 # Not in the link cache, add it to the query
2949 if ( !isset( $current ) ) {
2950 $current = $val;
2951 $query = "SELECT page_id, page_namespace, page_title";
2952 if ( $threshold > 0 ) {
2953 $query .= ', page_len, page_is_redirect';
2954 }
2955 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2956 } elseif ( $current != $val ) {
2957 $current = $val;
2958 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2959 } else {
2960 $query .= ', ';
2961 }
2962
2963 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
2964 }
2965 }
2966 if ( $query ) {
2967 $query .= '))';
2968 if ( $options & RLH_FOR_UPDATE ) {
2969 $query .= ' FOR UPDATE';
2970 }
2971
2972 $res = $dbr->query( $query, $fname );
2973
2974 # Fetch data and form into an associative array
2975 # non-existent = broken
2976 # 1 = known
2977 # 2 = stub
2978 while ( $s = $dbr->fetchObject($res) ) {
2979 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
2980 $pdbk = $title->getPrefixedDBkey();
2981 $wgLinkCache->addGoodLinkObj( $s->page_id, $title );
2982
2983 if ( $threshold > 0 ) {
2984 $size = $s->page_len;
2985 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
2986 $colours[$pdbk] = 1;
2987 } else {
2988 $colours[$pdbk] = 2;
2989 }
2990 } else {
2991 $colours[$pdbk] = 1;
2992 }
2993 }
2994 }
2995 wfProfileOut( $fname.'-check' );
2996
2997 # Construct search and replace arrays
2998 wfProfileIn( $fname.'-construct' );
2999 $wgOutputReplace = array();
3000 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3001 $pdbk = $pdbks[$key];
3002 $searchkey = "<!--LINK $key-->";
3003 $title = $this->mLinkHolders['titles'][$key];
3004 if ( empty( $colours[$pdbk] ) ) {
3005 $wgLinkCache->addBadLinkObj( $title );
3006 $colours[$pdbk] = 0;
3007 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3008 $this->mLinkHolders['texts'][$key],
3009 $this->mLinkHolders['queries'][$key] );
3010 } elseif ( $colours[$pdbk] == 1 ) {
3011 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3012 $this->mLinkHolders['texts'][$key],
3013 $this->mLinkHolders['queries'][$key] );
3014 } elseif ( $colours[$pdbk] == 2 ) {
3015 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3016 $this->mLinkHolders['texts'][$key],
3017 $this->mLinkHolders['queries'][$key] );
3018 }
3019 }
3020 wfProfileOut( $fname.'-construct' );
3021
3022 # Do the thing
3023 wfProfileIn( $fname.'-replace' );
3024
3025 $text = preg_replace_callback(
3026 '/(<!--LINK .*?-->)/',
3027 "wfOutputReplaceMatches",
3028 $text);
3029
3030 wfProfileOut( $fname.'-replace' );
3031 }
3032
3033 # Now process interwiki link holders
3034 # This is quite a bit simpler than internal links
3035 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3036 wfProfileIn( $fname.'-interwiki' );
3037 # Make interwiki link HTML
3038 $wgOutputReplace = array();
3039 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3040 $title = $this->mInterwikiLinkHolders['titles'][$key];
3041 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3042 }
3043
3044 $text = preg_replace_callback(
3045 '/<!--IWLINK (.*?)-->/',
3046 "wfOutputReplaceMatches",
3047 $text );
3048 wfProfileOut( $fname.'-interwiki' );
3049 }
3050
3051 wfProfileOut( $fname );
3052 return $colours;
3053 }
3054
3055 /**
3056 * Replace <!--LINK--> link placeholders with plain text of links
3057 * (not HTML-formatted).
3058 * @param string $text
3059 * @return string
3060 */
3061 function replaceLinkHoldersText( $text ) {
3062 global $wgUser, $wgLinkCache;
3063 global $wgOutputReplace;
3064
3065 $fname = 'Parser::replaceLinkHoldersText';
3066 wfProfileIn( $fname );
3067
3068 $text = preg_replace_callback(
3069 '/<!--(LINK|IWLINK) (.*?)-->/',
3070 array( &$this, 'replaceLinkHoldersTextCallback' ),
3071 $text );
3072
3073 wfProfileOut( $fname );
3074 return $text;
3075 }
3076
3077 /**
3078 * @param array $matches
3079 * @return string
3080 * @access private
3081 */
3082 function replaceLinkHoldersTextCallback( $matches ) {
3083 $type = $matches[1];
3084 $key = $matches[2];
3085 if( $type == 'LINK' ) {
3086 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3087 return $this->mLinkHolders['texts'][$key];
3088 }
3089 } elseif( $type == 'IWLINK' ) {
3090 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3091 return $this->mInterwikiLinkHolders['texts'][$key];
3092 }
3093 }
3094 return $matches[0];
3095 }
3096
3097 /**
3098 * Renders an image gallery from a text with one line per image.
3099 * text labels may be given by using |-style alternative text. E.g.
3100 * Image:one.jpg|The number "1"
3101 * Image:tree.jpg|A tree
3102 * given as text will return the HTML of a gallery with two images,
3103 * labeled 'The number "1"' and
3104 * 'A tree'.
3105 *
3106 * @static
3107 */
3108 function renderImageGallery( $text ) {
3109 # Setup the parser
3110 global $wgUser, $wgParser, $wgTitle;
3111 $parserOptions = ParserOptions::newFromUser( $wgUser );
3112
3113 global $wgLinkCache;
3114 $ig = new ImageGallery();
3115 $ig->setShowBytes( false );
3116 $ig->setShowFilename( false );
3117 $lines = explode( "\n", $text );
3118
3119 foreach ( $lines as $line ) {
3120 # match lines like these:
3121 # Image:someimage.jpg|This is some image
3122 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3123 # Skip empty lines
3124 if ( count( $matches ) == 0 ) {
3125 continue;
3126 }
3127 $nt = Title::newFromURL( $matches[1] );
3128 if( is_null( $nt ) ) {
3129 # Bogus title. Ignore these so we don't bomb out later.
3130 continue;
3131 }
3132 if ( isset( $matches[3] ) ) {
3133 $label = $matches[3];
3134 } else {
3135 $label = '';
3136 }
3137
3138 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
3139 $html = $html->mText;
3140
3141 $ig->add( new Image( $nt ), $html );
3142 $wgLinkCache->addImageLinkObj( $nt );
3143 }
3144 return $ig->toHTML();
3145 }
3146
3147 /**
3148 * Parse image options text and use it to make an image
3149 */
3150 function makeImage( &$nt, $options ) {
3151 global $wgContLang, $wgUseImageResize;
3152 global $wgUser, $wgThumbLimits;
3153
3154 $align = '';
3155
3156 # Check if the options text is of the form "options|alt text"
3157 # Options are:
3158 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3159 # * left no resizing, just left align. label is used for alt= only
3160 # * right same, but right aligned
3161 # * none same, but not aligned
3162 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3163 # * center center the image
3164 # * framed Keep original image size, no magnify-button.
3165
3166 $part = explode( '|', $options);
3167
3168 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3169 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3170 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3171 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3172 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3173 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3174 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3175 $caption = '';
3176
3177 $width = $height = $framed = $thumb = false;
3178 $manual_thumb = "" ;
3179
3180 foreach( $part as $key => $val ) {
3181 $val_parts = explode ( "=" , $val , 2 ) ;
3182 $left_part = array_shift ( $val_parts ) ;
3183 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3184 $thumb=true;
3185 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3186 # use manually specified thumbnail
3187 $thumb=true;
3188 $manual_thumb = array_shift ( $val_parts ) ;
3189 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3190 # remember to set an alignment, don't render immediately
3191 $align = 'right';
3192 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3193 # remember to set an alignment, don't render immediately
3194 $align = 'left';
3195 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3196 # remember to set an alignment, don't render immediately
3197 $align = 'center';
3198 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3199 # remember to set an alignment, don't render immediately
3200 $align = 'none';
3201 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3202 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3203 # $match is the image width in pixels
3204 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3205 $width = intval( $m[1] );
3206 $height = intval( $m[2] );
3207 } else {
3208 $width = intval($match);
3209 }
3210 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3211 $framed=true;
3212 } else {
3213 $caption = $val;
3214 }
3215 }
3216 # Strip bad stuff out of the alt text
3217 $alt = $this->replaceLinkHoldersText( $caption );
3218 $alt = Sanitizer::stripAllTags( $alt );
3219
3220 # Linker does the rest
3221 $sk =& $this->mOptions->getSkin();
3222 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3223 }
3224 }
3225
3226 /**
3227 * @todo document
3228 * @package MediaWiki
3229 */
3230 class ParserOutput
3231 {
3232 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3233 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3234 var $mVersion; # Compatibility check
3235 var $mTitleText; # title text of the chosen language variant
3236
3237 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3238 $containsOldMagic = false, $titletext = '' )
3239 {
3240 $this->mText = $text;
3241 $this->mLanguageLinks = $languageLinks;
3242 $this->mCategoryLinks = $categoryLinks;
3243 $this->mContainsOldMagic = $containsOldMagic;
3244 $this->mCacheTime = '';
3245 $this->mVersion = MW_PARSER_VERSION;
3246 $this->mTitleText = $titletext;
3247 }
3248
3249 function getText() { return $this->mText; }
3250 function getLanguageLinks() { return $this->mLanguageLinks; }
3251 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
3252 function getCacheTime() { return $this->mCacheTime; }
3253 function getTitleText() { return $this->mTitleText; }
3254 function containsOldMagic() { return $this->mContainsOldMagic; }
3255 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3256 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3257 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
3258 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3259 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3260 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3261
3262 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
3263
3264 function merge( $other ) {
3265 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3266 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3267 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3268 }
3269
3270 /**
3271 * Return true if this cached output object predates the global or
3272 * per-article cache invalidation timestamps, or if it comes from
3273 * an incompatible older version.
3274 *
3275 * @param string $touched the affected article's last touched timestamp
3276 * @return bool
3277 * @access public
3278 */
3279 function expired( $touched ) {
3280 global $wgCacheEpoch;
3281 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3282 $this->getCacheTime() <= $touched ||
3283 $this->getCacheTime() <= $wgCacheEpoch ||
3284 !isset( $this->mVersion ) ||
3285 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3286 }
3287 }
3288
3289 /**
3290 * Set options of the Parser
3291 * @todo document
3292 * @package MediaWiki
3293 */
3294 class ParserOptions
3295 {
3296 # All variables are private
3297 var $mUseTeX; # Use texvc to expand <math> tags
3298 var $mUseDynamicDates; # Use DateFormatter to format dates
3299 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3300 var $mAllowExternalImages; # Allow external images inline
3301 var $mSkin; # Reference to the preferred skin
3302 var $mDateFormat; # Date format index
3303 var $mEditSection; # Create "edit section" links
3304 var $mNumberHeadings; # Automatically number headings
3305 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3306
3307 function getUseTeX() { return $this->mUseTeX; }
3308 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3309 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3310 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3311 function getSkin() { return $this->mSkin; }
3312 function getDateFormat() { return $this->mDateFormat; }
3313 function getEditSection() { return $this->mEditSection; }
3314 function getNumberHeadings() { return $this->mNumberHeadings; }
3315 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3316
3317
3318 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3319 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3320 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3321 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3322 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3323 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3324 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3325 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3326
3327 function setSkin( &$x ) { $this->mSkin =& $x; }
3328
3329 function ParserOptions() {
3330 global $wgUser;
3331 $this->initialiseFromUser( $wgUser );
3332 }
3333
3334 /**
3335 * Get parser options
3336 * @static
3337 */
3338 function newFromUser( &$user ) {
3339 $popts = new ParserOptions;
3340 $popts->initialiseFromUser( $user );
3341 return $popts;
3342 }
3343
3344 /** Get user options */
3345 function initialiseFromUser( &$userInput ) {
3346 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3347 $wgAllowSpecialInclusion;
3348 $fname = 'ParserOptions::initialiseFromUser';
3349 wfProfileIn( $fname );
3350 if ( !$userInput ) {
3351 $user = new User;
3352 $user->setLoaded( true );
3353 } else {
3354 $user =& $userInput;
3355 }
3356
3357 $this->mUseTeX = $wgUseTeX;
3358 $this->mUseDynamicDates = $wgUseDynamicDates;
3359 $this->mInterwikiMagic = $wgInterwikiMagic;
3360 $this->mAllowExternalImages = $wgAllowExternalImages;
3361 wfProfileIn( $fname.'-skin' );
3362 $this->mSkin =& $user->getSkin();
3363 wfProfileOut( $fname.'-skin' );
3364 $this->mDateFormat = $user->getOption( 'date' );
3365 $this->mEditSection = $user->getOption( 'editsection' );
3366 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3367 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
3368 wfProfileOut( $fname );
3369 }
3370 }
3371
3372 /**
3373 * Callback function used by Parser::replaceLinkHolders()
3374 * to substitute link placeholders.
3375 */
3376 function &wfOutputReplaceMatches( $matches ) {
3377 global $wgOutputReplace;
3378 return $wgOutputReplace[$matches[1]];
3379 }
3380
3381 /**
3382 * Return the total number of articles
3383 */
3384 function wfNumberOfArticles() {
3385 global $wgNumberOfArticles;
3386
3387 wfLoadSiteStats();
3388 return $wgNumberOfArticles;
3389 }
3390
3391 /**
3392 * Get various statistics from the database
3393 * @private
3394 */
3395 function wfLoadSiteStats() {
3396 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3397 $fname = 'wfLoadSiteStats';
3398
3399 if ( -1 != $wgNumberOfArticles ) return;
3400 $dbr =& wfGetDB( DB_SLAVE );
3401 $s = $dbr->selectRow( 'site_stats',
3402 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3403 array( 'ss_row_id' => 1 ), $fname
3404 );
3405
3406 if ( $s === false ) {
3407 return;
3408 } else {
3409 $wgTotalViews = $s->ss_total_views;
3410 $wgTotalEdits = $s->ss_total_edits;
3411 $wgNumberOfArticles = $s->ss_good_articles;
3412 }
3413 }
3414
3415 /**
3416 * Escape html tags
3417 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3418 *
3419 * @param string $in Text that might contain HTML tags
3420 * @return string Escaped string
3421 */
3422 function wfEscapeHTMLTagsOnly( $in ) {
3423 return str_replace(
3424 array( '"', '>', '<' ),
3425 array( '&quot;', '&gt;', '&lt;' ),
3426 $in );
3427 }
3428
3429 ?>