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