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