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