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