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