Clean up experiments for special:data, special:validate, special:geo.
[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 $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
1112
1113 if ( $useLinkPrefixExtension ) {
1114 if ( preg_match( $e2, $s, $m ) ) {
1115 $first_prefix = $m[2];
1116 $s = $m[1];
1117 } else {
1118 $first_prefix = false;
1119 }
1120 } else {
1121 $prefix = '';
1122 }
1123
1124 $selflink = $this->mTitle->getPrefixedText();
1125 wfProfileOut( $fname.'-setup' );
1126
1127 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1128 $useSubpages = $this->areSubpagesAllowed();
1129
1130 # Loop for each link
1131 for ($k = 0; isset( $a[$k] ); $k++) {
1132 $line = $a[$k];
1133 if ( $useLinkPrefixExtension ) {
1134 wfProfileIn( $fname.'-prefixhandling' );
1135 if ( preg_match( $e2, $s, $m ) ) {
1136 $prefix = $m[2];
1137 $s = $m[1];
1138 } else {
1139 $prefix='';
1140 }
1141 # first link
1142 if($first_prefix) {
1143 $prefix = $first_prefix;
1144 $first_prefix = false;
1145 }
1146 wfProfileOut( $fname.'-prefixhandling' );
1147 }
1148
1149 $might_be_img = false;
1150
1151 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1152 $text = $m[2];
1153 # fix up urlencoded title texts
1154 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1155 $trail = $m[3];
1156 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1157 $might_be_img = true;
1158 $text = $m[2];
1159 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1160 $trail = "";
1161 } else { # Invalid form; output directly
1162 $s .= $prefix . '[[' . $line ;
1163 continue;
1164 }
1165
1166 # Don't allow internal links to pages containing
1167 # PROTO: where PROTO is a valid URL protocol; these
1168 # should be external links.
1169 if (preg_match('/^(\b(?:'.URL_PROTOCOLS.'):)/', $m[1])) {
1170 $s .= $prefix . '[[' . $line ;
1171 continue;
1172 }
1173
1174 # Make subpage if necessary
1175 if( $useSubpages ) {
1176 $link = $this->maybeDoSubpageLink( $m[1], $text );
1177 } else {
1178 $link = $m[1];
1179 }
1180
1181 $noforce = (substr($m[1], 0, 1) != ':');
1182 if (!$noforce) {
1183 # Strip off leading ':'
1184 $link = substr($link, 1);
1185 }
1186
1187 $nt =& Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1188 if( !$nt ) {
1189 $s .= $prefix . '[[' . $line;
1190 continue;
1191 }
1192
1193 #check other language variants of the link
1194 #if the article does not exist
1195 if( $checkVariantLink
1196 && $nt->getArticleID() == 0 ) {
1197 $wgContLang->findVariantLink($link, $nt);
1198 }
1199
1200 $ns = $nt->getNamespace();
1201 $iw = $nt->getInterWiki();
1202
1203 if ($might_be_img) { # if this is actually an invalid link
1204 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1205 $found = false;
1206 while (isset ($a[$k+1]) ) {
1207 #look at the next 'line' to see if we can close it there
1208 $next_line = array_shift(array_splice( $a, $k + 1, 1) );
1209 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1210 # the first ]] closes the inner link, the second the image
1211 $found = true;
1212 $text .= '[[' . $m[1];
1213 $trail = $m[2];
1214 break;
1215 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1216 #if there's exactly one ]] that's fine, we'll keep looking
1217 $text .= '[[' . $m[0];
1218 } else {
1219 #if $next_line is invalid too, we need look no further
1220 $text .= '[[' . $next_line;
1221 break;
1222 }
1223 }
1224 if ( !$found ) {
1225 # we couldn't find the end of this imageLink, so output it raw
1226 #but don't ignore what might be perfectly normal links in the text we've examined
1227 $text = $this->replaceInternalLinks($text);
1228 $s .= $prefix . '[[' . $link . '|' . $text;
1229 # note: no $trail, because without an end, there *is* no trail
1230 continue;
1231 }
1232 } else { #it's not an image, so output it raw
1233 $s .= $prefix . '[[' . $link . '|' . $text;
1234 # note: no $trail, because without an end, there *is* no trail
1235 continue;
1236 }
1237 }
1238
1239 $wasblank = ( '' == $text );
1240 if( $wasblank ) $text = $link;
1241
1242
1243 # Link not escaped by : , create the various objects
1244 if( $noforce ) {
1245
1246 # Interwikis
1247 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1248 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1249 $tmp = $prefix . $trail ;
1250 $s .= (trim($tmp) == '')? '': $tmp;
1251 continue;
1252 }
1253
1254 if ( $ns == NS_IMAGE ) {
1255 wfProfileIn( "$fname-image" );
1256
1257 # recursively parse links inside the image caption
1258 # actually, this will parse them in any other parameters, too,
1259 # but it might be hard to fix that, and it doesn't matter ATM
1260 $text = $this->replaceExternalLinks($text);
1261 $text = $this->replaceInternalLinks($text);
1262
1263 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1264 $s .= $prefix . str_replace('http://', 'http-noparse://', $sk->makeImageLinkObj( $nt, $text ) ) . $trail;
1265 $wgLinkCache->addImageLinkObj( $nt );
1266
1267 wfProfileOut( "$fname-image" );
1268 continue;
1269 }
1270
1271 if ( $ns == NS_CATEGORY ) {
1272 wfProfileIn( "$fname-category" );
1273 $t = $nt->getText();
1274
1275 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1276 $pPLC=$sk->postParseLinkColour();
1277 $sk->postParseLinkColour( false );
1278 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1279 $sk->postParseLinkColour( $pPLC );
1280 $wgLinkCache->resume();
1281
1282 if ( $wasblank ) {
1283 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1284 $sortkey = $this->mTitle->getText();
1285 } else {
1286 $sortkey = $this->mTitle->getPrefixedText();
1287 }
1288 } else {
1289 $sortkey = $text;
1290 }
1291 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1292 $this->mOutput->addCategoryLink( $t );
1293 $s .= $prefix . $trail ;
1294
1295 wfProfileOut( "$fname-category" );
1296 continue;
1297 }
1298 }
1299
1300 if( ( $nt->getPrefixedText() === $selflink ) &&
1301 ( $nt->getFragment() === '' ) ) {
1302 # Self-links are handled specially; generally de-link and change to bold.
1303 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1304 continue;
1305 }
1306
1307 # Special and Media are pseudo-namespaces; no pages actually exist in them
1308 if( $ns == NS_MEDIA ) {
1309 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1310 $wgLinkCache->addImageLinkObj( $nt );
1311 continue;
1312 } elseif( $ns == NS_SPECIAL ) {
1313 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1314 continue;
1315 }
1316 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1317 }
1318 $sk->postParseLinkColour( $saveParseColour );
1319 wfProfileOut( $fname );
1320 return $s;
1321 }
1322
1323 /**
1324 * Return true if subpage links should be expanded on this page.
1325 * @return bool
1326 */
1327 function areSubpagesAllowed() {
1328 # Some namespaces don't allow subpages
1329 global $wgNamespacesWithSubpages;
1330 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1331 }
1332
1333 /**
1334 * Handle link to subpage if necessary
1335 * @param string $target the source of the link
1336 * @param string &$text the link text, modified as necessary
1337 * @return string the full name of the link
1338 * @access private
1339 */
1340 function maybeDoSubpageLink($target, &$text) {
1341 # Valid link forms:
1342 # Foobar -- normal
1343 # :Foobar -- override special treatment of prefix (images, language links)
1344 # /Foobar -- convert to CurrentPage/Foobar
1345 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1346 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1347 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1348
1349 $fname = 'Parser::maybeDoSubpageLink';
1350 wfProfileIn( $fname );
1351 $ret = $target; # default return value is no change
1352
1353 # Some namespaces don't allow subpages,
1354 # so only perform processing if subpages are allowed
1355 if( $this->areSubpagesAllowed() ) {
1356 # Look at the first character
1357 if( $target != '' && $target{0} == '/' ) {
1358 # / at end means we don't want the slash to be shown
1359 if( substr( $target, -1, 1 ) == '/' ) {
1360 $target = substr( $target, 1, -1 );
1361 $noslash = $target;
1362 } else {
1363 $noslash = substr( $target, 1 );
1364 }
1365
1366 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1367 if( '' === $text ) {
1368 $text = $target;
1369 } # this might be changed for ugliness reasons
1370 } else {
1371 # check for .. subpage backlinks
1372 $dotdotcount = 0;
1373 $nodotdot = $target;
1374 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1375 ++$dotdotcount;
1376 $nodotdot = substr( $nodotdot, 3 );
1377 }
1378 if($dotdotcount > 0) {
1379 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1380 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1381 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1382 # / at the end means don't show full path
1383 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1384 $nodotdot = substr( $nodotdot, 0, -1 );
1385 if( '' === $text ) {
1386 $text = $nodotdot;
1387 }
1388 }
1389 $nodotdot = trim( $nodotdot );
1390 if( $nodotdot != '' ) {
1391 $ret .= '/' . $nodotdot;
1392 }
1393 }
1394 }
1395 }
1396 }
1397
1398 wfProfileOut( $fname );
1399 return $ret;
1400 }
1401
1402 /**#@+
1403 * Used by doBlockLevels()
1404 * @access private
1405 */
1406 /* private */ function closeParagraph() {
1407 $result = '';
1408 if ( '' != $this->mLastSection ) {
1409 $result = '</' . $this->mLastSection . ">\n";
1410 }
1411 $this->mInPre = false;
1412 $this->mLastSection = '';
1413 return $result;
1414 }
1415 # getCommon() returns the length of the longest common substring
1416 # of both arguments, starting at the beginning of both.
1417 #
1418 /* private */ function getCommon( $st1, $st2 ) {
1419 $fl = strlen( $st1 );
1420 $shorter = strlen( $st2 );
1421 if ( $fl < $shorter ) { $shorter = $fl; }
1422
1423 for ( $i = 0; $i < $shorter; ++$i ) {
1424 if ( $st1{$i} != $st2{$i} ) { break; }
1425 }
1426 return $i;
1427 }
1428 # These next three functions open, continue, and close the list
1429 # element appropriate to the prefix character passed into them.
1430 #
1431 /* private */ function openList( $char ) {
1432 $result = $this->closeParagraph();
1433
1434 if ( '*' == $char ) { $result .= '<ul><li>'; }
1435 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1436 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1437 else if ( ';' == $char ) {
1438 $result .= '<dl><dt>';
1439 $this->mDTopen = true;
1440 }
1441 else { $result = '<!-- ERR 1 -->'; }
1442
1443 return $result;
1444 }
1445
1446 /* private */ function nextItem( $char ) {
1447 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1448 else if ( ':' == $char || ';' == $char ) {
1449 $close = '</dd>';
1450 if ( $this->mDTopen ) { $close = '</dt>'; }
1451 if ( ';' == $char ) {
1452 $this->mDTopen = true;
1453 return $close . '<dt>';
1454 } else {
1455 $this->mDTopen = false;
1456 return $close . '<dd>';
1457 }
1458 }
1459 return '<!-- ERR 2 -->';
1460 }
1461
1462 /* private */ function closeList( $char ) {
1463 if ( '*' == $char ) { $text = '</li></ul>'; }
1464 else if ( '#' == $char ) { $text = '</li></ol>'; }
1465 else if ( ':' == $char ) {
1466 if ( $this->mDTopen ) {
1467 $this->mDTopen = false;
1468 $text = '</dt></dl>';
1469 } else {
1470 $text = '</dd></dl>';
1471 }
1472 }
1473 else { return '<!-- ERR 3 -->'; }
1474 return $text."\n";
1475 }
1476 /**#@-*/
1477
1478 /**
1479 * Make lists from lines starting with ':', '*', '#', etc.
1480 *
1481 * @access private
1482 * @return string the lists rendered as HTML
1483 */
1484 function doBlockLevels( $text, $linestart ) {
1485 $fname = 'Parser::doBlockLevels';
1486 wfProfileIn( $fname );
1487
1488 # Parsing through the text line by line. The main thing
1489 # happening here is handling of block-level elements p, pre,
1490 # and making lists from lines starting with * # : etc.
1491 #
1492 $textLines = explode( "\n", $text );
1493
1494 $lastPrefix = $output = $lastLine = '';
1495 $this->mDTopen = $inBlockElem = false;
1496 $prefixLength = 0;
1497 $paragraphStack = false;
1498
1499 if ( !$linestart ) {
1500 $output .= array_shift( $textLines );
1501 }
1502 foreach ( $textLines as $oLine ) {
1503 $lastPrefixLength = strlen( $lastPrefix );
1504 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1505 $preOpenMatch = preg_match('/<pre/i', $oLine );
1506 if ( !$this->mInPre ) {
1507 # Multiple prefixes may abut each other for nested lists.
1508 $prefixLength = strspn( $oLine, '*#:;' );
1509 $pref = substr( $oLine, 0, $prefixLength );
1510
1511 # eh?
1512 $pref2 = str_replace( ';', ':', $pref );
1513 $t = substr( $oLine, $prefixLength );
1514 $this->mInPre = !empty($preOpenMatch);
1515 } else {
1516 # Don't interpret any other prefixes in preformatted text
1517 $prefixLength = 0;
1518 $pref = $pref2 = '';
1519 $t = $oLine;
1520 }
1521
1522 # List generation
1523 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1524 # Same as the last item, so no need to deal with nesting or opening stuff
1525 $output .= $this->nextItem( substr( $pref, -1 ) );
1526 $paragraphStack = false;
1527
1528 if ( substr( $pref, -1 ) == ';') {
1529 # The one nasty exception: definition lists work like this:
1530 # ; title : definition text
1531 # So we check for : in the remainder text to split up the
1532 # title and definition, without b0rking links.
1533 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1534 $t = $t2;
1535 $output .= $term . $this->nextItem( ':' );
1536 }
1537 }
1538 } elseif( $prefixLength || $lastPrefixLength ) {
1539 # Either open or close a level...
1540 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1541 $paragraphStack = false;
1542
1543 while( $commonPrefixLength < $lastPrefixLength ) {
1544 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1545 --$lastPrefixLength;
1546 }
1547 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1548 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1549 }
1550 while ( $prefixLength > $commonPrefixLength ) {
1551 $char = substr( $pref, $commonPrefixLength, 1 );
1552 $output .= $this->openList( $char );
1553
1554 if ( ';' == $char ) {
1555 # FIXME: This is dupe of code above
1556 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1557 $t = $t2;
1558 $output .= $term . $this->nextItem( ':' );
1559 }
1560 }
1561 ++$commonPrefixLength;
1562 }
1563 $lastPrefix = $pref2;
1564 }
1565 if( 0 == $prefixLength ) {
1566 wfProfileIn( "$fname-paragraph" );
1567 # No prefix (not in list)--go to paragraph mode
1568 $uniq_prefix = UNIQ_PREFIX;
1569 // XXX: use a stack for nestable elements like span, table and div
1570 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1571 $closematch = preg_match(
1572 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1573 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1574 if ( $openmatch or $closematch ) {
1575 $paragraphStack = false;
1576 $output .= $this->closeParagraph();
1577 if($preOpenMatch and !$preCloseMatch) {
1578 $this->mInPre = true;
1579 }
1580 if ( $closematch ) {
1581 $inBlockElem = false;
1582 } else {
1583 $inBlockElem = true;
1584 }
1585 } else if ( !$inBlockElem && !$this->mInPre ) {
1586 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1587 // pre
1588 if ($this->mLastSection != 'pre') {
1589 $paragraphStack = false;
1590 $output .= $this->closeParagraph().'<pre>';
1591 $this->mLastSection = 'pre';
1592 }
1593 $t = substr( $t, 1 );
1594 } else {
1595 // paragraph
1596 if ( '' == trim($t) ) {
1597 if ( $paragraphStack ) {
1598 $output .= $paragraphStack.'<br />';
1599 $paragraphStack = false;
1600 $this->mLastSection = 'p';
1601 } else {
1602 if ($this->mLastSection != 'p' ) {
1603 $output .= $this->closeParagraph();
1604 $this->mLastSection = '';
1605 $paragraphStack = '<p>';
1606 } else {
1607 $paragraphStack = '</p><p>';
1608 }
1609 }
1610 } else {
1611 if ( $paragraphStack ) {
1612 $output .= $paragraphStack;
1613 $paragraphStack = false;
1614 $this->mLastSection = 'p';
1615 } else if ($this->mLastSection != 'p') {
1616 $output .= $this->closeParagraph().'<p>';
1617 $this->mLastSection = 'p';
1618 }
1619 }
1620 }
1621 }
1622 wfProfileOut( "$fname-paragraph" );
1623 }
1624 if ($paragraphStack === false) {
1625 $output .= $t."\n";
1626 }
1627 }
1628 while ( $prefixLength ) {
1629 $output .= $this->closeList( $pref2{$prefixLength-1} );
1630 --$prefixLength;
1631 }
1632 if ( '' != $this->mLastSection ) {
1633 $output .= '</' . $this->mLastSection . '>';
1634 $this->mLastSection = '';
1635 }
1636
1637 wfProfileOut( $fname );
1638 return $output;
1639 }
1640
1641 /**
1642 * Split up a string on ':', ignoring any occurences inside
1643 * <a>..</a> or <span>...</span>
1644 * @param string $str the string to split
1645 * @param string &$before set to everything before the ':'
1646 * @param string &$after set to everything after the ':'
1647 * return string the position of the ':', or false if none found
1648 */
1649 function findColonNoLinks($str, &$before, &$after) {
1650 # I wonder if we should make this count all tags, not just <a>
1651 # and <span>. That would prevent us from matching a ':' that
1652 # comes in the middle of italics other such formatting....
1653 # -- Wil
1654 $fname = 'Parser::findColonNoLinks';
1655 wfProfileIn( $fname );
1656 $pos = 0;
1657 do {
1658 $colon = strpos($str, ':', $pos);
1659
1660 if ($colon !== false) {
1661 $before = substr($str, 0, $colon);
1662 $after = substr($str, $colon + 1);
1663
1664 # Skip any ':' within <a> or <span> pairs
1665 $a = substr_count($before, '<a');
1666 $s = substr_count($before, '<span');
1667 $ca = substr_count($before, '</a>');
1668 $cs = substr_count($before, '</span>');
1669
1670 if ($a <= $ca and $s <= $cs) {
1671 # Tags are balanced before ':'; ok
1672 break;
1673 }
1674 $pos = $colon + 1;
1675 }
1676 } while ($colon !== false);
1677 wfProfileOut( $fname );
1678 return $colon;
1679 }
1680
1681 /**
1682 * Return value of a magic variable (like PAGENAME)
1683 *
1684 * @access private
1685 */
1686 function getVariableValue( $index ) {
1687 global $wgContLang, $wgSitename, $wgServer;
1688
1689 /**
1690 * Some of these require message or data lookups and can be
1691 * expensive to check many times.
1692 */
1693 static $varCache = array();
1694 if( isset( $varCache[$index] ) ) return $varCache[$index];
1695
1696 switch ( $index ) {
1697 case MAG_CURRENTMONTH:
1698 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1699 case MAG_CURRENTMONTHNAME:
1700 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1701 case MAG_CURRENTMONTHNAMEGEN:
1702 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1703 case MAG_CURRENTDAY:
1704 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1705 case MAG_PAGENAME:
1706 return $this->mTitle->getText();
1707 case MAG_PAGENAMEE:
1708 return $this->mTitle->getPartialURL();
1709 case MAG_NAMESPACE:
1710 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1711 return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1712 case MAG_CURRENTDAYNAME:
1713 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1714 case MAG_CURRENTYEAR:
1715 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1716 case MAG_CURRENTTIME:
1717 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1718 case MAG_CURRENTWEEK:
1719 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1720 case MAG_CURRENTDOW:
1721 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1722 case MAG_NUMBEROFARTICLES:
1723 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1724 case MAG_SITENAME:
1725 return $wgSitename;
1726 case MAG_SERVER:
1727 return $wgServer;
1728 default:
1729 return NULL;
1730 }
1731 }
1732
1733 /**
1734 * initialise the magic variables (like CURRENTMONTHNAME)
1735 *
1736 * @access private
1737 */
1738 function initialiseVariables() {
1739 $fname = 'Parser::initialiseVariables';
1740 wfProfileIn( $fname );
1741 global $wgVariableIDs;
1742 $this->mVariables = array();
1743 foreach ( $wgVariableIDs as $id ) {
1744 $mw =& MagicWord::get( $id );
1745 $mw->addToArray( $this->mVariables, $id );
1746 }
1747 wfProfileOut( $fname );
1748 }
1749
1750 /**
1751 * Replace magic variables, templates, and template arguments
1752 * with the appropriate text. Templates are substituted recursively,
1753 * taking care to avoid infinite loops.
1754 *
1755 * Note that the substitution depends on value of $mOutputType:
1756 * OT_WIKI: only {{subst:}} templates
1757 * OT_MSG: only magic variables
1758 * OT_HTML: all templates and magic variables
1759 *
1760 * @param string $tex The text to transform
1761 * @param array $args Key-value pairs representing template parameters to substitute
1762 * @access private
1763 */
1764 function replaceVariables( $text, $args = array() ) {
1765 global $wgLang, $wgScript, $wgArticlePath;
1766
1767 # Prevent too big inclusions
1768 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
1769 return $text;
1770 }
1771
1772 $fname = 'Parser::replaceVariables';
1773 wfProfileIn( $fname );
1774
1775 $titleChars = Title::legalChars();
1776
1777 # This function is called recursively. To keep track of arguments we need a stack:
1778 array_push( $this->mArgStack, $args );
1779
1780 # Variable substitution
1781 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1782
1783 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
1784 # Argument substitution
1785 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1786 }
1787 # Template substitution
1788 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1789 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1790
1791 array_pop( $this->mArgStack );
1792
1793 wfProfileOut( $fname );
1794 return $text;
1795 }
1796
1797 /**
1798 * Replace magic variables
1799 * @access private
1800 */
1801 function variableSubstitution( $matches ) {
1802 $fname = 'parser::variableSubstitution';
1803 $varname = $matches[1];
1804 wfProfileIn( $fname );
1805 if ( !$this->mVariables ) {
1806 $this->initialiseVariables();
1807 }
1808 $skip = false;
1809 if ( $this->mOutputType == OT_WIKI ) {
1810 # Do only magic variables prefixed by SUBST
1811 $mwSubst =& MagicWord::get( MAG_SUBST );
1812 if (!$mwSubst->matchStartAndRemove( $varname ))
1813 $skip = true;
1814 # Note that if we don't substitute the variable below,
1815 # we don't remove the {{subst:}} magic word, in case
1816 # it is a template rather than a magic variable.
1817 }
1818 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
1819 $id = $this->mVariables[$varname];
1820 $text = $this->getVariableValue( $id );
1821 $this->mOutput->mContainsOldMagic = true;
1822 } else {
1823 $text = $matches[0];
1824 }
1825 wfProfileOut( $fname );
1826 return $text;
1827 }
1828
1829 # Split template arguments
1830 function getTemplateArgs( $argsString ) {
1831 if ( $argsString === '' ) {
1832 return array();
1833 }
1834
1835 $args = explode( '|', substr( $argsString, 1 ) );
1836
1837 # If any of the arguments contains a '[[' but no ']]', it needs to be
1838 # merged with the next arg because the '|' character between belongs
1839 # to the link syntax and not the template parameter syntax.
1840 $argc = count($args);
1841 $i = 0;
1842 for ( $i = 0; $i < $argc-1; $i++ ) {
1843 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1844 $args[$i] .= '|'.$args[$i+1];
1845 array_splice($args, $i+1, 1);
1846 $i--;
1847 $argc--;
1848 }
1849 }
1850
1851 return $args;
1852 }
1853
1854 /**
1855 * Return the text of a template, after recursively
1856 * replacing any variables or templates within the template.
1857 *
1858 * @param array $matches The parts of the template
1859 * $matches[1]: the title, i.e. the part before the |
1860 * $matches[2]: the parameters (including a leading |), if any
1861 * @return string the text of the template
1862 * @access private
1863 */
1864 function braceSubstitution( $matches ) {
1865 global $wgLinkCache, $wgContLang;
1866 $fname = 'Parser::braceSubstitution';
1867 wfProfileIn( $fname );
1868
1869 $found = false;
1870 $nowiki = false;
1871 $noparse = false;
1872
1873 $title = NULL;
1874
1875 # Need to know if the template comes at the start of a line,
1876 # to treat the beginning of the template like the beginning
1877 # of a line for tables and block-level elements.
1878 $linestart = $matches[1];
1879
1880 # $part1 is the bit before the first |, and must contain only title characters
1881 # $args is a list of arguments, starting from index 0, not including $part1
1882
1883 $part1 = $matches[2];
1884 # If the third subpattern matched anything, it will start with |
1885
1886 $args = $this->getTemplateArgs($matches[3]);
1887 $argc = count( $args );
1888
1889 # Don't parse {{{}}} because that's only for template arguments
1890 if ( $linestart === '{' ) {
1891 $text = $matches[0];
1892 $found = true;
1893 $noparse = true;
1894 }
1895
1896 # SUBST
1897 if ( !$found ) {
1898 $mwSubst =& MagicWord::get( MAG_SUBST );
1899 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
1900 # One of two possibilities is true:
1901 # 1) Found SUBST but not in the PST phase
1902 # 2) Didn't find SUBST and in the PST phase
1903 # In either case, return without further processing
1904 $text = $matches[0];
1905 $found = true;
1906 $noparse = true;
1907 }
1908 }
1909
1910 # MSG, MSGNW and INT
1911 if ( !$found ) {
1912 # Check for MSGNW:
1913 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1914 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1915 $nowiki = true;
1916 } else {
1917 # Remove obsolete MSG:
1918 $mwMsg =& MagicWord::get( MAG_MSG );
1919 $mwMsg->matchStartAndRemove( $part1 );
1920 }
1921
1922 # Check if it is an internal message
1923 $mwInt =& MagicWord::get( MAG_INT );
1924 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1925 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1926 $text = $linestart . wfMsgReal( $part1, $args, true );
1927 $found = true;
1928 }
1929 }
1930 }
1931
1932 # NS
1933 if ( !$found ) {
1934 # Check for NS: (namespace expansion)
1935 $mwNs = MagicWord::get( MAG_NS );
1936 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1937 if ( intval( $part1 ) ) {
1938 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1939 $found = true;
1940 } else {
1941 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1942 if ( !is_null( $index ) ) {
1943 $text = $linestart . $wgContLang->getNsText( $index );
1944 $found = true;
1945 }
1946 }
1947 }
1948 }
1949
1950 # LOCALURL and LOCALURLE
1951 if ( !$found ) {
1952 $mwLocal = MagicWord::get( MAG_LOCALURL );
1953 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1954
1955 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1956 $func = 'getLocalURL';
1957 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1958 $func = 'escapeLocalURL';
1959 } else {
1960 $func = '';
1961 }
1962
1963 if ( $func !== '' ) {
1964 $title = Title::newFromText( $part1 );
1965 if ( !is_null( $title ) ) {
1966 if ( $argc > 0 ) {
1967 $text = $linestart . $title->$func( $args[0] );
1968 } else {
1969 $text = $linestart . $title->$func();
1970 }
1971 $found = true;
1972 }
1973 }
1974 }
1975
1976 # GRAMMAR
1977 if ( !$found && $argc == 1 ) {
1978 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
1979 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1980 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
1981 $found = true;
1982 }
1983 }
1984
1985 # Template table test
1986
1987 # Did we encounter this template already? If yes, it is in the cache
1988 # and we need to check for loops.
1989 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
1990 $found = true;
1991
1992 # Infinite loop test
1993 if ( isset( $this->mTemplatePath[$part1] ) ) {
1994 $noparse = true;
1995 $found = true;
1996 $text = $linestart .
1997 "\{\{$part1}}" .
1998 '<!-- WARNING: template loop detected -->';
1999 wfDebug( "$fname: template loop broken at '$part1'\n" );
2000 } else {
2001 # set $text to cached message.
2002 $text = $linestart . $this->mTemplates[$part1];
2003 }
2004 }
2005
2006 # Load from database
2007 $itcamefromthedatabase = false;
2008 $lastPathLevel = $this->mTemplatePath;
2009 if ( !$found ) {
2010 $ns = NS_TEMPLATE;
2011 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2012 if ($subpage !== '') {
2013 $ns = $this->mTitle->getNamespace();
2014 }
2015 $title = Title::newFromText( $part1, $ns );
2016 if ( !is_null( $title ) && !$title->isExternal() ) {
2017 # Check for excessive inclusion
2018 $dbk = $title->getPrefixedDBkey();
2019 if ( $this->incrementIncludeCount( $dbk ) ) {
2020 # This should never be reached.
2021 $article = new Article( $title );
2022 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2023 if ( $articleContent !== false ) {
2024 $found = true;
2025 $text = $linestart . $articleContent;
2026 $itcamefromthedatabase = true;
2027 }
2028 }
2029
2030 # If the title is valid but undisplayable, make a link to it
2031 if ( $this->mOutputType == OT_HTML && !$found ) {
2032 $text = $linestart . '[['.$title->getPrefixedText().']]';
2033 $found = true;
2034 }
2035
2036 # Template cache array insertion
2037 if( $found ) {
2038 $this->mTemplates[$part1] = $text;
2039 }
2040 }
2041 }
2042
2043 # Recursive parsing, escaping and link table handling
2044 # Only for HTML output
2045 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2046 $text = wfEscapeWikiText( $text );
2047 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2048 # Clean up argument array
2049 $assocArgs = array();
2050 $index = 1;
2051 foreach( $args as $arg ) {
2052 $eqpos = strpos( $arg, '=' );
2053 if ( $eqpos === false ) {
2054 $assocArgs[$index++] = $arg;
2055 } else {
2056 $name = trim( substr( $arg, 0, $eqpos ) );
2057 $value = trim( substr( $arg, $eqpos+1 ) );
2058 if ( $value === false ) {
2059 $value = '';
2060 }
2061 if ( $name !== false ) {
2062 $assocArgs[$name] = $value;
2063 }
2064 }
2065 }
2066
2067 # Add a new element to the templace recursion path
2068 $this->mTemplatePath[$part1] = 1;
2069
2070 $text = $this->strip( $text, $this->mStripState );
2071 $text = Sanitizer::removeHTMLtags( $text );
2072 $text = $this->replaceVariables( $text, $assocArgs );
2073
2074 # Resume the link cache and register the inclusion as a link
2075 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2076 $wgLinkCache->addLinkObj( $title );
2077 }
2078
2079 # If the template begins with a table or block-level
2080 # element, it should be treated as beginning a new line.
2081 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2082 $text = "\n" . $text;
2083 }
2084 }
2085 # Prune lower levels off the recursion check path
2086 $this->mTemplatePath = $lastPathLevel;
2087
2088 if ( !$found ) {
2089 wfProfileOut( $fname );
2090 return $matches[0];
2091 } else {
2092 # replace ==section headers==
2093 # XXX this needs to go away once we have a better parser.
2094 if ( $this->mOutputType != OT_WIKI && $itcamefromthedatabase ) {
2095 if( !is_null( $title ) )
2096 $encodedname = base64_encode($title->getPrefixedDBkey());
2097 else
2098 $encodedname = base64_encode("");
2099 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2100 PREG_SPLIT_DELIM_CAPTURE);
2101 $text = '';
2102 $nsec = 0;
2103 for( $i = 0; $i < count($m); $i += 2 ) {
2104 $text .= $m[$i];
2105 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2106 $hl = $m[$i + 1];
2107 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2108 $text .= $hl;
2109 continue;
2110 }
2111 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2112 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2113 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2114
2115 $nsec++;
2116 }
2117 }
2118 }
2119 # Prune lower levels off the recursion check path
2120 $this->mTemplatePath = $lastPathLevel;
2121
2122 if ( !$found ) {
2123 wfProfileOut( $fname );
2124 return $matches[0];
2125 } else {
2126 wfProfileOut( $fname );
2127 return $text;
2128 }
2129 }
2130
2131 /**
2132 * Triple brace replacement -- used for template arguments
2133 * @access private
2134 */
2135 function argSubstitution( $matches ) {
2136 $arg = trim( $matches[1] );
2137 $text = $matches[0];
2138 $inputArgs = end( $this->mArgStack );
2139
2140 if ( array_key_exists( $arg, $inputArgs ) ) {
2141 $text = $inputArgs[$arg];
2142 }
2143
2144 return $text;
2145 }
2146
2147 /**
2148 * Returns true if the function is allowed to include this entity
2149 * @access private
2150 */
2151 function incrementIncludeCount( $dbk ) {
2152 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2153 $this->mIncludeCount[$dbk] = 0;
2154 }
2155 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2156 return true;
2157 } else {
2158 return false;
2159 }
2160 }
2161
2162 /**
2163 * This function accomplishes several tasks:
2164 * 1) Auto-number headings if that option is enabled
2165 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2166 * 3) Add a Table of contents on the top for users who have enabled the option
2167 * 4) Auto-anchor headings
2168 *
2169 * It loops through all headlines, collects the necessary data, then splits up the
2170 * string and re-inserts the newly formatted headlines.
2171 *
2172 * @param string $text
2173 * @param boolean $isMain
2174 * @access private
2175 */
2176 function formatHeadings( $text, $isMain=true ) {
2177 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2178
2179 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2180 $doShowToc = $this->mOptions->getShowToc();
2181 $forceTocHere = false;
2182 if( !$this->mTitle->userCanEdit() ) {
2183 $showEditLink = 0;
2184 $rightClickHack = 0;
2185 } else {
2186 $showEditLink = $this->mOptions->getEditSection();
2187 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
2188 }
2189
2190 # Inhibit editsection links if requested in the page
2191 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2192 if( $esw->matchAndRemove( $text ) ) {
2193 $showEditLink = 0;
2194 }
2195 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2196 # do not add TOC
2197 $mw =& MagicWord::get( MAG_NOTOC );
2198 if( $mw->matchAndRemove( $text ) ) {
2199 $doShowToc = 0;
2200 }
2201
2202 # never add the TOC to the Main Page. This is an entry page that should not
2203 # be more than 1-2 screens large anyway
2204 if( $this->mTitle->getPrefixedText() == wfMsg('mainpage') ) {
2205 $doShowToc = 0;
2206 }
2207
2208 # Get all headlines for numbering them and adding funky stuff like [edit]
2209 # links - this is for later, but we need the number of headlines right now
2210 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2211
2212 # if there are fewer than 4 headlines in the article, do not show TOC
2213 if( $numMatches < 4 ) {
2214 $doShowToc = 0;
2215 }
2216
2217 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2218 # override above conditions and always show TOC at that place
2219
2220 $mw =& MagicWord::get( MAG_TOC );
2221 if($mw->match( $text ) ) {
2222 $doShowToc = 1;
2223 $forceTocHere = true;
2224 } else {
2225 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2226 # override above conditions and always show TOC above first header
2227 $mw =& MagicWord::get( MAG_FORCETOC );
2228 if ($mw->matchAndRemove( $text ) ) {
2229 $doShowToc = 1;
2230 }
2231 }
2232
2233 # Never ever show TOC if no headers
2234 if( $numMatches < 1 ) {
2235 $doShowToc = 0;
2236 }
2237
2238 # We need this to perform operations on the HTML
2239 $sk =& $this->mOptions->getSkin();
2240
2241 # headline counter
2242 $headlineCount = 0;
2243 $sectionCount = 0; # headlineCount excluding template sections
2244
2245 # Ugh .. the TOC should have neat indentation levels which can be
2246 # passed to the skin functions. These are determined here
2247 $toc = '';
2248 $full = '';
2249 $head = array();
2250 $sublevelCount = array();
2251 $levelCount = array();
2252 $toclevel = 0;
2253 $level = 0;
2254 $prevlevel = 0;
2255 $toclevel = 0;
2256 $prevtoclevel = 0;
2257
2258 foreach( $matches[3] as $headline ) {
2259 $istemplate = 0;
2260 $templatetitle = '';
2261 $templatesection = 0;
2262 $numbering = '';
2263
2264 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2265 $istemplate = 1;
2266 $templatetitle = base64_decode($mat[1]);
2267 $templatesection = 1 + (int)base64_decode($mat[2]);
2268 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2269 }
2270
2271 if( $toclevel ) {
2272 $prevlevel = $level;
2273 $prevtoclevel = $toclevel;
2274 }
2275 $level = $matches[1][$headlineCount];
2276
2277 if( $doNumberHeadings || $doShowToc ) {
2278
2279 if ( $level > $prevlevel ) {
2280 # Increase TOC level
2281 $toclevel++;
2282 $sublevelCount[$toclevel] = 0;
2283 $toc .= $sk->tocIndent();
2284 }
2285 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2286 # Decrease TOC level, find level to jump to
2287
2288 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2289 # Can only go down to level 1
2290 $toclevel = 1;
2291 } else {
2292 for ($i = $toclevel; $i > 0; $i--) {
2293 if ( $levelCount[$i] == $level ) {
2294 # Found last matching level
2295 $toclevel = $i;
2296 break;
2297 }
2298 elseif ( $levelCount[$i] < $level ) {
2299 # Found first matching level below current level
2300 $toclevel = $i + 1;
2301 break;
2302 }
2303 }
2304 }
2305
2306 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2307 }
2308 else {
2309 # No change in level, end TOC line
2310 $toc .= $sk->tocLineEnd();
2311 }
2312
2313 $levelCount[$toclevel] = $level;
2314
2315 # count number of headlines for each level
2316 @$sublevelCount[$toclevel]++;
2317 $dot = 0;
2318 for( $i = 1; $i <= $toclevel; $i++ ) {
2319 if( !empty( $sublevelCount[$i] ) ) {
2320 if( $dot ) {
2321 $numbering .= '.';
2322 }
2323 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2324 $dot = 1;
2325 }
2326 }
2327 }
2328
2329 # The canonized header is a version of the header text safe to use for links
2330 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2331 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2332 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2333
2334 # Remove link placeholders by the link text.
2335 # <!--LINK number-->
2336 # turns into
2337 # link text with suffix
2338 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2339 "\$wgLinkHolders['texts'][\$1]",
2340 $canonized_headline );
2341 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2342 "\$wgInterwikiLinkHolders[\$1]",
2343 $canonized_headline );
2344
2345 # strip out HTML
2346 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2347 $tocline = trim( $canonized_headline );
2348 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
2349 $replacearray = array(
2350 '%3A' => ':',
2351 '%' => '.'
2352 );
2353 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2354 $refer[$headlineCount] = $canonized_headline;
2355
2356 # count how many in assoc. array so we can track dupes in anchors
2357 @$refers[$canonized_headline]++;
2358 $refcount[$headlineCount]=$refers[$canonized_headline];
2359
2360 # Don't number the heading if it is the only one (looks silly)
2361 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2362 # the two are different if the line contains a link
2363 $headline=$numbering . ' ' . $headline;
2364 }
2365
2366 # Create the anchor for linking from the TOC to the section
2367 $anchor = $canonized_headline;
2368 if($refcount[$headlineCount] > 1 ) {
2369 $anchor .= '_' . $refcount[$headlineCount];
2370 }
2371 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2372 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2373 }
2374 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2375 if ( empty( $head[$headlineCount] ) ) {
2376 $head[$headlineCount] = '';
2377 }
2378 if( $istemplate )
2379 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2380 else
2381 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2382 }
2383
2384 # Add the edit section span
2385 if( $rightClickHack ) {
2386 if( $istemplate )
2387 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2388 else
2389 $headline = $sk->editSectionScript($this->mTitle, $sectionCount+1,$headline);
2390 }
2391
2392 # give headline the correct <h#> tag
2393 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2394
2395 $headlineCount++;
2396 if( !$istemplate )
2397 $sectionCount++;
2398 }
2399
2400 if( $doShowToc ) {
2401 $toclines = $headlineCount;
2402 $toc .= $sk->tocUnindent( $toclevel - 1 );
2403 $toc = $sk->tocList( $toc );
2404 }
2405
2406 # split up and insert constructed headlines
2407
2408 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2409 $i = 0;
2410
2411 foreach( $blocks as $block ) {
2412 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2413 # This is the [edit] link that appears for the top block of text when
2414 # section editing is enabled
2415
2416 # Disabled because it broke block formatting
2417 # For example, a bullet point in the top line
2418 # $full .= $sk->editSectionLink(0);
2419 }
2420 $full .= $block;
2421 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2422 # Top anchor now in skin
2423 $full = $full.$toc;
2424 }
2425
2426 if( !empty( $head[$i] ) ) {
2427 $full .= $head[$i];
2428 }
2429 $i++;
2430 }
2431 if($forceTocHere) {
2432 $mw =& MagicWord::get( MAG_TOC );
2433 return $mw->replace( $toc, $full );
2434 } else {
2435 return $full;
2436 }
2437 }
2438
2439 /**
2440 * Return an HTML link for the "ISBN 123456" text
2441 * @access private
2442 */
2443 function magicISBN( $text ) {
2444 global $wgLang;
2445 $fname = 'Parser::magicISBN';
2446 wfProfileIn( $fname );
2447
2448 $a = split( 'ISBN ', ' '.$text );
2449 if ( count ( $a ) < 2 ) {
2450 wfProfileOut( $fname );
2451 return $text;
2452 }
2453 $text = substr( array_shift( $a ), 1);
2454 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2455
2456 foreach ( $a as $x ) {
2457 $isbn = $blank = '' ;
2458 while ( ' ' == $x{0} ) {
2459 $blank .= ' ';
2460 $x = substr( $x, 1 );
2461 }
2462 if ( $x == '' ) { # blank isbn
2463 $text .= "ISBN $blank";
2464 continue;
2465 }
2466 while ( strstr( $valid, $x{0} ) != false ) {
2467 $isbn .= $x{0};
2468 $x = substr( $x, 1 );
2469 }
2470 $num = str_replace( '-', '', $isbn );
2471 $num = str_replace( ' ', '', $num );
2472
2473 if ( '' == $num ) {
2474 $text .= "ISBN $blank$x";
2475 } else {
2476 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2477 $text .= '<a href="' .
2478 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2479 "\" class=\"internal\">ISBN $isbn</a>";
2480 $text .= $x;
2481 }
2482 }
2483 wfProfileOut( $fname );
2484 return $text;
2485 }
2486
2487 /**
2488 * Return an HTML link for the "RFC 1234" text
2489 * @access private
2490 * @param string $text text to be processed
2491 */
2492 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2493 global $wgLang;
2494
2495 $valid = '0123456789';
2496 $internal = false;
2497
2498 $a = split( $keyword, ' '.$text );
2499 if ( count ( $a ) < 2 ) {
2500 return $text;
2501 }
2502 $text = substr( array_shift( $a ), 1);
2503
2504 /* Check if keyword is preceed by [[.
2505 * This test is made here cause of the array_shift above
2506 * that prevent the test to be done in the foreach.
2507 */
2508 if ( substr( $text, -2 ) == '[[' ) {
2509 $internal = true;
2510 }
2511
2512 foreach ( $a as $x ) {
2513 /* token might be empty if we have RFC RFC 1234 */
2514 if ( $x=='' ) {
2515 $text.=$keyword;
2516 continue;
2517 }
2518
2519 $id = $blank = '' ;
2520
2521 /** remove and save whitespaces in $blank */
2522 while ( $x{0} == ' ' ) {
2523 $blank .= ' ';
2524 $x = substr( $x, 1 );
2525 }
2526
2527 /** remove and save the rfc number in $id */
2528 while ( strstr( $valid, $x{0} ) != false ) {
2529 $id .= $x{0};
2530 $x = substr( $x, 1 );
2531 }
2532
2533 if ( $id == '' ) {
2534 /* call back stripped spaces*/
2535 $text .= $keyword.$blank.$x;
2536 } elseif( $internal ) {
2537 /* normal link */
2538 $text .= $keyword.$id.$x;
2539 } else {
2540 /* build the external link*/
2541 $url = wfmsg( $urlmsg );
2542 $url = str_replace( '$1', $id, $url);
2543 $sk =& $this->mOptions->getSkin();
2544 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2545 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2546 }
2547
2548 /* Check if the next RFC keyword is preceed by [[ */
2549 $internal = ( substr($x,-2) == '[[' );
2550 }
2551 return $text;
2552 }
2553
2554 /**
2555 * Transform wiki markup when saving a page by doing \r\n -> \n
2556 * conversion, substitting signatures, {{subst:}} templates, etc.
2557 *
2558 * @param string $text the text to transform
2559 * @param Title &$title the Title object for the current article
2560 * @param User &$user the User object describing the current user
2561 * @param ParserOptions $options parsing options
2562 * @param bool $clearState whether to clear the parser state first
2563 * @return string the altered wiki markup
2564 * @access public
2565 */
2566 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2567 $this->mOptions = $options;
2568 $this->mTitle =& $title;
2569 $this->mOutputType = OT_WIKI;
2570
2571 if ( $clearState ) {
2572 $this->clearState();
2573 }
2574
2575 $stripState = false;
2576 $pairs = array(
2577 "\r\n" => "\n",
2578 );
2579 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2580 $text = $this->strip( $text, $stripState, false );
2581 $text = $this->pstPass2( $text, $user );
2582 $text = $this->unstrip( $text, $stripState );
2583 $text = $this->unstripNoWiki( $text, $stripState );
2584 return $text;
2585 }
2586
2587 /**
2588 * Pre-save transform helper function
2589 * @access private
2590 */
2591 function pstPass2( $text, &$user ) {
2592 global $wgLang, $wgContLang, $wgLocaltimezone;
2593
2594 # Variable replacement
2595 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2596 $text = $this->replaceVariables( $text );
2597
2598 # Signatures
2599 #
2600 $n = $user->getName();
2601 $k = $user->getOption( 'nickname' );
2602 if ( '' == $k ) { $k = $n; }
2603 if ( isset( $wgLocaltimezone ) ) {
2604 $oldtz = getenv( 'TZ' );
2605 putenv( 'TZ='.$wgLocaltimezone );
2606 }
2607 /* Note: this is an ugly timezone hack for the European wikis */
2608 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2609 ' (' . date( 'T' ) . ')';
2610 if ( isset( $wgLocaltimezone ) ) {
2611 putenv( 'TZ='.$oldtzs );
2612 }
2613
2614 if( $user->getOption( 'fancysig' ) ) {
2615 $sigText = $k;
2616 } else {
2617 $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
2618 }
2619 $text = preg_replace( '/~~~~~/', $d, $text );
2620 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2621 $text = preg_replace( '/~~~/', $sigText, $text );
2622
2623 # Context links: [[|name]] and [[name (context)|]]
2624 #
2625 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2626 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2627 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2628 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2629
2630 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2631 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2632 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2633 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2634 $context = '';
2635 $t = $this->mTitle->getText();
2636 if ( preg_match( $conpat, $t, $m ) ) {
2637 $context = $m[2];
2638 }
2639 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2640 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2641 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2642
2643 if ( '' == $context ) {
2644 $text = preg_replace( $p2, '[[\\1]]', $text );
2645 } else {
2646 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2647 }
2648
2649 # Trim trailing whitespace
2650 # MAG_END (__END__) tag allows for trailing
2651 # whitespace to be deliberately included
2652 $text = rtrim( $text );
2653 $mw =& MagicWord::get( MAG_END );
2654 $mw->matchAndRemove( $text );
2655
2656 return $text;
2657 }
2658
2659 /**
2660 * Set up some variables which are usually set up in parse()
2661 * so that an external function can call some class members with confidence
2662 * @access public
2663 */
2664 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2665 $this->mTitle =& $title;
2666 $this->mOptions = $options;
2667 $this->mOutputType = $outputType;
2668 if ( $clearState ) {
2669 $this->clearState();
2670 }
2671 }
2672
2673 /**
2674 * Transform a MediaWiki message by replacing magic variables.
2675 *
2676 * @param string $text the text to transform
2677 * @param ParserOptions $options options
2678 * @return string the text with variables substituted
2679 * @access public
2680 */
2681 function transformMsg( $text, $options ) {
2682 global $wgTitle;
2683 static $executing = false;
2684
2685 # Guard against infinite recursion
2686 if ( $executing ) {
2687 return $text;
2688 }
2689 $executing = true;
2690
2691 $this->mTitle = $wgTitle;
2692 $this->mOptions = $options;
2693 $this->mOutputType = OT_MSG;
2694 $this->clearState();
2695 $text = $this->replaceVariables( $text );
2696
2697 $executing = false;
2698 return $text;
2699 }
2700
2701 /**
2702 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2703 * Callback will be called with the text within
2704 * Transform and return the text within
2705 * @access public
2706 */
2707 function setHook( $tag, $callback ) {
2708 $oldVal = @$this->mTagHooks[$tag];
2709 $this->mTagHooks[$tag] = $callback;
2710 return $oldVal;
2711 }
2712
2713 /**
2714 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2715 * Placeholders created in Skin::makeLinkObj()
2716 * Returns an array of links found, indexed by PDBK:
2717 * 0 - broken
2718 * 1 - normal link
2719 * 2 - stub
2720 * $options is a bit field, RLH_FOR_UPDATE to select for update
2721 */
2722 function replaceLinkHolders( &$text, $options = 0 ) {
2723 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2724 global $wgInterwikiLinkHolders;
2725 global $outputReplace;
2726
2727 if ( $wgUseOldExistenceCheck ) {
2728 return array();
2729 }
2730
2731 $fname = 'Parser::replaceLinkHolders';
2732 wfProfileIn( $fname );
2733
2734 $pdbks = array();
2735 $colours = array();
2736
2737 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2738 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2739 wfProfileIn( $fname.'-check' );
2740 $dbr =& wfGetDB( DB_SLAVE );
2741 $page = $dbr->tableName( 'page' );
2742 $sk = $wgUser->getSkin();
2743 $threshold = $wgUser->getOption('stubthreshold');
2744
2745 # Sort by namespace
2746 asort( $wgLinkHolders['namespaces'] );
2747
2748 # Generate query
2749 $query = false;
2750 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2751 # Make title object
2752 $title = $wgLinkHolders['titles'][$key];
2753
2754 # Skip invalid entries.
2755 # Result will be ugly, but prevents crash.
2756 if ( is_null( $title ) ) {
2757 continue;
2758 }
2759 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2760
2761 # Check if it's in the link cache already
2762 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2763 $colours[$pdbk] = 1;
2764 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2765 $colours[$pdbk] = 0;
2766 } else {
2767 # Not in the link cache, add it to the query
2768 if ( !isset( $current ) ) {
2769 $current = $val;
2770 $tables = $page;
2771 $join = '';
2772 $query = "SELECT page_id, page_namespace, page_title";
2773 if ( $threshold > 0 ) {
2774 $textTable = $dbr->tableName( 'text' );
2775 $query .= ', LENGTH(old_text) AS page_len, page_is_redirect';
2776 $tables .= ", $textTable";
2777 $join = 'page_latest=old_id AND';
2778 }
2779 $query .= " FROM $tables WHERE $join (page_namespace=$val AND page_title IN(";
2780 } elseif ( $current != $val ) {
2781 $current = $val;
2782 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2783 } else {
2784 $query .= ', ';
2785 }
2786
2787 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2788 }
2789 }
2790 if ( $query ) {
2791 $query .= '))';
2792 if ( $options & RLH_FOR_UPDATE ) {
2793 $query .= ' FOR UPDATE';
2794 }
2795
2796 $res = $dbr->query( $query, $fname );
2797
2798 # Fetch data and form into an associative array
2799 # non-existent = broken
2800 # 1 = known
2801 # 2 = stub
2802 while ( $s = $dbr->fetchObject($res) ) {
2803 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
2804 $pdbk = $title->getPrefixedDBkey();
2805 $wgLinkCache->addGoodLink( $s->page_id, $pdbk );
2806
2807 if ( $threshold > 0 ) {
2808 $size = $s->page_len;
2809 if ( $s->page_is_redirect || $s->page_namespace != 0 || $length < $threshold ) {
2810 $colours[$pdbk] = 1;
2811 } else {
2812 $colours[$pdbk] = 2;
2813 }
2814 } else {
2815 $colours[$pdbk] = 1;
2816 }
2817 }
2818 }
2819 wfProfileOut( $fname.'-check' );
2820
2821 # Construct search and replace arrays
2822 wfProfileIn( $fname.'-construct' );
2823 $outputReplace = array();
2824 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2825 $pdbk = $pdbks[$key];
2826 $searchkey = '<!--LINK '.$key.'-->';
2827 $title = $wgLinkHolders['titles'][$key];
2828 if ( empty( $colours[$pdbk] ) ) {
2829 $wgLinkCache->addBadLink( $pdbk );
2830 $colours[$pdbk] = 0;
2831 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2832 $wgLinkHolders['texts'][$key],
2833 $wgLinkHolders['queries'][$key] );
2834 } elseif ( $colours[$pdbk] == 1 ) {
2835 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2836 $wgLinkHolders['texts'][$key],
2837 $wgLinkHolders['queries'][$key] );
2838 } elseif ( $colours[$pdbk] == 2 ) {
2839 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2840 $wgLinkHolders['texts'][$key],
2841 $wgLinkHolders['queries'][$key] );
2842 }
2843 }
2844 wfProfileOut( $fname.'-construct' );
2845
2846 # Do the thing
2847 wfProfileIn( $fname.'-replace' );
2848
2849 $text = preg_replace_callback(
2850 '/(<!--LINK .*?-->)/',
2851 "outputReplaceMatches",
2852 $text);
2853 wfProfileOut( $fname.'-replace' );
2854 }
2855
2856 if ( !empty( $wgInterwikiLinkHolders ) ) {
2857 wfProfileIn( $fname.'-interwiki' );
2858 $outputReplace = $wgInterwikiLinkHolders;
2859 $text = preg_replace_callback(
2860 '/<!--IWLINK (.*?)-->/',
2861 "outputReplaceMatches",
2862 $text );
2863 wfProfileOut( $fname.'-interwiki' );
2864 }
2865
2866 wfProfileOut( $fname );
2867 return $colours;
2868 }
2869
2870 /**
2871 * Renders an image gallery from a text with one line per image.
2872 * text labels may be given by using |-style alternative text. E.g.
2873 * Image:one.jpg|The number "1"
2874 * Image:tree.jpg|A tree
2875 * given as text will return the HTML of a gallery with two images,
2876 * labeled 'The number "1"' and
2877 * 'A tree'.
2878 */
2879 function renderImageGallery( $text ) {
2880 global $wgLinkCache;
2881 $ig = new ImageGallery();
2882 $ig->setShowBytes( false );
2883 $ig->setShowFilename( false );
2884 $lines = explode( "\n", $text );
2885
2886 foreach ( $lines as $line ) {
2887 # match lines like these:
2888 # Image:someimage.jpg|This is some image
2889 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
2890 # Skip empty lines
2891 if ( count( $matches ) == 0 ) {
2892 continue;
2893 }
2894 $nt = Title::newFromURL( $matches[1] );
2895 if( is_null( $nt ) ) {
2896 # Bogus title. Ignore these so we don't bomb out later.
2897 continue;
2898 }
2899 if ( isset( $matches[3] ) ) {
2900 $label = $matches[3];
2901 } else {
2902 $label = '';
2903 }
2904
2905 # FIXME: Use the full wiki parser and add its links
2906 # to the page's links.
2907 $html = $this->mOptions->mSkin->formatComment( $label );
2908
2909 $ig->add( Image::newFromTitle( $nt ), $html );
2910 $wgLinkCache->addImageLinkObj( $nt );
2911 }
2912 return $ig->toHTML();
2913 }
2914 }
2915
2916 /**
2917 * @todo document
2918 * @package MediaWiki
2919 */
2920 class ParserOutput
2921 {
2922 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2923 var $mCacheTime; # Used in ParserCache
2924 var $mVersion; # Compatibility check
2925
2926 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2927 $containsOldMagic = false )
2928 {
2929 $this->mText = $text;
2930 $this->mLanguageLinks = $languageLinks;
2931 $this->mCategoryLinks = $categoryLinks;
2932 $this->mContainsOldMagic = $containsOldMagic;
2933 $this->mCacheTime = '';
2934 $this->mVersion = MW_PARSER_VERSION;
2935 }
2936
2937 function getText() { return $this->mText; }
2938 function getLanguageLinks() { return $this->mLanguageLinks; }
2939 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
2940 function getCacheTime() { return $this->mCacheTime; }
2941 function containsOldMagic() { return $this->mContainsOldMagic; }
2942 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2943 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2944 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2945 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2946 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2947 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
2948
2949 function merge( $other ) {
2950 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2951 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2952 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2953 }
2954
2955 /**
2956 * Return true if this cached output object predates the global or
2957 * per-article cache invalidation timestamps, or if it comes from
2958 * an incompatible older version.
2959 *
2960 * @param string $touched the affected article's last touched timestamp
2961 * @return bool
2962 * @access public
2963 */
2964 function expired( $touched ) {
2965 global $wgCacheEpoch;
2966 return $this->getCacheTime() <= $touched ||
2967 $this->getCacheTime() <= $wgCacheEpoch ||
2968 !isset( $this->mVersion ) ||
2969 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
2970 }
2971 }
2972
2973 /**
2974 * Set options of the Parser
2975 * @todo document
2976 * @package MediaWiki
2977 */
2978 class ParserOptions
2979 {
2980 # All variables are private
2981 var $mUseTeX; # Use texvc to expand <math> tags
2982 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2983 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2984 var $mAllowExternalImages; # Allow external images inline
2985 var $mSkin; # Reference to the preferred skin
2986 var $mDateFormat; # Date format index
2987 var $mEditSection; # Create "edit section" links
2988 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2989 var $mNumberHeadings; # Automatically number headings
2990 var $mShowToc; # Show table of contents
2991
2992 function getUseTeX() { return $this->mUseTeX; }
2993 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2994 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2995 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2996 function getSkin() { return $this->mSkin; }
2997 function getDateFormat() { return $this->mDateFormat; }
2998 function getEditSection() { return $this->mEditSection; }
2999 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
3000 function getNumberHeadings() { return $this->mNumberHeadings; }
3001 function getShowToc() { return $this->mShowToc; }
3002
3003 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3004 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3005 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3006 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3007 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3008 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3009 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
3010 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3011 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
3012
3013 function setSkin( &$x ) { $this->mSkin =& $x; }
3014
3015 /**
3016 * Get parser options
3017 * @static
3018 */
3019 function newFromUser( &$user ) {
3020 $popts = new ParserOptions;
3021 $popts->initialiseFromUser( $user );
3022 return $popts;
3023 }
3024
3025 /** Get user options */
3026 function initialiseFromUser( &$userInput ) {
3027 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3028 $fname = 'ParserOptions::initialiseFromUser';
3029 wfProfileIn( $fname );
3030 if ( !$userInput ) {
3031 $user = new User;
3032 $user->setLoaded( true );
3033 } else {
3034 $user =& $userInput;
3035 }
3036
3037 $this->mUseTeX = $wgUseTeX;
3038 $this->mUseDynamicDates = $wgUseDynamicDates;
3039 $this->mInterwikiMagic = $wgInterwikiMagic;
3040 $this->mAllowExternalImages = $wgAllowExternalImages;
3041 wfProfileIn( $fname.'-skin' );
3042 $this->mSkin =& $user->getSkin();
3043 wfProfileOut( $fname.'-skin' );
3044 $this->mDateFormat = $user->getOption( 'date' );
3045 $this->mEditSection = $user->getOption( 'editsection' );
3046 $this->mEditSectionOnRightClick = $user->getOption( 'editsectiononrightclick' );
3047 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3048 $this->mShowToc = $user->getOption( 'showtoc' );
3049 wfProfileOut( $fname );
3050 }
3051 }
3052
3053 /**
3054 * Callback function used by Parser::replaceLinkHolders()
3055 * to substitute link placeholders.
3056 */
3057 function &outputReplaceMatches( $matches ) {
3058 global $outputReplace;
3059 return $outputReplace[$matches[1]];
3060 }
3061
3062 /**
3063 * Return the total number of articles
3064 */
3065 function wfNumberOfArticles() {
3066 global $wgNumberOfArticles;
3067
3068 wfLoadSiteStats();
3069 return $wgNumberOfArticles;
3070 }
3071
3072 /**
3073 * Get various statistics from the database
3074 * @private
3075 */
3076 function wfLoadSiteStats() {
3077 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3078 $fname = 'wfLoadSiteStats';
3079
3080 if ( -1 != $wgNumberOfArticles ) return;
3081 $dbr =& wfGetDB( DB_SLAVE );
3082 $s = $dbr->selectRow( 'site_stats',
3083 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3084 array( 'ss_row_id' => 1 ), $fname
3085 );
3086
3087 if ( $s === false ) {
3088 return;
3089 } else {
3090 $wgTotalViews = $s->ss_total_views;
3091 $wgTotalEdits = $s->ss_total_edits;
3092 $wgNumberOfArticles = $s->ss_good_articles;
3093 }
3094 }
3095
3096 /**
3097 * Escape html tags
3098 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3099 *
3100 * @param string $in Text that might contain HTML tags
3101 * @return string Escaped string
3102 */
3103 function wfEscapeHTMLTagsOnly( $in ) {
3104 return str_replace(
3105 array( '"', '>', '<' ),
3106 array( '&quot;', '&gt;', '&lt;' ),
3107 $in );
3108 }
3109
3110 ?>