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