Use the new character entity reference sanitizer on wikitext as well as
[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 # set $text to cached message.
1995 $text = $linestart . $this->mTemplates[$part1];
1996 $found = true;
1997
1998 # Infinite loop test
1999 if ( isset( $this->mTemplatePath[$part1] ) ) {
2000 $noparse = true;
2001 $found = true;
2002 $text .= '<!-- WARNING: template loop detected -->';
2003 }
2004 }
2005
2006 # Load from database
2007 $itcamefromthedatabase = false;
2008 if ( !$found ) {
2009 $ns = NS_TEMPLATE;
2010 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2011 if ($subpage !== '') {
2012 $ns = $this->mTitle->getNamespace();
2013 }
2014 $title = Title::newFromText( $part1, $ns );
2015 if ( !is_null( $title ) && !$title->isExternal() ) {
2016 # Check for excessive inclusion
2017 $dbk = $title->getPrefixedDBkey();
2018 if ( $this->incrementIncludeCount( $dbk ) ) {
2019 # This should never be reached.
2020 $article = new Article( $title );
2021 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2022 if ( $articleContent !== false ) {
2023 $found = true;
2024 $text = $linestart . $articleContent;
2025 $itcamefromthedatabase = true;
2026 }
2027 }
2028
2029 # If the title is valid but undisplayable, make a link to it
2030 if ( $this->mOutputType == OT_HTML && !$found ) {
2031 $text = $linestart . '[['.$title->getPrefixedText().']]';
2032 $found = true;
2033 }
2034
2035 # Template cache array insertion
2036 if( $found ) {
2037 $this->mTemplates[$part1] = $text;
2038 }
2039 }
2040 }
2041
2042 # Recursive parsing, escaping and link table handling
2043 # Only for HTML output
2044 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2045 $text = wfEscapeWikiText( $text );
2046 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2047 # Clean up argument array
2048 $assocArgs = array();
2049 $index = 1;
2050 foreach( $args as $arg ) {
2051 $eqpos = strpos( $arg, '=' );
2052 if ( $eqpos === false ) {
2053 $assocArgs[$index++] = $arg;
2054 } else {
2055 $name = trim( substr( $arg, 0, $eqpos ) );
2056 $value = trim( substr( $arg, $eqpos+1 ) );
2057 if ( $value === false ) {
2058 $value = '';
2059 }
2060 if ( $name !== false ) {
2061 $assocArgs[$name] = $value;
2062 }
2063 }
2064 }
2065
2066 # Add a new element to the templace recursion path
2067 $this->mTemplatePath[$part1] = 1;
2068
2069 $text = $this->strip( $text, $this->mStripState );
2070 $text = Sanitizer::removeHTMLtags( $text );
2071 $text = $this->replaceVariables( $text, $assocArgs );
2072
2073 # Resume the link cache and register the inclusion as a link
2074 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2075 $wgLinkCache->addLinkObj( $title );
2076 }
2077
2078 # If the template begins with a table or block-level
2079 # element, it should be treated as beginning a new line.
2080 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2081 $text = "\n" . $text;
2082 }
2083 }
2084
2085 # Empties the template path
2086 $this->mTemplatePath = array();
2087 if ( !$found ) {
2088 wfProfileOut( $fname );
2089 return $matches[0];
2090 } else {
2091 # replace ==section headers==
2092 # XXX this needs to go away once we have a better parser.
2093 if ( $this->mOutputType != OT_WIKI && $itcamefromthedatabase ) {
2094 if( !is_null( $title ) )
2095 $encodedname = base64_encode($title->getPrefixedDBkey());
2096 else
2097 $encodedname = base64_encode("");
2098 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2099 PREG_SPLIT_DELIM_CAPTURE);
2100 $text = '';
2101 $nsec = 0;
2102 for( $i = 0; $i < count($m); $i += 2 ) {
2103 $text .= $m[$i];
2104 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2105 $hl = $m[$i + 1];
2106 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2107 $text .= $hl;
2108 continue;
2109 }
2110 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2111 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2112 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2113
2114 $nsec++;
2115 }
2116 }
2117 }
2118
2119 # Empties the template path
2120 $this->mTemplatePath = array();
2121
2122 if ( !$found ) {
2123 wfProfileOut( $fname );
2124 return $matches[0];
2125 } else {
2126 wfProfileOut( $fname );
2127 return $text;
2128 }
2129 }
2130
2131 /**
2132 * Triple brace replacement -- used for template arguments
2133 * @access private
2134 */
2135 function argSubstitution( $matches ) {
2136 $arg = trim( $matches[1] );
2137 $text = $matches[0];
2138 $inputArgs = end( $this->mArgStack );
2139
2140 if ( array_key_exists( $arg, $inputArgs ) ) {
2141 $text = $inputArgs[$arg];
2142 }
2143
2144 return $text;
2145 }
2146
2147 /**
2148 * Returns true if the function is allowed to include this entity
2149 * @access private
2150 */
2151 function incrementIncludeCount( $dbk ) {
2152 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2153 $this->mIncludeCount[$dbk] = 0;
2154 }
2155 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2156 return true;
2157 } else {
2158 return false;
2159 }
2160 }
2161
2162 /**
2163 * This function accomplishes several tasks:
2164 * 1) Auto-number headings if that option is enabled
2165 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2166 * 3) Add a Table of contents on the top for users who have enabled the option
2167 * 4) Auto-anchor headings
2168 *
2169 * It loops through all headlines, collects the necessary data, then splits up the
2170 * string and re-inserts the newly formatted headlines.
2171 *
2172 * @param string $text
2173 * @param boolean $isMain
2174 * @access private
2175 */
2176 function formatHeadings( $text, $isMain=true ) {
2177 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2178
2179 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2180 $doShowToc = $this->mOptions->getShowToc();
2181 $forceTocHere = false;
2182 if( !$this->mTitle->userCanEdit() ) {
2183 $showEditLink = 0;
2184 $rightClickHack = 0;
2185 } else {
2186 $showEditLink = $this->mOptions->getEditSection();
2187 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
2188 }
2189
2190 # Inhibit editsection links if requested in the page
2191 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2192 if( $esw->matchAndRemove( $text ) ) {
2193 $showEditLink = 0;
2194 }
2195 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2196 # do not add TOC
2197 $mw =& MagicWord::get( MAG_NOTOC );
2198 if( $mw->matchAndRemove( $text ) ) {
2199 $doShowToc = 0;
2200 }
2201
2202 # never add the TOC to the Main Page. This is an entry page that should not
2203 # be more than 1-2 screens large anyway
2204 if( $this->mTitle->getPrefixedText() == wfMsg('mainpage') ) {
2205 $doShowToc = 0;
2206 }
2207
2208 # Get all headlines for numbering them and adding funky stuff like [edit]
2209 # links - this is for later, but we need the number of headlines right now
2210 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2211
2212 # if there are fewer than 4 headlines in the article, do not show TOC
2213 if( $numMatches < 4 ) {
2214 $doShowToc = 0;
2215 }
2216
2217 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2218 # override above conditions and always show TOC at that place
2219
2220 $mw =& MagicWord::get( MAG_TOC );
2221 if($mw->match( $text ) ) {
2222 $doShowToc = 1;
2223 $forceTocHere = true;
2224 } else {
2225 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2226 # override above conditions and always show TOC above first header
2227 $mw =& MagicWord::get( MAG_FORCETOC );
2228 if ($mw->matchAndRemove( $text ) ) {
2229 $doShowToc = 1;
2230 }
2231 }
2232
2233 # Never ever show TOC if no headers
2234 if( $numMatches < 1 ) {
2235 $doShowToc = 0;
2236 }
2237
2238 # We need this to perform operations on the HTML
2239 $sk =& $this->mOptions->getSkin();
2240
2241 # headline counter
2242 $headlineCount = 0;
2243 $sectionCount = 0; # headlineCount excluding template sections
2244
2245 # Ugh .. the TOC should have neat indentation levels which can be
2246 # passed to the skin functions. These are determined here
2247 $toc = '';
2248 $full = '';
2249 $head = array();
2250 $sublevelCount = array();
2251 $levelCount = array();
2252 $toclevel = 0;
2253 $level = 0;
2254 $prevlevel = 0;
2255 $toclevel = 0;
2256 $prevtoclevel = 0;
2257
2258 foreach( $matches[3] as $headline ) {
2259 $istemplate = 0;
2260 $templatetitle = '';
2261 $templatesection = 0;
2262 $numbering = '';
2263
2264 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2265 $istemplate = 1;
2266 $templatetitle = base64_decode($mat[1]);
2267 $templatesection = 1 + (int)base64_decode($mat[2]);
2268 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2269 }
2270
2271 if( $toclevel ) {
2272 $prevlevel = $level;
2273 $prevtoclevel = $toclevel;
2274 }
2275 $level = $matches[1][$headlineCount];
2276
2277 if( $doNumberHeadings || $doShowToc ) {
2278
2279 if ( $level > $prevlevel ) {
2280 # Increase TOC level
2281 $toclevel++;
2282 $sublevelCount[$toclevel] = 0;
2283 $toc .= $sk->tocIndent();
2284 }
2285 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2286 # Decrease TOC level, find level to jump to
2287
2288 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2289 # Can only go down to level 1
2290 $toclevel = 1;
2291 } else {
2292 for ($i = $toclevel; $i > 0; $i--) {
2293 if ( $levelCount[$i] == $level ) {
2294 # Found last matching level
2295 $toclevel = $i;
2296 break;
2297 }
2298 elseif ( $levelCount[$i] < $level ) {
2299 # Found first matching level below current level
2300 $toclevel = $i + 1;
2301 break;
2302 }
2303 }
2304 }
2305
2306 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2307 }
2308 else {
2309 # No change in level, end TOC line
2310 $toc .= $sk->tocLineEnd();
2311 }
2312
2313 $levelCount[$toclevel] = $level;
2314
2315 # count number of headlines for each level
2316 @$sublevelCount[$toclevel]++;
2317 $dot = 0;
2318 for( $i = 1; $i <= $toclevel; $i++ ) {
2319 if( !empty( $sublevelCount[$i] ) ) {
2320 if( $dot ) {
2321 $numbering .= '.';
2322 }
2323 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2324 $dot = 1;
2325 }
2326 }
2327 }
2328
2329 # The canonized header is a version of the header text safe to use for links
2330 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2331 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2332 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2333
2334 # Remove link placeholders by the link text.
2335 # <!--LINK number-->
2336 # turns into
2337 # link text with suffix
2338 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2339 "\$wgLinkHolders['texts'][\$1]",
2340 $canonized_headline );
2341 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2342 "\$wgInterwikiLinkHolders[\$1]",
2343 $canonized_headline );
2344
2345 # strip out HTML
2346 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2347 $tocline = trim( $canonized_headline );
2348 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
2349 $replacearray = array(
2350 '%3A' => ':',
2351 '%' => '.'
2352 );
2353 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2354 $refer[$headlineCount] = $canonized_headline;
2355
2356 # count how many in assoc. array so we can track dupes in anchors
2357 @$refers[$canonized_headline]++;
2358 $refcount[$headlineCount]=$refers[$canonized_headline];
2359
2360 # Don't number the heading if it is the only one (looks silly)
2361 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2362 # the two are different if the line contains a link
2363 $headline=$numbering . ' ' . $headline;
2364 }
2365
2366 # Create the anchor for linking from the TOC to the section
2367 $anchor = $canonized_headline;
2368 if($refcount[$headlineCount] > 1 ) {
2369 $anchor .= '_' . $refcount[$headlineCount];
2370 }
2371 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2372 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2373 }
2374 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2375 if ( empty( $head[$headlineCount] ) ) {
2376 $head[$headlineCount] = '';
2377 }
2378 if( $istemplate )
2379 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2380 else
2381 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2382 }
2383
2384 # Add the edit section span
2385 if( $rightClickHack ) {
2386 if( $istemplate )
2387 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2388 else
2389 $headline = $sk->editSectionScript($this->mTitle, $sectionCount+1,$headline);
2390 }
2391
2392 # give headline the correct <h#> tag
2393 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2394
2395 $headlineCount++;
2396 if( !$istemplate )
2397 $sectionCount++;
2398 }
2399
2400 if( $doShowToc ) {
2401 $toclines = $headlineCount;
2402 $toc .= $sk->tocUnindent( $toclevel - 1 );
2403 $toc = $sk->tocList( $toc );
2404 }
2405
2406 # split up and insert constructed headlines
2407
2408 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2409 $i = 0;
2410
2411 foreach( $blocks as $block ) {
2412 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2413 # This is the [edit] link that appears for the top block of text when
2414 # section editing is enabled
2415
2416 # Disabled because it broke block formatting
2417 # For example, a bullet point in the top line
2418 # $full .= $sk->editSectionLink(0);
2419 }
2420 $full .= $block;
2421 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2422 # Top anchor now in skin
2423 $full = $full.$toc;
2424 }
2425
2426 if( !empty( $head[$i] ) ) {
2427 $full .= $head[$i];
2428 }
2429 $i++;
2430 }
2431 if($forceTocHere) {
2432 $mw =& MagicWord::get( MAG_TOC );
2433 return $mw->replace( $toc, $full );
2434 } else {
2435 return $full;
2436 }
2437 }
2438
2439 /**
2440 * Return an HTML link for the "ISBN 123456" text
2441 * @access private
2442 */
2443 function magicISBN( $text ) {
2444 global $wgLang;
2445 $fname = 'Parser::magicISBN';
2446 wfProfileIn( $fname );
2447
2448 $a = split( 'ISBN ', ' '.$text );
2449 if ( count ( $a ) < 2 ) {
2450 wfProfileOut( $fname );
2451 return $text;
2452 }
2453 $text = substr( array_shift( $a ), 1);
2454 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2455
2456 foreach ( $a as $x ) {
2457 $isbn = $blank = '' ;
2458 while ( ' ' == $x{0} ) {
2459 $blank .= ' ';
2460 $x = substr( $x, 1 );
2461 }
2462 if ( $x == '' ) { # blank isbn
2463 $text .= "ISBN $blank";
2464 continue;
2465 }
2466 while ( strstr( $valid, $x{0} ) != false ) {
2467 $isbn .= $x{0};
2468 $x = substr( $x, 1 );
2469 }
2470 $num = str_replace( '-', '', $isbn );
2471 $num = str_replace( ' ', '', $num );
2472
2473 if ( '' == $num ) {
2474 $text .= "ISBN $blank$x";
2475 } else {
2476 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2477 $text .= '<a href="' .
2478 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2479 "\" class=\"internal\">ISBN $isbn</a>";
2480 $text .= $x;
2481 }
2482 }
2483 wfProfileOut( $fname );
2484 return $text;
2485 }
2486
2487 /**
2488 * Return an HTML link for the "GEO ..." text
2489 * @access private
2490 */
2491 function magicGEO( $text ) {
2492 global $wgLang, $wgUseGeoMode;
2493 $fname = 'Parser::magicGEO';
2494 wfProfileIn( $fname );
2495
2496 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2497 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2498 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2499 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2500 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2501 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2502
2503 $a = split( 'GEO ', ' '.$text );
2504 if ( count ( $a ) < 2 ) {
2505 wfProfileOut( $fname );
2506 return $text;
2507 }
2508 $text = substr( array_shift( $a ), 1);
2509 $valid = '0123456789.+-:';
2510
2511 foreach ( $a as $x ) {
2512 $geo = $blank = '' ;
2513 while ( ' ' == $x{0} ) {
2514 $blank .= ' ';
2515 $x = substr( $x, 1 );
2516 }
2517 while ( strstr( $valid, $x{0} ) != false ) {
2518 $geo .= $x{0};
2519 $x = substr( $x, 1 );
2520 }
2521 $num = str_replace( '+', '', $geo );
2522 $num = str_replace( ' ', '', $num );
2523
2524 if ( '' == $num || count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2525 $text .= "GEO $blank$x";
2526 } else {
2527 $titleObj = Title::makeTitle( NS_SPECIAL, 'Geo' );
2528 $text .= '<a href="' .
2529 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2530 "\" class=\"internal\">GEO $geo</a>";
2531 $text .= $x;
2532 }
2533 }
2534 wfProfileOut( $fname );
2535 return $text;
2536 }
2537
2538 /**
2539 * Return an HTML link for the "RFC 1234" text
2540 * @access private
2541 * @param string $text text to be processed
2542 */
2543 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2544 global $wgLang;
2545
2546 $valid = '0123456789';
2547 $internal = false;
2548
2549 $a = split( $keyword, ' '.$text );
2550 if ( count ( $a ) < 2 ) {
2551 return $text;
2552 }
2553 $text = substr( array_shift( $a ), 1);
2554
2555 /* Check if keyword is preceed by [[.
2556 * This test is made here cause of the array_shift above
2557 * that prevent the test to be done in the foreach.
2558 */
2559 if ( substr( $text, -2 ) == '[[' ) {
2560 $internal = true;
2561 }
2562
2563 foreach ( $a as $x ) {
2564 /* token might be empty if we have RFC RFC 1234 */
2565 if ( $x=='' ) {
2566 $text.=$keyword;
2567 continue;
2568 }
2569
2570 $id = $blank = '' ;
2571
2572 /** remove and save whitespaces in $blank */
2573 while ( $x{0} == ' ' ) {
2574 $blank .= ' ';
2575 $x = substr( $x, 1 );
2576 }
2577
2578 /** remove and save the rfc number in $id */
2579 while ( strstr( $valid, $x{0} ) != false ) {
2580 $id .= $x{0};
2581 $x = substr( $x, 1 );
2582 }
2583
2584 if ( $id == '' ) {
2585 /* call back stripped spaces*/
2586 $text .= $keyword.$blank.$x;
2587 } elseif( $internal ) {
2588 /* normal link */
2589 $text .= $keyword.$id.$x;
2590 } else {
2591 /* build the external link*/
2592 $url = wfmsg( $urlmsg );
2593 $url = str_replace( '$1', $id, $url);
2594 $sk =& $this->mOptions->getSkin();
2595 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2596 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2597 }
2598
2599 /* Check if the next RFC keyword is preceed by [[ */
2600 $internal = ( substr($x,-2) == '[[' );
2601 }
2602 return $text;
2603 }
2604
2605 /**
2606 * Transform wiki markup when saving a page by doing \r\n -> \n
2607 * conversion, substitting signatures, {{subst:}} templates, etc.
2608 *
2609 * @param string $text the text to transform
2610 * @param Title &$title the Title object for the current article
2611 * @param User &$user the User object describing the current user
2612 * @param ParserOptions $options parsing options
2613 * @param bool $clearState whether to clear the parser state first
2614 * @return string the altered wiki markup
2615 * @access public
2616 */
2617 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2618 $this->mOptions = $options;
2619 $this->mTitle =& $title;
2620 $this->mOutputType = OT_WIKI;
2621
2622 if ( $clearState ) {
2623 $this->clearState();
2624 }
2625
2626 $stripState = false;
2627 $pairs = array(
2628 "\r\n" => "\n",
2629 );
2630 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2631 $text = $this->strip( $text, $stripState, false );
2632 $text = $this->pstPass2( $text, $user );
2633 $text = $this->unstrip( $text, $stripState );
2634 $text = $this->unstripNoWiki( $text, $stripState );
2635 return $text;
2636 }
2637
2638 /**
2639 * Pre-save transform helper function
2640 * @access private
2641 */
2642 function pstPass2( $text, &$user ) {
2643 global $wgLang, $wgContLang, $wgLocaltimezone;
2644
2645 # Variable replacement
2646 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2647 $text = $this->replaceVariables( $text );
2648
2649 # Signatures
2650 #
2651 $n = $user->getName();
2652 $k = $user->getOption( 'nickname' );
2653 if ( '' == $k ) { $k = $n; }
2654 if ( isset( $wgLocaltimezone ) ) {
2655 $oldtz = getenv( 'TZ' );
2656 putenv( 'TZ='.$wgLocaltimezone );
2657 }
2658 /* Note: this is an ugly timezone hack for the European wikis */
2659 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2660 ' (' . date( 'T' ) . ')';
2661 if ( isset( $wgLocaltimezone ) ) {
2662 putenv( 'TZ='.$oldtzs );
2663 }
2664
2665 if( $user->getOption( 'fancysig' ) ) {
2666 $sigText = $k;
2667 } else {
2668 $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
2669 }
2670 $text = preg_replace( '/~~~~~/', $d, $text );
2671 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2672 $text = preg_replace( '/~~~/', $sigText, $text );
2673
2674 # Context links: [[|name]] and [[name (context)|]]
2675 #
2676 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2677 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2678 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2679 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2680
2681 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2682 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2683 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2684 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2685 $context = '';
2686 $t = $this->mTitle->getText();
2687 if ( preg_match( $conpat, $t, $m ) ) {
2688 $context = $m[2];
2689 }
2690 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2691 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2692 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2693
2694 if ( '' == $context ) {
2695 $text = preg_replace( $p2, '[[\\1]]', $text );
2696 } else {
2697 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2698 }
2699
2700 # Trim trailing whitespace
2701 # MAG_END (__END__) tag allows for trailing
2702 # whitespace to be deliberately included
2703 $text = rtrim( $text );
2704 $mw =& MagicWord::get( MAG_END );
2705 $mw->matchAndRemove( $text );
2706
2707 return $text;
2708 }
2709
2710 /**
2711 * Set up some variables which are usually set up in parse()
2712 * so that an external function can call some class members with confidence
2713 * @access public
2714 */
2715 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2716 $this->mTitle =& $title;
2717 $this->mOptions = $options;
2718 $this->mOutputType = $outputType;
2719 if ( $clearState ) {
2720 $this->clearState();
2721 }
2722 }
2723
2724 /**
2725 * Transform a MediaWiki message by replacing magic variables.
2726 *
2727 * @param string $text the text to transform
2728 * @param ParserOptions $options options
2729 * @return string the text with variables substituted
2730 * @access public
2731 */
2732 function transformMsg( $text, $options ) {
2733 global $wgTitle;
2734 static $executing = false;
2735
2736 # Guard against infinite recursion
2737 if ( $executing ) {
2738 return $text;
2739 }
2740 $executing = true;
2741
2742 $this->mTitle = $wgTitle;
2743 $this->mOptions = $options;
2744 $this->mOutputType = OT_MSG;
2745 $this->clearState();
2746 $text = $this->replaceVariables( $text );
2747
2748 $executing = false;
2749 return $text;
2750 }
2751
2752 /**
2753 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2754 * Callback will be called with the text within
2755 * Transform and return the text within
2756 * @access public
2757 */
2758 function setHook( $tag, $callback ) {
2759 $oldVal = @$this->mTagHooks[$tag];
2760 $this->mTagHooks[$tag] = $callback;
2761 return $oldVal;
2762 }
2763
2764 /**
2765 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2766 * Placeholders created in Skin::makeLinkObj()
2767 * Returns an array of links found, indexed by PDBK:
2768 * 0 - broken
2769 * 1 - normal link
2770 * 2 - stub
2771 * $options is a bit field, RLH_FOR_UPDATE to select for update
2772 */
2773 function replaceLinkHolders( &$text, $options = 0 ) {
2774 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2775 global $wgInterwikiLinkHolders;
2776 global $outputReplace;
2777
2778 if ( $wgUseOldExistenceCheck ) {
2779 return array();
2780 }
2781
2782 $fname = 'Parser::replaceLinkHolders';
2783 wfProfileIn( $fname );
2784
2785 $pdbks = array();
2786 $colours = array();
2787
2788 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2789 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2790 wfProfileIn( $fname.'-check' );
2791 $dbr =& wfGetDB( DB_SLAVE );
2792 $page = $dbr->tableName( 'page' );
2793 $sk = $wgUser->getSkin();
2794 $threshold = $wgUser->getOption('stubthreshold');
2795
2796 # Sort by namespace
2797 asort( $wgLinkHolders['namespaces'] );
2798
2799 # Generate query
2800 $query = false;
2801 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2802 # Make title object
2803 $title = $wgLinkHolders['titles'][$key];
2804
2805 # Skip invalid entries.
2806 # Result will be ugly, but prevents crash.
2807 if ( is_null( $title ) ) {
2808 continue;
2809 }
2810 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2811
2812 # Check if it's in the link cache already
2813 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2814 $colours[$pdbk] = 1;
2815 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2816 $colours[$pdbk] = 0;
2817 } else {
2818 # Not in the link cache, add it to the query
2819 if ( !isset( $current ) ) {
2820 $current = $val;
2821 $tables = $page;
2822 $join = '';
2823 $query = "SELECT page_id, page_namespace, page_title";
2824 if ( $threshold > 0 ) {
2825 $textTable = $dbr->tableName( 'text' );
2826 $query .= ', LENGTH(old_text) AS page_len, page_is_redirect';
2827 $tables .= ", $textTable";
2828 $join = 'page_latest=old_id AND';
2829 }
2830 $query .= " FROM $tables WHERE $join (page_namespace=$val AND page_title IN(";
2831 } elseif ( $current != $val ) {
2832 $current = $val;
2833 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2834 } else {
2835 $query .= ', ';
2836 }
2837
2838 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2839 }
2840 }
2841 if ( $query ) {
2842 $query .= '))';
2843 if ( $options & RLH_FOR_UPDATE ) {
2844 $query .= ' FOR UPDATE';
2845 }
2846
2847 $res = $dbr->query( $query, $fname );
2848
2849 # Fetch data and form into an associative array
2850 # non-existent = broken
2851 # 1 = known
2852 # 2 = stub
2853 while ( $s = $dbr->fetchObject($res) ) {
2854 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
2855 $pdbk = $title->getPrefixedDBkey();
2856 $wgLinkCache->addGoodLink( $s->page_id, $pdbk );
2857
2858 if ( $threshold > 0 ) {
2859 $size = $s->page_len;
2860 if ( $s->page_is_redirect || $s->page_namespace != 0 || $length < $threshold ) {
2861 $colours[$pdbk] = 1;
2862 } else {
2863 $colours[$pdbk] = 2;
2864 }
2865 } else {
2866 $colours[$pdbk] = 1;
2867 }
2868 }
2869 }
2870 wfProfileOut( $fname.'-check' );
2871
2872 # Construct search and replace arrays
2873 wfProfileIn( $fname.'-construct' );
2874 $outputReplace = array();
2875 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2876 $pdbk = $pdbks[$key];
2877 $searchkey = '<!--LINK '.$key.'-->';
2878 $title = $wgLinkHolders['titles'][$key];
2879 if ( empty( $colours[$pdbk] ) ) {
2880 $wgLinkCache->addBadLink( $pdbk );
2881 $colours[$pdbk] = 0;
2882 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2883 $wgLinkHolders['texts'][$key],
2884 $wgLinkHolders['queries'][$key] );
2885 } elseif ( $colours[$pdbk] == 1 ) {
2886 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2887 $wgLinkHolders['texts'][$key],
2888 $wgLinkHolders['queries'][$key] );
2889 } elseif ( $colours[$pdbk] == 2 ) {
2890 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2891 $wgLinkHolders['texts'][$key],
2892 $wgLinkHolders['queries'][$key] );
2893 }
2894 }
2895 wfProfileOut( $fname.'-construct' );
2896
2897 # Do the thing
2898 wfProfileIn( $fname.'-replace' );
2899
2900 $text = preg_replace_callback(
2901 '/(<!--LINK .*?-->)/',
2902 "outputReplaceMatches",
2903 $text);
2904 wfProfileOut( $fname.'-replace' );
2905 }
2906
2907 if ( !empty( $wgInterwikiLinkHolders ) ) {
2908 wfProfileIn( $fname.'-interwiki' );
2909 $outputReplace = $wgInterwikiLinkHolders;
2910 $text = preg_replace_callback(
2911 '/<!--IWLINK (.*?)-->/',
2912 "outputReplaceMatches",
2913 $text );
2914 wfProfileOut( $fname.'-interwiki' );
2915 }
2916
2917 wfProfileOut( $fname );
2918 return $colours;
2919 }
2920
2921 /**
2922 * Renders an image gallery from a text with one line per image.
2923 * text labels may be given by using |-style alternative text. E.g.
2924 * Image:one.jpg|The number "1"
2925 * Image:tree.jpg|A tree
2926 * given as text will return the HTML of a gallery with two images,
2927 * labeled 'The number "1"' and
2928 * 'A tree'.
2929 */
2930 function renderImageGallery( $text ) {
2931 global $wgLinkCache;
2932 $ig = new ImageGallery();
2933 $ig->setShowBytes( false );
2934 $ig->setShowFilename( false );
2935 $lines = explode( "\n", $text );
2936
2937 foreach ( $lines as $line ) {
2938 # match lines like these:
2939 # Image:someimage.jpg|This is some image
2940 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
2941 # Skip empty lines
2942 if ( count( $matches ) == 0 ) {
2943 continue;
2944 }
2945 $nt = Title::newFromURL( $matches[1] );
2946 if( is_null( $nt ) ) {
2947 # Bogus title. Ignore these so we don't bomb out later.
2948 continue;
2949 }
2950 if ( isset( $matches[3] ) ) {
2951 $label = $matches[3];
2952 } else {
2953 $label = '';
2954 }
2955
2956 # FIXME: Use the full wiki parser and add its links
2957 # to the page's links.
2958 $html = $this->mOptions->mSkin->formatComment( $label );
2959
2960 $ig->add( Image::newFromTitle( $nt ), $html );
2961 $wgLinkCache->addImageLinkObj( $nt );
2962 }
2963 return $ig->toHTML();
2964 }
2965 }
2966
2967 /**
2968 * @todo document
2969 * @package MediaWiki
2970 */
2971 class ParserOutput
2972 {
2973 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2974 var $mCacheTime; # Used in ParserCache
2975 var $mVersion; # Compatibility check
2976
2977 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2978 $containsOldMagic = false )
2979 {
2980 $this->mText = $text;
2981 $this->mLanguageLinks = $languageLinks;
2982 $this->mCategoryLinks = $categoryLinks;
2983 $this->mContainsOldMagic = $containsOldMagic;
2984 $this->mCacheTime = '';
2985 $this->mVersion = MW_PARSER_VERSION;
2986 }
2987
2988 function getText() { return $this->mText; }
2989 function getLanguageLinks() { return $this->mLanguageLinks; }
2990 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
2991 function getCacheTime() { return $this->mCacheTime; }
2992 function containsOldMagic() { return $this->mContainsOldMagic; }
2993 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2994 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2995 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2996 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2997 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2998 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
2999
3000 function merge( $other ) {
3001 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3002 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3003 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3004 }
3005
3006 /**
3007 * Return true if this cached output object predates the global or
3008 * per-article cache invalidation timestamps, or if it comes from
3009 * an incompatible older version.
3010 *
3011 * @param string $touched the affected article's last touched timestamp
3012 * @return bool
3013 * @access public
3014 */
3015 function expired( $touched ) {
3016 global $wgCacheEpoch;
3017 return $this->getCacheTime() <= $touched ||
3018 $this->getCacheTime() <= $wgCacheEpoch ||
3019 !isset( $this->mVersion ) ||
3020 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3021 }
3022 }
3023
3024 /**
3025 * Set options of the Parser
3026 * @todo document
3027 * @package MediaWiki
3028 */
3029 class ParserOptions
3030 {
3031 # All variables are private
3032 var $mUseTeX; # Use texvc to expand <math> tags
3033 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
3034 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3035 var $mAllowExternalImages; # Allow external images inline
3036 var $mSkin; # Reference to the preferred skin
3037 var $mDateFormat; # Date format index
3038 var $mEditSection; # Create "edit section" links
3039 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
3040 var $mNumberHeadings; # Automatically number headings
3041 var $mShowToc; # Show table of contents
3042
3043 function getUseTeX() { return $this->mUseTeX; }
3044 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3045 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3046 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3047 function getSkin() { return $this->mSkin; }
3048 function getDateFormat() { return $this->mDateFormat; }
3049 function getEditSection() { return $this->mEditSection; }
3050 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
3051 function getNumberHeadings() { return $this->mNumberHeadings; }
3052 function getShowToc() { return $this->mShowToc; }
3053
3054 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3055 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3056 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3057 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3058 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3059 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3060 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
3061 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3062 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
3063
3064 function setSkin( &$x ) { $this->mSkin =& $x; }
3065
3066 /**
3067 * Get parser options
3068 * @static
3069 */
3070 function newFromUser( &$user ) {
3071 $popts = new ParserOptions;
3072 $popts->initialiseFromUser( $user );
3073 return $popts;
3074 }
3075
3076 /** Get user options */
3077 function initialiseFromUser( &$userInput ) {
3078 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3079 $fname = 'ParserOptions::initialiseFromUser';
3080 wfProfileIn( $fname );
3081 if ( !$userInput ) {
3082 $user = new User;
3083 $user->setLoaded( true );
3084 } else {
3085 $user =& $userInput;
3086 }
3087
3088 $this->mUseTeX = $wgUseTeX;
3089 $this->mUseDynamicDates = $wgUseDynamicDates;
3090 $this->mInterwikiMagic = $wgInterwikiMagic;
3091 $this->mAllowExternalImages = $wgAllowExternalImages;
3092 wfProfileIn( $fname.'-skin' );
3093 $this->mSkin =& $user->getSkin();
3094 wfProfileOut( $fname.'-skin' );
3095 $this->mDateFormat = $user->getOption( 'date' );
3096 $this->mEditSection = $user->getOption( 'editsection' );
3097 $this->mEditSectionOnRightClick = $user->getOption( 'editsectiononrightclick' );
3098 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3099 $this->mShowToc = $user->getOption( 'showtoc' );
3100 wfProfileOut( $fname );
3101 }
3102 }
3103
3104 /**
3105 * Callback function used by Parser::replaceLinkHolders()
3106 * to substitute link placeholders.
3107 */
3108 function &outputReplaceMatches( $matches ) {
3109 global $outputReplace;
3110 return $outputReplace[$matches[1]];
3111 }
3112
3113 /**
3114 * Return the total number of articles
3115 */
3116 function wfNumberOfArticles() {
3117 global $wgNumberOfArticles;
3118
3119 wfLoadSiteStats();
3120 return $wgNumberOfArticles;
3121 }
3122
3123 /**
3124 * Get various statistics from the database
3125 * @private
3126 */
3127 function wfLoadSiteStats() {
3128 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3129 $fname = 'wfLoadSiteStats';
3130
3131 if ( -1 != $wgNumberOfArticles ) return;
3132 $dbr =& wfGetDB( DB_SLAVE );
3133 $s = $dbr->selectRow( 'site_stats',
3134 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3135 array( 'ss_row_id' => 1 ), $fname
3136 );
3137
3138 if ( $s === false ) {
3139 return;
3140 } else {
3141 $wgTotalViews = $s->ss_total_views;
3142 $wgTotalEdits = $s->ss_total_edits;
3143 $wgNumberOfArticles = $s->ss_good_articles;
3144 }
3145 }
3146
3147 /**
3148 * Escape html tags
3149 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3150 *
3151 * @param string $in Text that might contain HTML tags
3152 * @return string Escaped string
3153 */
3154 function wfEscapeHTMLTagsOnly( $in ) {
3155 return str_replace(
3156 array( '"', '>', '<' ),
3157 array( '&quot;', '&gt;', '&lt;' ),
3158 $in );
3159 }
3160
3161 ?>