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