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