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