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