Use Revision for individual message loads; not using it for bulk load just now; need...
[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.4.0' );
17
18 /**
19 * Variable substitution O(N^2) attack
20 *
21 * Without countermeasures, it would be possible to attack the parser by saving
22 * a page filled with a large number of inclusions of large pages. The size of
23 * the generated page would be proportional to the square of the input size.
24 * Hence, we limit the number of inclusions of any given page, thus bringing any
25 * attack back to O(N).
26 */
27
28 define( 'MAX_INCLUDE_REPEAT', 100 );
29 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
30
31 define( 'RLH_FOR_UPDATE', 1 );
32
33 # Allowed values for $mOutputType
34 define( 'OT_HTML', 1 );
35 define( 'OT_WIKI', 2 );
36 define( 'OT_MSG' , 3 );
37
38 # string parameter for extractTags which will cause it
39 # to strip HTML comments in addition to regular
40 # <XML>-style tags. This should not be anything we
41 # may want to use in wikisyntax
42 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
43
44 # prefix for escaping, used in two functions at least
45 define( 'UNIQ_PREFIX', 'NaodW29');
46
47 # Constants needed for external link processing
48 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
49 define( 'HTTP_PROTOCOLS', 'http|https' );
50 # Everything except bracket, space, or control characters
51 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
52 # Including space
53 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
54 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
55 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
56 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS.'):'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
57 define( 'EXT_IMAGE_REGEX',
58 '/^('.HTTP_PROTOCOLS.':)'. # Protocol
59 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
60 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
61 );
62
63 /**
64 * PHP Parser
65 *
66 * Processes wiki markup
67 *
68 * <pre>
69 * There are three main entry points into the Parser class:
70 * parse()
71 * produces HTML output
72 * preSaveTransform().
73 * produces altered wiki markup.
74 * transformMsg()
75 * performs brace substitution on MediaWiki messages
76 *
77 * Globals used:
78 * objects: $wgLang, $wgDateFormatter, $wgLinkCache
79 *
80 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 *
82 * settings:
83 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
84 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
85 * $wgLocaltimezone
86 *
87 * * only within ParserOptions
88 * </pre>
89 *
90 * @package MediaWiki
91 */
92 class Parser
93 {
94 /**#@+
95 * @access private
96 */
97 # Persistent:
98 var $mTagHooks;
99
100 # Cleared with clearState():
101 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
102 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
103
104 # Temporary:
105 var $mOptions, $mTitle, $mOutputType,
106 $mTemplates, // cache of already loaded templates, avoids
107 // multiple SQL queries for the same string
108 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
109 // in this path. Used for loop detection.
110
111 /**#@-*/
112
113 /**
114 * Constructor
115 *
116 * @access public
117 */
118 function Parser() {
119 $this->mTemplates = array();
120 $this->mTemplatePath = array();
121 $this->mTagHooks = array();
122 $this->clearState();
123 }
124
125 /**
126 * Clear Parser state
127 *
128 * @access private
129 */
130 function clearState() {
131 $this->mOutput = new ParserOutput;
132 $this->mAutonumber = 0;
133 $this->mLastSection = '';
134 $this->mDTopen = false;
135 $this->mVariables = false;
136 $this->mIncludeCount = array();
137 $this->mStripState = array();
138 $this->mArgStack = array();
139 $this->mInPre = false;
140 }
141
142 /**
143 * First pass--just handle <nowiki> sections, pass the rest off
144 * to internalParse() which does all the real work.
145 *
146 * @access private
147 * @param string $text Text we want to parse
148 * @param Title &$title A title object
149 * @param array $options
150 * @param boolean $linestart
151 * @param boolean $clearState
152 * @return ParserOutput a ParserOutput
153 */
154 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
155 global $wgUseTidy, $wgContLang;
156 $fname = 'Parser::parse';
157 wfProfileIn( $fname );
158
159 if ( $clearState ) {
160 $this->clearState();
161 }
162
163 $this->mOptions = $options;
164 $this->mTitle =& $title;
165 $this->mOutputType = OT_HTML;
166
167 $stripState = NULL;
168 global $fnord; $fnord = 1;
169 //$text = $this->strip( $text, $this->mStripState );
170 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
171 $x =& $this->mStripState;
172 $text = $this->strip( $text, $x );
173
174 $text = $this->internalParse( $text, $linestart );
175
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;
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_CURRENTDAY:
1716 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1717 case MAG_PAGENAME:
1718 return $this->mTitle->getText();
1719 case MAG_PAGENAMEE:
1720 return $this->mTitle->getPartialURL();
1721 case MAG_NAMESPACE:
1722 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1723 return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1724 case MAG_CURRENTDAYNAME:
1725 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1726 case MAG_CURRENTYEAR:
1727 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1728 case MAG_CURRENTTIME:
1729 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1730 case MAG_CURRENTWEEK:
1731 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1732 case MAG_CURRENTDOW:
1733 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1734 case MAG_NUMBEROFARTICLES:
1735 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1736 case MAG_SITENAME:
1737 return $wgSitename;
1738 case MAG_SERVER:
1739 return $wgServer;
1740 default:
1741 return NULL;
1742 }
1743 }
1744
1745 /**
1746 * initialise the magic variables (like CURRENTMONTHNAME)
1747 *
1748 * @access private
1749 */
1750 function initialiseVariables() {
1751 $fname = 'Parser::initialiseVariables';
1752 wfProfileIn( $fname );
1753 global $wgVariableIDs;
1754 $this->mVariables = array();
1755 foreach ( $wgVariableIDs as $id ) {
1756 $mw =& MagicWord::get( $id );
1757 $mw->addToArray( $this->mVariables, $id );
1758 }
1759 wfProfileOut( $fname );
1760 }
1761
1762 /**
1763 * Replace magic variables, templates, and template arguments
1764 * with the appropriate text. Templates are substituted recursively,
1765 * taking care to avoid infinite loops.
1766 *
1767 * Note that the substitution depends on value of $mOutputType:
1768 * OT_WIKI: only {{subst:}} templates
1769 * OT_MSG: only magic variables
1770 * OT_HTML: all templates and magic variables
1771 *
1772 * @param string $tex The text to transform
1773 * @param array $args Key-value pairs representing template parameters to substitute
1774 * @access private
1775 */
1776 function replaceVariables( $text, $args = array() ) {
1777 global $wgLang, $wgScript, $wgArticlePath;
1778
1779 # Prevent too big inclusions
1780 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
1781 return $text;
1782 }
1783
1784 $fname = 'Parser::replaceVariables';
1785 wfProfileIn( $fname );
1786
1787 $titleChars = Title::legalChars();
1788
1789 # This function is called recursively. To keep track of arguments we need a stack:
1790 array_push( $this->mArgStack, $args );
1791
1792 # Variable substitution
1793 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1794
1795 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
1796 # Argument substitution
1797 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1798 }
1799 # Template substitution
1800 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1801 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1802
1803 array_pop( $this->mArgStack );
1804
1805 wfProfileOut( $fname );
1806 return $text;
1807 }
1808
1809 /**
1810 * Replace magic variables
1811 * @access private
1812 */
1813 function variableSubstitution( $matches ) {
1814 $fname = 'parser::variableSubstitution';
1815 $varname = $matches[1];
1816 wfProfileIn( $fname );
1817 if ( !$this->mVariables ) {
1818 $this->initialiseVariables();
1819 }
1820 $skip = false;
1821 if ( $this->mOutputType == OT_WIKI ) {
1822 # Do only magic variables prefixed by SUBST
1823 $mwSubst =& MagicWord::get( MAG_SUBST );
1824 if (!$mwSubst->matchStartAndRemove( $varname ))
1825 $skip = true;
1826 # Note that if we don't substitute the variable below,
1827 # we don't remove the {{subst:}} magic word, in case
1828 # it is a template rather than a magic variable.
1829 }
1830 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
1831 $id = $this->mVariables[$varname];
1832 $text = $this->getVariableValue( $id );
1833 $this->mOutput->mContainsOldMagic = true;
1834 } else {
1835 $text = $matches[0];
1836 }
1837 wfProfileOut( $fname );
1838 return $text;
1839 }
1840
1841 # Split template arguments
1842 function getTemplateArgs( $argsString ) {
1843 if ( $argsString === '' ) {
1844 return array();
1845 }
1846
1847 $args = explode( '|', substr( $argsString, 1 ) );
1848
1849 # If any of the arguments contains a '[[' but no ']]', it needs to be
1850 # merged with the next arg because the '|' character between belongs
1851 # to the link syntax and not the template parameter syntax.
1852 $argc = count($args);
1853 $i = 0;
1854 for ( $i = 0; $i < $argc-1; $i++ ) {
1855 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1856 $args[$i] .= '|'.$args[$i+1];
1857 array_splice($args, $i+1, 1);
1858 $i--;
1859 $argc--;
1860 }
1861 }
1862
1863 return $args;
1864 }
1865
1866 /**
1867 * Return the text of a template, after recursively
1868 * replacing any variables or templates within the template.
1869 *
1870 * @param array $matches The parts of the template
1871 * $matches[1]: the title, i.e. the part before the |
1872 * $matches[2]: the parameters (including a leading |), if any
1873 * @return string the text of the template
1874 * @access private
1875 */
1876 function braceSubstitution( $matches ) {
1877 global $wgLinkCache, $wgContLang;
1878 $fname = 'Parser::braceSubstitution';
1879 wfProfileIn( $fname );
1880
1881 $found = false;
1882 $nowiki = false;
1883 $noparse = false;
1884
1885 $title = NULL;
1886
1887 # Need to know if the template comes at the start of a line,
1888 # to treat the beginning of the template like the beginning
1889 # of a line for tables and block-level elements.
1890 $linestart = $matches[1];
1891
1892 # $part1 is the bit before the first |, and must contain only title characters
1893 # $args is a list of arguments, starting from index 0, not including $part1
1894
1895 $part1 = $matches[2];
1896 # If the third subpattern matched anything, it will start with |
1897
1898 $args = $this->getTemplateArgs($matches[3]);
1899 $argc = count( $args );
1900
1901 # Don't parse {{{}}} because that's only for template arguments
1902 if ( $linestart === '{' ) {
1903 $text = $matches[0];
1904 $found = true;
1905 $noparse = true;
1906 }
1907
1908 # SUBST
1909 if ( !$found ) {
1910 $mwSubst =& MagicWord::get( MAG_SUBST );
1911 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
1912 # One of two possibilities is true:
1913 # 1) Found SUBST but not in the PST phase
1914 # 2) Didn't find SUBST and in the PST phase
1915 # In either case, return without further processing
1916 $text = $matches[0];
1917 $found = true;
1918 $noparse = true;
1919 }
1920 }
1921
1922 # MSG, MSGNW and INT
1923 if ( !$found ) {
1924 # Check for MSGNW:
1925 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1926 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1927 $nowiki = true;
1928 } else {
1929 # Remove obsolete MSG:
1930 $mwMsg =& MagicWord::get( MAG_MSG );
1931 $mwMsg->matchStartAndRemove( $part1 );
1932 }
1933
1934 # Check if it is an internal message
1935 $mwInt =& MagicWord::get( MAG_INT );
1936 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1937 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1938 $text = $linestart . wfMsgReal( $part1, $args, true );
1939 $found = true;
1940 }
1941 }
1942 }
1943
1944 # NS
1945 if ( !$found ) {
1946 # Check for NS: (namespace expansion)
1947 $mwNs = MagicWord::get( MAG_NS );
1948 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1949 if ( intval( $part1 ) ) {
1950 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1951 $found = true;
1952 } else {
1953 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1954 if ( !is_null( $index ) ) {
1955 $text = $linestart . $wgContLang->getNsText( $index );
1956 $found = true;
1957 }
1958 }
1959 }
1960 }
1961
1962 # LOCALURL and LOCALURLE
1963 if ( !$found ) {
1964 $mwLocal = MagicWord::get( MAG_LOCALURL );
1965 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1966
1967 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1968 $func = 'getLocalURL';
1969 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1970 $func = 'escapeLocalURL';
1971 } else {
1972 $func = '';
1973 }
1974
1975 if ( $func !== '' ) {
1976 $title = Title::newFromText( $part1 );
1977 if ( !is_null( $title ) ) {
1978 if ( $argc > 0 ) {
1979 $text = $linestart . $title->$func( $args[0] );
1980 } else {
1981 $text = $linestart . $title->$func();
1982 }
1983 $found = true;
1984 }
1985 }
1986 }
1987
1988 # GRAMMAR
1989 if ( !$found && $argc == 1 ) {
1990 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
1991 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1992 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
1993 $found = true;
1994 }
1995 }
1996
1997 # Template table test
1998
1999 # Did we encounter this template already? If yes, it is in the cache
2000 # and we need to check for loops.
2001 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
2002 $found = true;
2003
2004 # Infinite loop test
2005 if ( isset( $this->mTemplatePath[$part1] ) ) {
2006 $noparse = true;
2007 $found = true;
2008 $text = $linestart .
2009 "\{\{$part1}}" .
2010 '<!-- WARNING: template loop detected -->';
2011 wfDebug( "$fname: template loop broken at '$part1'\n" );
2012 } else {
2013 # set $text to cached message.
2014 $text = $linestart . $this->mTemplates[$part1];
2015 }
2016 }
2017
2018 # Load from database
2019 $itcamefromthedatabase = false;
2020 $lastPathLevel = $this->mTemplatePath;
2021 if ( !$found ) {
2022 $ns = NS_TEMPLATE;
2023 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2024 if ($subpage !== '') {
2025 $ns = $this->mTitle->getNamespace();
2026 }
2027 $title = Title::newFromText( $part1, $ns );
2028 if ( !is_null( $title ) && !$title->isExternal() ) {
2029 # Check for excessive inclusion
2030 $dbk = $title->getPrefixedDBkey();
2031 if ( $this->incrementIncludeCount( $dbk ) ) {
2032 # This should never be reached.
2033 $article = new Article( $title );
2034 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2035 if ( $articleContent !== false ) {
2036 $found = true;
2037 $text = $linestart . $articleContent;
2038 $itcamefromthedatabase = true;
2039 }
2040 }
2041
2042 # If the title is valid but undisplayable, make a link to it
2043 if ( $this->mOutputType == OT_HTML && !$found ) {
2044 $text = $linestart . '[['.$title->getPrefixedText().']]';
2045 $found = true;
2046 }
2047
2048 # Template cache array insertion
2049 if( $found ) {
2050 $this->mTemplates[$part1] = $text;
2051 }
2052 }
2053 }
2054
2055 # Recursive parsing, escaping and link table handling
2056 # Only for HTML output
2057 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2058 $text = wfEscapeWikiText( $text );
2059 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2060 # Clean up argument array
2061 $assocArgs = array();
2062 $index = 1;
2063 foreach( $args as $arg ) {
2064 $eqpos = strpos( $arg, '=' );
2065 if ( $eqpos === false ) {
2066 $assocArgs[$index++] = $arg;
2067 } else {
2068 $name = trim( substr( $arg, 0, $eqpos ) );
2069 $value = trim( substr( $arg, $eqpos+1 ) );
2070 if ( $value === false ) {
2071 $value = '';
2072 }
2073 if ( $name !== false ) {
2074 $assocArgs[$name] = $value;
2075 }
2076 }
2077 }
2078
2079 # Add a new element to the templace recursion path
2080 $this->mTemplatePath[$part1] = 1;
2081
2082 $text = $this->strip( $text, $this->mStripState );
2083 $text = Sanitizer::removeHTMLtags( $text );
2084 $text = $this->replaceVariables( $text, $assocArgs );
2085
2086 # Resume the link cache and register the inclusion as a link
2087 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2088 $wgLinkCache->addLinkObj( $title );
2089 }
2090
2091 # If the template begins with a table or block-level
2092 # element, it should be treated as beginning a new line.
2093 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2094 $text = "\n" . $text;
2095 }
2096 }
2097 # Prune lower levels off the recursion check path
2098 $this->mTemplatePath = $lastPathLevel;
2099
2100 if ( !$found ) {
2101 wfProfileOut( $fname );
2102 return $matches[0];
2103 } else {
2104 # replace ==section headers==
2105 # XXX this needs to go away once we have a better parser.
2106 if ( $this->mOutputType != OT_WIKI && $itcamefromthedatabase ) {
2107 if( !is_null( $title ) )
2108 $encodedname = base64_encode($title->getPrefixedDBkey());
2109 else
2110 $encodedname = base64_encode("");
2111 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2112 PREG_SPLIT_DELIM_CAPTURE);
2113 $text = '';
2114 $nsec = 0;
2115 for( $i = 0; $i < count($m); $i += 2 ) {
2116 $text .= $m[$i];
2117 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2118 $hl = $m[$i + 1];
2119 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2120 $text .= $hl;
2121 continue;
2122 }
2123 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2124 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2125 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2126
2127 $nsec++;
2128 }
2129 }
2130 }
2131 # Prune lower levels off the recursion check path
2132 $this->mTemplatePath = $lastPathLevel;
2133
2134 if ( !$found ) {
2135 wfProfileOut( $fname );
2136 return $matches[0];
2137 } else {
2138 wfProfileOut( $fname );
2139 return $text;
2140 }
2141 }
2142
2143 /**
2144 * Triple brace replacement -- used for template arguments
2145 * @access private
2146 */
2147 function argSubstitution( $matches ) {
2148 $arg = trim( $matches[1] );
2149 $text = $matches[0];
2150 $inputArgs = end( $this->mArgStack );
2151
2152 if ( array_key_exists( $arg, $inputArgs ) ) {
2153 $text = $inputArgs[$arg];
2154 }
2155
2156 return $text;
2157 }
2158
2159 /**
2160 * Returns true if the function is allowed to include this entity
2161 * @access private
2162 */
2163 function incrementIncludeCount( $dbk ) {
2164 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2165 $this->mIncludeCount[$dbk] = 0;
2166 }
2167 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2168 return true;
2169 } else {
2170 return false;
2171 }
2172 }
2173
2174 /**
2175 * This function accomplishes several tasks:
2176 * 1) Auto-number headings if that option is enabled
2177 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2178 * 3) Add a Table of contents on the top for users who have enabled the option
2179 * 4) Auto-anchor headings
2180 *
2181 * It loops through all headlines, collects the necessary data, then splits up the
2182 * string and re-inserts the newly formatted headlines.
2183 *
2184 * @param string $text
2185 * @param boolean $isMain
2186 * @access private
2187 */
2188 function formatHeadings( $text, $isMain=true ) {
2189 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2190
2191 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2192 $doShowToc = $this->mOptions->getShowToc();
2193 $forceTocHere = false;
2194 if( !$this->mTitle->userCanEdit() ) {
2195 $showEditLink = 0;
2196 $rightClickHack = 0;
2197 } else {
2198 $showEditLink = $this->mOptions->getEditSection();
2199 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
2200 }
2201
2202 # Inhibit editsection links if requested in the page
2203 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2204 if( $esw->matchAndRemove( $text ) ) {
2205 $showEditLink = 0;
2206 }
2207 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2208 # do not add TOC
2209 $mw =& MagicWord::get( MAG_NOTOC );
2210 if( $mw->matchAndRemove( $text ) ) {
2211 $doShowToc = 0;
2212 }
2213
2214 # Get all headlines for numbering them and adding funky stuff like [edit]
2215 # links - this is for later, but we need the number of headlines right now
2216 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2217
2218 # if there are fewer than 4 headlines in the article, do not show TOC
2219 if( $numMatches < 4 ) {
2220 $doShowToc = 0;
2221 }
2222
2223 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2224 # override above conditions and always show TOC at that place
2225
2226 $mw =& MagicWord::get( MAG_TOC );
2227 if($mw->match( $text ) ) {
2228 $doShowToc = 1;
2229 $forceTocHere = true;
2230 } else {
2231 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2232 # override above conditions and always show TOC above first header
2233 $mw =& MagicWord::get( MAG_FORCETOC );
2234 if ($mw->matchAndRemove( $text ) ) {
2235 $doShowToc = 1;
2236 }
2237 }
2238
2239 # Never ever show TOC if no headers
2240 if( $numMatches < 1 ) {
2241 $doShowToc = 0;
2242 }
2243
2244 # We need this to perform operations on the HTML
2245 $sk =& $this->mOptions->getSkin();
2246
2247 # headline counter
2248 $headlineCount = 0;
2249 $sectionCount = 0; # headlineCount excluding template sections
2250
2251 # Ugh .. the TOC should have neat indentation levels which can be
2252 # passed to the skin functions. These are determined here
2253 $toc = '';
2254 $full = '';
2255 $head = array();
2256 $sublevelCount = array();
2257 $levelCount = array();
2258 $toclevel = 0;
2259 $level = 0;
2260 $prevlevel = 0;
2261 $toclevel = 0;
2262 $prevtoclevel = 0;
2263
2264 foreach( $matches[3] as $headline ) {
2265 $istemplate = 0;
2266 $templatetitle = '';
2267 $templatesection = 0;
2268 $numbering = '';
2269
2270 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2271 $istemplate = 1;
2272 $templatetitle = base64_decode($mat[1]);
2273 $templatesection = 1 + (int)base64_decode($mat[2]);
2274 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2275 }
2276
2277 if( $toclevel ) {
2278 $prevlevel = $level;
2279 $prevtoclevel = $toclevel;
2280 }
2281 $level = $matches[1][$headlineCount];
2282
2283 if( $doNumberHeadings || $doShowToc ) {
2284
2285 if ( $level > $prevlevel ) {
2286 # Increase TOC level
2287 $toclevel++;
2288 $sublevelCount[$toclevel] = 0;
2289 $toc .= $sk->tocIndent();
2290 }
2291 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2292 # Decrease TOC level, find level to jump to
2293
2294 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2295 # Can only go down to level 1
2296 $toclevel = 1;
2297 } else {
2298 for ($i = $toclevel; $i > 0; $i--) {
2299 if ( $levelCount[$i] == $level ) {
2300 # Found last matching level
2301 $toclevel = $i;
2302 break;
2303 }
2304 elseif ( $levelCount[$i] < $level ) {
2305 # Found first matching level below current level
2306 $toclevel = $i + 1;
2307 break;
2308 }
2309 }
2310 }
2311
2312 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2313 }
2314 else {
2315 # No change in level, end TOC line
2316 $toc .= $sk->tocLineEnd();
2317 }
2318
2319 $levelCount[$toclevel] = $level;
2320
2321 # count number of headlines for each level
2322 @$sublevelCount[$toclevel]++;
2323 $dot = 0;
2324 for( $i = 1; $i <= $toclevel; $i++ ) {
2325 if( !empty( $sublevelCount[$i] ) ) {
2326 if( $dot ) {
2327 $numbering .= '.';
2328 }
2329 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2330 $dot = 1;
2331 }
2332 }
2333 }
2334
2335 # The canonized header is a version of the header text safe to use for links
2336 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2337 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2338 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2339
2340 # Remove link placeholders by the link text.
2341 # <!--LINK number-->
2342 # turns into
2343 # link text with suffix
2344 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2345 "\$wgLinkHolders['texts'][\$1]",
2346 $canonized_headline );
2347 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2348 "\$wgInterwikiLinkHolders[\$1]",
2349 $canonized_headline );
2350
2351 # strip out HTML
2352 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2353 $tocline = trim( $canonized_headline );
2354 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
2355 $replacearray = array(
2356 '%3A' => ':',
2357 '%' => '.'
2358 );
2359 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2360 $refer[$headlineCount] = $canonized_headline;
2361
2362 # count how many in assoc. array so we can track dupes in anchors
2363 @$refers[$canonized_headline]++;
2364 $refcount[$headlineCount]=$refers[$canonized_headline];
2365
2366 # Don't number the heading if it is the only one (looks silly)
2367 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2368 # the two are different if the line contains a link
2369 $headline=$numbering . ' ' . $headline;
2370 }
2371
2372 # Create the anchor for linking from the TOC to the section
2373 $anchor = $canonized_headline;
2374 if($refcount[$headlineCount] > 1 ) {
2375 $anchor .= '_' . $refcount[$headlineCount];
2376 }
2377 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2378 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2379 }
2380 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2381 if ( empty( $head[$headlineCount] ) ) {
2382 $head[$headlineCount] = '';
2383 }
2384 if( $istemplate )
2385 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2386 else
2387 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2388 }
2389
2390 # Add the edit section span
2391 if( $rightClickHack ) {
2392 if( $istemplate )
2393 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2394 else
2395 $headline = $sk->editSectionScript($this->mTitle, $sectionCount+1,$headline);
2396 }
2397
2398 # give headline the correct <h#> tag
2399 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2400
2401 $headlineCount++;
2402 if( !$istemplate )
2403 $sectionCount++;
2404 }
2405
2406 if( $doShowToc ) {
2407 $toclines = $headlineCount;
2408 $toc .= $sk->tocUnindent( $toclevel - 1 );
2409 $toc = $sk->tocList( $toc );
2410 }
2411
2412 # split up and insert constructed headlines
2413
2414 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2415 $i = 0;
2416
2417 foreach( $blocks as $block ) {
2418 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2419 # This is the [edit] link that appears for the top block of text when
2420 # section editing is enabled
2421
2422 # Disabled because it broke block formatting
2423 # For example, a bullet point in the top line
2424 # $full .= $sk->editSectionLink(0);
2425 }
2426 $full .= $block;
2427 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2428 # Top anchor now in skin
2429 $full = $full.$toc;
2430 }
2431
2432 if( !empty( $head[$i] ) ) {
2433 $full .= $head[$i];
2434 }
2435 $i++;
2436 }
2437 if($forceTocHere) {
2438 $mw =& MagicWord::get( MAG_TOC );
2439 return $mw->replace( $toc, $full );
2440 } else {
2441 return $full;
2442 }
2443 }
2444
2445 /**
2446 * Return an HTML link for the "ISBN 123456" text
2447 * @access private
2448 */
2449 function magicISBN( $text ) {
2450 global $wgLang;
2451 $fname = 'Parser::magicISBN';
2452 wfProfileIn( $fname );
2453
2454 $a = split( 'ISBN ', ' '.$text );
2455 if ( count ( $a ) < 2 ) {
2456 wfProfileOut( $fname );
2457 return $text;
2458 }
2459 $text = substr( array_shift( $a ), 1);
2460 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2461
2462 foreach ( $a as $x ) {
2463 $isbn = $blank = '' ;
2464 while ( ' ' == $x{0} ) {
2465 $blank .= ' ';
2466 $x = substr( $x, 1 );
2467 }
2468 if ( $x == '' ) { # blank isbn
2469 $text .= "ISBN $blank";
2470 continue;
2471 }
2472 while ( strstr( $valid, $x{0} ) != false ) {
2473 $isbn .= $x{0};
2474 $x = substr( $x, 1 );
2475 }
2476 $num = str_replace( '-', '', $isbn );
2477 $num = str_replace( ' ', '', $num );
2478
2479 if ( '' == $num ) {
2480 $text .= "ISBN $blank$x";
2481 } else {
2482 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2483 $text .= '<a href="' .
2484 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2485 "\" class=\"internal\">ISBN $isbn</a>";
2486 $text .= $x;
2487 }
2488 }
2489 wfProfileOut( $fname );
2490 return $text;
2491 }
2492
2493 /**
2494 * Return an HTML link for the "RFC 1234" text
2495 * @access private
2496 * @param string $text text to be processed
2497 */
2498 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2499 global $wgLang;
2500
2501 $valid = '0123456789';
2502 $internal = false;
2503
2504 $a = split( $keyword, ' '.$text );
2505 if ( count ( $a ) < 2 ) {
2506 return $text;
2507 }
2508 $text = substr( array_shift( $a ), 1);
2509
2510 /* Check if keyword is preceed by [[.
2511 * This test is made here cause of the array_shift above
2512 * that prevent the test to be done in the foreach.
2513 */
2514 if ( substr( $text, -2 ) == '[[' ) {
2515 $internal = true;
2516 }
2517
2518 foreach ( $a as $x ) {
2519 /* token might be empty if we have RFC RFC 1234 */
2520 if ( $x=='' ) {
2521 $text.=$keyword;
2522 continue;
2523 }
2524
2525 $id = $blank = '' ;
2526
2527 /** remove and save whitespaces in $blank */
2528 while ( $x{0} == ' ' ) {
2529 $blank .= ' ';
2530 $x = substr( $x, 1 );
2531 }
2532
2533 /** remove and save the rfc number in $id */
2534 while ( strstr( $valid, $x{0} ) != false ) {
2535 $id .= $x{0};
2536 $x = substr( $x, 1 );
2537 }
2538
2539 if ( $id == '' ) {
2540 /* call back stripped spaces*/
2541 $text .= $keyword.$blank.$x;
2542 } elseif( $internal ) {
2543 /* normal link */
2544 $text .= $keyword.$id.$x;
2545 } else {
2546 /* build the external link*/
2547 $url = wfmsg( $urlmsg );
2548 $url = str_replace( '$1', $id, $url);
2549 $sk =& $this->mOptions->getSkin();
2550 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2551 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2552 }
2553
2554 /* Check if the next RFC keyword is preceed by [[ */
2555 $internal = ( substr($x,-2) == '[[' );
2556 }
2557 return $text;
2558 }
2559
2560 /**
2561 * Transform wiki markup when saving a page by doing \r\n -> \n
2562 * conversion, substitting signatures, {{subst:}} templates, etc.
2563 *
2564 * @param string $text the text to transform
2565 * @param Title &$title the Title object for the current article
2566 * @param User &$user the User object describing the current user
2567 * @param ParserOptions $options parsing options
2568 * @param bool $clearState whether to clear the parser state first
2569 * @return string the altered wiki markup
2570 * @access public
2571 */
2572 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2573 $this->mOptions = $options;
2574 $this->mTitle =& $title;
2575 $this->mOutputType = OT_WIKI;
2576
2577 if ( $clearState ) {
2578 $this->clearState();
2579 }
2580
2581 $stripState = false;
2582 $pairs = array(
2583 "\r\n" => "\n",
2584 );
2585 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2586 $text = $this->strip( $text, $stripState, false );
2587 $text = $this->pstPass2( $text, $user );
2588 $text = $this->unstrip( $text, $stripState );
2589 $text = $this->unstripNoWiki( $text, $stripState );
2590 return $text;
2591 }
2592
2593 /**
2594 * Pre-save transform helper function
2595 * @access private
2596 */
2597 function pstPass2( $text, &$user ) {
2598 global $wgLang, $wgContLang, $wgLocaltimezone;
2599
2600 # Variable replacement
2601 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2602 $text = $this->replaceVariables( $text );
2603
2604 # Signatures
2605 #
2606 $n = $user->getName();
2607 $k = $user->getOption( 'nickname' );
2608 if ( '' == $k ) { $k = $n; }
2609 if ( isset( $wgLocaltimezone ) ) {
2610 $oldtz = getenv( 'TZ' );
2611 putenv( 'TZ='.$wgLocaltimezone );
2612 }
2613 /* Note: this is an ugly timezone hack for the European wikis */
2614 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2615 ' (' . date( 'T' ) . ')';
2616 if ( isset( $wgLocaltimezone ) ) {
2617 putenv( 'TZ='.$oldtzs );
2618 }
2619
2620 if( $user->getOption( 'fancysig' ) ) {
2621 $sigText = $k;
2622 } else {
2623 $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
2624 }
2625 $text = preg_replace( '/~~~~~/', $d, $text );
2626 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2627 $text = preg_replace( '/~~~/', $sigText, $text );
2628
2629 # Context links: [[|name]] and [[name (context)|]]
2630 #
2631 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2632 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2633 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2634 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2635
2636 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2637 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2638 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2639 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2640 $context = '';
2641 $t = $this->mTitle->getText();
2642 if ( preg_match( $conpat, $t, $m ) ) {
2643 $context = $m[2];
2644 }
2645 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2646 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2647 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2648
2649 if ( '' == $context ) {
2650 $text = preg_replace( $p2, '[[\\1]]', $text );
2651 } else {
2652 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2653 }
2654
2655 # Trim trailing whitespace
2656 # MAG_END (__END__) tag allows for trailing
2657 # whitespace to be deliberately included
2658 $text = rtrim( $text );
2659 $mw =& MagicWord::get( MAG_END );
2660 $mw->matchAndRemove( $text );
2661
2662 return $text;
2663 }
2664
2665 /**
2666 * Set up some variables which are usually set up in parse()
2667 * so that an external function can call some class members with confidence
2668 * @access public
2669 */
2670 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2671 $this->mTitle =& $title;
2672 $this->mOptions = $options;
2673 $this->mOutputType = $outputType;
2674 if ( $clearState ) {
2675 $this->clearState();
2676 }
2677 }
2678
2679 /**
2680 * Transform a MediaWiki message by replacing magic variables.
2681 *
2682 * @param string $text the text to transform
2683 * @param ParserOptions $options options
2684 * @return string the text with variables substituted
2685 * @access public
2686 */
2687 function transformMsg( $text, $options ) {
2688 global $wgTitle;
2689 static $executing = false;
2690
2691 # Guard against infinite recursion
2692 if ( $executing ) {
2693 return $text;
2694 }
2695 $executing = true;
2696
2697 $this->mTitle = $wgTitle;
2698 $this->mOptions = $options;
2699 $this->mOutputType = OT_MSG;
2700 $this->clearState();
2701 $text = $this->replaceVariables( $text );
2702
2703 $executing = false;
2704 return $text;
2705 }
2706
2707 /**
2708 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2709 * Callback will be called with the text within
2710 * Transform and return the text within
2711 * @access public
2712 */
2713 function setHook( $tag, $callback ) {
2714 $oldVal = @$this->mTagHooks[$tag];
2715 $this->mTagHooks[$tag] = $callback;
2716 return $oldVal;
2717 }
2718
2719 /**
2720 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2721 * Placeholders created in Skin::makeLinkObj()
2722 * Returns an array of links found, indexed by PDBK:
2723 * 0 - broken
2724 * 1 - normal link
2725 * 2 - stub
2726 * $options is a bit field, RLH_FOR_UPDATE to select for update
2727 */
2728 function replaceLinkHolders( &$text, $options = 0 ) {
2729 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2730 global $wgInterwikiLinkHolders;
2731 global $outputReplace;
2732
2733 if ( $wgUseOldExistenceCheck ) {
2734 return array();
2735 }
2736
2737 $fname = 'Parser::replaceLinkHolders';
2738 wfProfileIn( $fname );
2739
2740 $pdbks = array();
2741 $colours = array();
2742
2743 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2744 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2745 wfProfileIn( $fname.'-check' );
2746 $dbr =& wfGetDB( DB_SLAVE );
2747 $page = $dbr->tableName( 'page' );
2748 $sk = $wgUser->getSkin();
2749 $threshold = $wgUser->getOption('stubthreshold');
2750
2751 # Sort by namespace
2752 asort( $wgLinkHolders['namespaces'] );
2753
2754 # Generate query
2755 $query = false;
2756 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2757 # Make title object
2758 $title = $wgLinkHolders['titles'][$key];
2759
2760 # Skip invalid entries.
2761 # Result will be ugly, but prevents crash.
2762 if ( is_null( $title ) ) {
2763 continue;
2764 }
2765 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2766
2767 # Check if it's in the link cache already
2768 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2769 $colours[$pdbk] = 1;
2770 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2771 $colours[$pdbk] = 0;
2772 } else {
2773 # Not in the link cache, add it to the query
2774 if ( !isset( $current ) ) {
2775 $current = $val;
2776 $query = "SELECT page_id, page_namespace, page_title";
2777 if ( $threshold > 0 ) {
2778 $query .= ', page_len, page_is_redirect';
2779 }
2780 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2781 } elseif ( $current != $val ) {
2782 $current = $val;
2783 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2784 } else {
2785 $query .= ', ';
2786 }
2787
2788 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2789 }
2790 }
2791 if ( $query ) {
2792 $query .= '))';
2793 if ( $options & RLH_FOR_UPDATE ) {
2794 $query .= ' FOR UPDATE';
2795 }
2796
2797 $res = $dbr->query( $query, $fname );
2798
2799 # Fetch data and form into an associative array
2800 # non-existent = broken
2801 # 1 = known
2802 # 2 = stub
2803 while ( $s = $dbr->fetchObject($res) ) {
2804 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
2805 $pdbk = $title->getPrefixedDBkey();
2806 $wgLinkCache->addGoodLink( $s->page_id, $pdbk );
2807
2808 if ( $threshold > 0 ) {
2809 $size = $s->page_len;
2810 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
2811 $colours[$pdbk] = 1;
2812 } else {
2813 $colours[$pdbk] = 2;
2814 }
2815 } else {
2816 $colours[$pdbk] = 1;
2817 }
2818 }
2819 }
2820 wfProfileOut( $fname.'-check' );
2821
2822 # Construct search and replace arrays
2823 wfProfileIn( $fname.'-construct' );
2824 $outputReplace = array();
2825 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2826 $pdbk = $pdbks[$key];
2827 $searchkey = '<!--LINK '.$key.'-->';
2828 $title = $wgLinkHolders['titles'][$key];
2829 if ( empty( $colours[$pdbk] ) ) {
2830 $wgLinkCache->addBadLink( $pdbk );
2831 $colours[$pdbk] = 0;
2832 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2833 $wgLinkHolders['texts'][$key],
2834 $wgLinkHolders['queries'][$key] );
2835 } elseif ( $colours[$pdbk] == 1 ) {
2836 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2837 $wgLinkHolders['texts'][$key],
2838 $wgLinkHolders['queries'][$key] );
2839 } elseif ( $colours[$pdbk] == 2 ) {
2840 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2841 $wgLinkHolders['texts'][$key],
2842 $wgLinkHolders['queries'][$key] );
2843 }
2844 }
2845 wfProfileOut( $fname.'-construct' );
2846
2847 # Do the thing
2848 wfProfileIn( $fname.'-replace' );
2849
2850 $text = preg_replace_callback(
2851 '/(<!--LINK .*?-->)/',
2852 "outputReplaceMatches",
2853 $text);
2854 wfProfileOut( $fname.'-replace' );
2855 }
2856
2857 if ( !empty( $wgInterwikiLinkHolders ) ) {
2858 wfProfileIn( $fname.'-interwiki' );
2859 $outputReplace = $wgInterwikiLinkHolders;
2860 $text = preg_replace_callback(
2861 '/<!--IWLINK (.*?)-->/',
2862 "outputReplaceMatches",
2863 $text );
2864 wfProfileOut( $fname.'-interwiki' );
2865 }
2866
2867 wfProfileOut( $fname );
2868 return $colours;
2869 }
2870
2871 /**
2872 * Renders an image gallery from a text with one line per image.
2873 * text labels may be given by using |-style alternative text. E.g.
2874 * Image:one.jpg|The number "1"
2875 * Image:tree.jpg|A tree
2876 * given as text will return the HTML of a gallery with two images,
2877 * labeled 'The number "1"' and
2878 * 'A tree'.
2879 */
2880 function renderImageGallery( $text ) {
2881 global $wgLinkCache;
2882 $ig = new ImageGallery();
2883 $ig->setShowBytes( false );
2884 $ig->setShowFilename( false );
2885 $lines = explode( "\n", $text );
2886
2887 foreach ( $lines as $line ) {
2888 # match lines like these:
2889 # Image:someimage.jpg|This is some image
2890 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
2891 # Skip empty lines
2892 if ( count( $matches ) == 0 ) {
2893 continue;
2894 }
2895 $nt = Title::newFromURL( $matches[1] );
2896 if( is_null( $nt ) ) {
2897 # Bogus title. Ignore these so we don't bomb out later.
2898 continue;
2899 }
2900 if ( isset( $matches[3] ) ) {
2901 $label = $matches[3];
2902 } else {
2903 $label = '';
2904 }
2905
2906 # FIXME: Use the full wiki parser and add its links
2907 # to the page's links.
2908 $html = $this->mOptions->mSkin->formatComment( $label );
2909
2910 $ig->add( Image::newFromTitle( $nt ), $html );
2911 $wgLinkCache->addImageLinkObj( $nt );
2912 }
2913 return $ig->toHTML();
2914 }
2915 }
2916
2917 /**
2918 * @todo document
2919 * @package MediaWiki
2920 */
2921 class ParserOutput
2922 {
2923 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2924 var $mCacheTime; # Used in ParserCache
2925 var $mVersion; # Compatibility check
2926
2927 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2928 $containsOldMagic = false )
2929 {
2930 $this->mText = $text;
2931 $this->mLanguageLinks = $languageLinks;
2932 $this->mCategoryLinks = $categoryLinks;
2933 $this->mContainsOldMagic = $containsOldMagic;
2934 $this->mCacheTime = '';
2935 $this->mVersion = MW_PARSER_VERSION;
2936 }
2937
2938 function getText() { return $this->mText; }
2939 function getLanguageLinks() { return $this->mLanguageLinks; }
2940 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
2941 function getCacheTime() { return $this->mCacheTime; }
2942 function containsOldMagic() { return $this->mContainsOldMagic; }
2943 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2944 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2945 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2946 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2947 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2948 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
2949
2950 function merge( $other ) {
2951 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2952 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2953 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2954 }
2955
2956 /**
2957 * Return true if this cached output object predates the global or
2958 * per-article cache invalidation timestamps, or if it comes from
2959 * an incompatible older version.
2960 *
2961 * @param string $touched the affected article's last touched timestamp
2962 * @return bool
2963 * @access public
2964 */
2965 function expired( $touched ) {
2966 global $wgCacheEpoch;
2967 return $this->getCacheTime() <= $touched ||
2968 $this->getCacheTime() <= $wgCacheEpoch ||
2969 !isset( $this->mVersion ) ||
2970 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
2971 }
2972 }
2973
2974 /**
2975 * Set options of the Parser
2976 * @todo document
2977 * @package MediaWiki
2978 */
2979 class ParserOptions
2980 {
2981 # All variables are private
2982 var $mUseTeX; # Use texvc to expand <math> tags
2983 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2984 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2985 var $mAllowExternalImages; # Allow external images inline
2986 var $mSkin; # Reference to the preferred skin
2987 var $mDateFormat; # Date format index
2988 var $mEditSection; # Create "edit section" links
2989 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2990 var $mNumberHeadings; # Automatically number headings
2991 var $mShowToc; # Show table of contents
2992
2993 function getUseTeX() { return $this->mUseTeX; }
2994 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2995 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2996 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2997 function getSkin() { return $this->mSkin; }
2998 function getDateFormat() { return $this->mDateFormat; }
2999 function getEditSection() { return $this->mEditSection; }
3000 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
3001 function getNumberHeadings() { return $this->mNumberHeadings; }
3002 function getShowToc() { return $this->mShowToc; }
3003
3004 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3005 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3006 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3007 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3008 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3009 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3010 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
3011 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3012 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
3013
3014 function setSkin( &$x ) { $this->mSkin =& $x; }
3015
3016 /**
3017 * Get parser options
3018 * @static
3019 */
3020 function newFromUser( &$user ) {
3021 $popts = new ParserOptions;
3022 $popts->initialiseFromUser( $user );
3023 return $popts;
3024 }
3025
3026 /** Get user options */
3027 function initialiseFromUser( &$userInput ) {
3028 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3029 $fname = 'ParserOptions::initialiseFromUser';
3030 wfProfileIn( $fname );
3031 if ( !$userInput ) {
3032 $user = new User;
3033 $user->setLoaded( true );
3034 } else {
3035 $user =& $userInput;
3036 }
3037
3038 $this->mUseTeX = $wgUseTeX;
3039 $this->mUseDynamicDates = $wgUseDynamicDates;
3040 $this->mInterwikiMagic = $wgInterwikiMagic;
3041 $this->mAllowExternalImages = $wgAllowExternalImages;
3042 wfProfileIn( $fname.'-skin' );
3043 $this->mSkin =& $user->getSkin();
3044 wfProfileOut( $fname.'-skin' );
3045 $this->mDateFormat = $user->getOption( 'date' );
3046 $this->mEditSection = $user->getOption( 'editsection' );
3047 $this->mEditSectionOnRightClick = $user->getOption( 'editsectiononrightclick' );
3048 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3049 $this->mShowToc = $user->getOption( 'showtoc' );
3050 wfProfileOut( $fname );
3051 }
3052 }
3053
3054 /**
3055 * Callback function used by Parser::replaceLinkHolders()
3056 * to substitute link placeholders.
3057 */
3058 function &outputReplaceMatches( $matches ) {
3059 global $outputReplace;
3060 return $outputReplace[$matches[1]];
3061 }
3062
3063 /**
3064 * Return the total number of articles
3065 */
3066 function wfNumberOfArticles() {
3067 global $wgNumberOfArticles;
3068
3069 wfLoadSiteStats();
3070 return $wgNumberOfArticles;
3071 }
3072
3073 /**
3074 * Get various statistics from the database
3075 * @private
3076 */
3077 function wfLoadSiteStats() {
3078 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3079 $fname = 'wfLoadSiteStats';
3080
3081 if ( -1 != $wgNumberOfArticles ) return;
3082 $dbr =& wfGetDB( DB_SLAVE );
3083 $s = $dbr->selectRow( 'site_stats',
3084 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3085 array( 'ss_row_id' => 1 ), $fname
3086 );
3087
3088 if ( $s === false ) {
3089 return;
3090 } else {
3091 $wgTotalViews = $s->ss_total_views;
3092 $wgTotalEdits = $s->ss_total_edits;
3093 $wgNumberOfArticles = $s->ss_good_articles;
3094 }
3095 }
3096
3097 /**
3098 * Escape html tags
3099 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3100 *
3101 * @param string $in Text that might contain HTML tags
3102 * @return string Escaped string
3103 */
3104 function wfEscapeHTMLTagsOnly( $in ) {
3105 return str_replace(
3106 array( '"', '>', '<' ),
3107 array( '&quot;', '&gt;', '&lt;' ),
3108 $in );
3109 }
3110
3111 ?>