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