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