pre handling fix
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2
3 require_once('Tokenizer.php');
4
5 if( $GLOBALS['wgUseWikiHiero'] ){
6 require_once('extensions/wikihiero/wikihiero.php');
7 }
8 if( $GLOBALS['wgUseTimeline'] ){
9 require_once('extensions/timeline/Timeline.php');
10 }
11
12 # PHP Parser
13 #
14 # Processes wiki markup
15 #
16 # There are two main entry points into the Parser class: parse() and preSaveTransform().
17 # The parse() function produces HTML output, preSaveTransform() produces altered wiki markup.
18 #
19 # Globals used:
20 # objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
21 #
22 # NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
23 #
24 # settings: $wgUseTex*, $wgUseCategoryMagic*, $wgUseDynamicDates*, $wgInterwikiMagic*,
25 # $wgNamespacesWithSubpages, $wgLanguageCode, $wgAllowExternalImages*,
26 # $wgLocaltimezone
27 #
28 # * only within ParserOptions
29 #
30 #
31 #----------------------------------------
32 # Variable substitution O(N^2) attack
33 #-----------------------------------------
34 # Without countermeasures, it would be possible to attack the parser by saving a page
35 # filled with a large number of inclusions of large pages. The size of the generated
36 # page would be proportional to the square of the input size. Hence, we limit the number
37 # of inclusions of any given page, thus bringing any attack back to O(N).
38 #
39
40 define( "MAX_INCLUDE_REPEAT", 5 );
41
42 # Allowed values for $mOutputType
43 define( "OT_HTML", 1 );
44 define( "OT_WIKI", 2 );
45 define( "OT_MSG", 3 );
46
47 # string parameter for extractTags which will cause it
48 # to strip HTML comments in addition to regular
49 # <XML>-style tags. This should not be anything we
50 # may want to use in wikisyntax
51 define( "STRIP_COMMENTS", "HTMLCommentStrip" );
52
53 # prefix for escaping, used in two functions at least
54 define( "UNIQ_PREFIX", "NaodW29");
55
56 class Parser
57 {
58 # Cleared with clearState():
59 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
60 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
61
62 # Temporary:
63 var $mOptions, $mTitle, $mOutputType;
64
65 function Parser()
66 {
67 $this->clearState();
68 }
69
70 function clearState()
71 {
72 $this->mOutput = new ParserOutput;
73 $this->mAutonumber = 0;
74 $this->mLastSection = "";
75 $this->mDTopen = false;
76 $this->mVariables = false;
77 $this->mIncludeCount = array();
78 $this->mStripState = array();
79 $this->mArgStack = array();
80 }
81
82 # First pass--just handle <nowiki> sections, pass the rest off
83 # to internalParse() which does all the real work.
84 #
85 # Returns a ParserOutput
86 #
87 function parse( $text, &$title, $options, $linestart = true, $clearState = true )
88 {
89 global $wgUseTidy;
90 $fname = "Parser::parse";
91 wfProfileIn( $fname );
92
93 if ( $clearState ) {
94 $this->clearState();
95 }
96
97 $this->mOptions = $options;
98 $this->mTitle =& $title;
99 $this->mOutputType = OT_HTML;
100
101 $stripState = NULL;
102 $text = $this->strip( $text, $this->mStripState );
103 $text = $this->internalParse( $text, $linestart );
104 $text = $this->unstrip( $text, $this->mStripState );
105 # Clean up special characters, only run once, next-to-last before doBlockLevels
106 if(!$wgUseTidy) {
107 $fixtags = array(
108 "/<hr *>/i" => '<hr/>',
109 "/<br *>/i" => '<br/>',
110 "/<center *>/i"=>'<div class="center">',
111 "/<\\/center *>/i" => '</div>',
112 # Clean up spare ampersands; note that we probably ought to be
113 # more careful about named entities.
114 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&amp;'
115 );
116 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
117 } else {
118 $fixtags = array(
119 "/<center *>/i"=>'<div class="center">',
120 "/<\\/center *>/i" => '</div>'
121 );
122 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
123 }
124 # only once and last
125 $text = $this->doBlockLevels( $text, $linestart );
126 if($wgUseTidy) {
127 $text = $this->tidy($text);
128 }
129 $this->mOutput->setText( $text );
130 wfProfileOut( $fname );
131 return $this->mOutput;
132 }
133
134 /* static */ function getRandomString()
135 {
136 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
137 }
138
139 # Replaces all occurrences of <$tag>content</$tag> in the text
140 # with a random marker and returns the new text. the output parameter
141 # $content will be an associative array filled with data on the form
142 # $unique_marker => content.
143
144 # If $content is already set, the additional entries will be appended
145
146 # If $tag is set to STRIP_COMMENTS, the function will extract
147 # <!-- HTML comments -->
148
149 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
150 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
151 if ( !$content ) {
152 $content = array( );
153 }
154 $n = 1;
155 $stripped = "";
156
157 while ( "" != $text ) {
158 if($tag==STRIP_COMMENTS) {
159 $p = preg_split( "/<!--/i", $text, 2 );
160 } else {
161 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
162 }
163 $stripped .= $p[0];
164 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) {
165 $text = "";
166 } else {
167 if($tag==STRIP_COMMENTS) {
168 $q = preg_split( "/-->/i", $p[1], 2 );
169 } else {
170 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
171 }
172 $marker = $rnd . sprintf("%08X", $n++);
173 $content[$marker] = $q[0];
174 $stripped .= $marker;
175 $text = $q[1];
176 }
177 }
178 return $stripped;
179 }
180
181 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
182 # If $render is set, performs necessary rendering operations on plugins
183 # Returns the text, and fills an array with data needed in unstrip()
184 # If the $state is already a valid strip state, it adds to the state
185
186 # When $stripcomments is set, HTML comments <!-- like this -->
187 # will be stripped in addition to other tags. This is important
188 # for section editing, where these comments cause confusion when
189 # counting the sections in the wikisource
190 function strip( $text, &$state, $stripcomments = false )
191 {
192 $render = ($this->mOutputType == OT_HTML);
193 $nowiki_content = array();
194 $hiero_content = array();
195 $math_content = array();
196 $pre_content = array();
197 $comment_content = array();
198
199 # Replace any instances of the placeholders
200 $uniq_prefix = UNIQ_PREFIX;
201 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
202
203 $text = Parser::extractTags("nowiki", $text, $nowiki_content, $uniq_prefix);
204 foreach( $nowiki_content as $marker => $content ){
205 if( $render ){
206 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
207 } else {
208 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
209 }
210 }
211
212 $text = Parser::extractTags("hiero", $text, $hiero_content, $uniq_prefix);
213 foreach( $hiero_content as $marker => $content ){
214 if( $render && $GLOBALS['wgUseWikiHiero']){
215 $hiero_content[$marker] = WikiHiero( $content, WH_MODE_HTML);
216 } else {
217 $hiero_content[$marker] = "<hiero>$content</hiero>";
218 }
219 }
220
221 $text = Parser::extractTags("math", $text, $math_content, $uniq_prefix);
222 foreach( $math_content as $marker => $content ){
223 if( $render ) {
224 if( $this->mOptions->getUseTeX() ) {
225 $math_content[$marker] = renderMath( $content );
226 } else {
227 $math_content[$marker] = "&lt;math&gt;$content&lt;math&gt;";
228 }
229 } else {
230 $math_content[$marker] = "<math>$content</math>";
231 }
232 }
233
234 $text = Parser::extractTags("pre", $text, $pre_content, $uniq_prefix);
235 foreach( $pre_content as $marker => $content ){
236 if( $render ){
237 $pre_content[$marker] = "<pre>" . wfEscapeHTMLTagsOnly( $content ) . "</pre>";
238 } else {
239 $pre_content[$marker] = "<pre>$content</pre>";
240 }
241 }
242 if($stripcomments) {
243 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
244 foreach( $comment_content as $marker => $content ){
245 $comment_content[$marker] = "<!--$content-->";
246 }
247 }
248
249 # Merge state with the pre-existing state, if there is one
250 if ( $state ) {
251 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
252 $state['hiero'] = $state['hiero'] + $hiero_content;
253 $state['math'] = $state['math'] + $math_content;
254 $state['pre'] = $state['pre'] + $pre_content;
255 $state['comment'] = $state['comment'] + $comment_content;
256 } else {
257 $state = array(
258 'nowiki' => $nowiki_content,
259 'hiero' => $hiero_content,
260 'math' => $math_content,
261 'pre' => $pre_content,
262 'comment' => $comment_content
263 );
264 }
265 return $text;
266 }
267
268 function unstrip( $text, &$state )
269 {
270 # Must expand in reverse order, otherwise nested tags will be corrupted
271 $contentDict = end( $state );
272 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
273 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
274 $text = str_replace( key( $contentDict ), $content, $text );
275 }
276 }
277
278 return $text;
279 }
280
281 # Add an item to the strip state
282 # Returns the unique tag which must be inserted into the stripped text
283 # The tag will be replaced with the original text in unstrip()
284
285 function insertStripItem( $text, &$state )
286 {
287 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
288 if ( !$state ) {
289 $state = array(
290 'nowiki' => array(),
291 'hiero' => array(),
292 'math' => array(),
293 'pre' => array()
294 );
295 }
296 $state['item'][$rnd] = $text;
297 return $rnd;
298 }
299
300 # This method generates the list of subcategories and pages for a category
301 function categoryMagic ()
302 {
303 global $wgLang , $wgUser ;
304 if ( !$this->mOptions->getUseCategoryMagic() ) return ; # Doesn't use categories at all
305
306 $cns = Namespace::getCategory() ;
307 if ( $this->mTitle->getNamespace() != $cns ) return "" ; # This ain't a category page
308
309 $r = "<br style=\"clear:both;\"/>\n";
310
311
312 $sk =& $wgUser->getSkin() ;
313
314 $articles = array() ;
315 $children = array() ;
316 $data = array () ;
317 $id = $this->mTitle->getArticleID() ;
318
319 # FIXME: add limits
320 $t = wfStrencode( $this->mTitle->getDBKey() );
321 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM cur,categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
322 $res = wfQuery ( $sql, DB_READ ) ;
323 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
324
325 # For all pages that link to this category
326 foreach ( $data AS $x )
327 {
328 $t = $wgLang->getNsText ( $x->cur_namespace ) ;
329 if ( $t != "" ) $t .= ":" ;
330 $t .= $x->cur_title ;
331
332 if ( $x->cur_namespace == $cns ) {
333 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
334 } else {
335 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
336 }
337 }
338 wfFreeResult ( $res ) ;
339
340 # Showing subcategories
341 if ( count ( $children ) > 0 ) {
342 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
343 $r .= implode ( ", " , $children ) ;
344 }
345
346 # Showing pages in this category
347 if ( count ( $articles ) > 0 ) {
348 $ti = $this->mTitle->getText() ;
349 $h = wfMsg( "category_header", $ti );
350 $r .= "<h2>{$h}</h2>\n" ;
351 $r .= implode ( ", " , $articles ) ;
352 }
353
354
355 return $r ;
356 }
357
358 function getHTMLattrs ()
359 {
360 $htmlattrs = array( # Allowed attributes--no scripting, etc.
361 "title", "align", "lang", "dir", "width", "height",
362 "bgcolor", "clear", /* BR */ "noshade", /* HR */
363 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
364 /* FONT */ "type", "start", "value", "compact",
365 /* For various lists, mostly deprecated but safe */
366 "summary", "width", "border", "frame", "rules",
367 "cellspacing", "cellpadding", "valign", "char",
368 "charoff", "colgroup", "col", "span", "abbr", "axis",
369 "headers", "scope", "rowspan", "colspan", /* Tables */
370 "id", "class", "name", "style" /* For CSS */
371 );
372 return $htmlattrs ;
373 }
374
375 function fixTagAttributes ( $t )
376 {
377 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
378 $htmlattrs = $this->getHTMLattrs() ;
379
380 # Strip non-approved attributes from the tag
381 $t = preg_replace(
382 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
383 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
384 $t);
385 # Strip javascript "expression" from stylesheets. Brute force approach:
386 # If anythin offensive is found, all attributes of the HTML tag are dropped
387
388 if( preg_match(
389 "/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is",
390 wfMungeToUtf8( $t ) ) )
391 {
392 $t="";
393 }
394
395 return trim ( $t ) ;
396 }
397
398 /* interface with html tidy, used if $wgUseTidy = true */
399 function tidy ( $text ) {
400 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
401 global $wgInputEncoding, $wgOutputEncoding;
402 $cleansource = '';
403 switch(strtoupper($wgOutputEncoding)) {
404 case 'ISO-8859-1':
405 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -latin1':' -raw';
406 break;
407 case 'UTF-8':
408 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -utf8':' -raw';
409 break;
410 default:
411 $wgTidyOpts .= ' -raw';
412 }
413
414 $text = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
415 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
416 '<head><title>test</title></head><body>'.$text.'</body></html>';
417 $descriptorspec = array(
418 0 => array("pipe", "r"),
419 1 => array("pipe", "w"),
420 2 => array("file", "/dev/null", "a")
421 );
422 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
423 if (is_resource($process)) {
424 fwrite($pipes[0], $text);
425 fclose($pipes[0]);
426 while (!feof($pipes[1])) {
427 $cleansource .= fgets($pipes[1], 1024);
428 }
429 fclose($pipes[1]);
430 $return_value = proc_close($process);
431 }
432 if( $cleansource == '' && $text != '') {
433 return '<h2>'.wfMsg('seriousxhtmlerrors').'</h2><pre>'.htmlspecialchars($text).'</pre>';
434 } else {
435 return $cleansource;
436 }
437 }
438
439 function doTableStuff ( $t )
440 {
441 $t = explode ( "\n" , $t ) ;
442 $td = array () ; # Is currently a td tag open?
443 $ltd = array () ; # Was it TD or TH?
444 $tr = array () ; # Is currently a tr tag open?
445 $ltr = array () ; # tr attributes
446 foreach ( $t AS $k => $x )
447 {
448 $x = trim ( $x ) ;
449 $fc = substr ( $x , 0 , 1 ) ;
450 if ( "{|" == substr ( $x , 0 , 2 ) )
451 {
452 $t[$k] = "\n<table " . $this->fixTagAttributes ( substr ( $x , 3 ) ) . ">" ;
453 array_push ( $td , false ) ;
454 array_push ( $ltd , "" ) ;
455 array_push ( $tr , false ) ;
456 array_push ( $ltr , "" ) ;
457 }
458 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
459 else if ( "|}" == substr ( $x , 0 , 2 ) )
460 {
461 $z = "</table>\n" ;
462 $l = array_pop ( $ltd ) ;
463 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
464 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
465 array_pop ( $ltr ) ;
466 $t[$k] = $z ;
467 }
468 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
469 {
470 $z = trim ( substr ( $x , 2 ) ) ;
471 $t[$k] = "<caption>{$z}</caption>\n" ;
472 }*/
473 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
474 {
475 $x = substr ( $x , 1 ) ;
476 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
477 $z = "" ;
478 $l = array_pop ( $ltd ) ;
479 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
480 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
481 array_pop ( $ltr ) ;
482 $t[$k] = $z ;
483 array_push ( $tr , false ) ;
484 array_push ( $td , false ) ;
485 array_push ( $ltd , "" ) ;
486 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
487 }
488 else if ( "|" == $fc || "!" == $fc || "|+" == substr ( $x , 0 , 2 ) ) # Caption
489 {
490 if ( "|+" == substr ( $x , 0 , 2 ) )
491 {
492 $fc = "+" ;
493 $x = substr ( $x , 1 ) ;
494 }
495 $after = substr ( $x , 1 ) ;
496 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
497 $after = explode ( "||" , $after ) ;
498 $t[$k] = "" ;
499 foreach ( $after AS $theline )
500 {
501 $z = "" ;
502 if ( $fc != "+" )
503 {
504 $tra = array_pop ( $ltr ) ;
505 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
506 array_push ( $tr , true ) ;
507 array_push ( $ltr , "" ) ;
508 }
509
510 $l = array_pop ( $ltd ) ;
511 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
512 if ( $fc == "|" ) $l = "td" ;
513 else if ( $fc == "!" ) $l = "th" ;
514 else if ( $fc == "+" ) $l = "caption" ;
515 else $l = "" ;
516 array_push ( $ltd , $l ) ;
517 $y = explode ( "|" , $theline , 2 ) ;
518 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
519 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
520 $t[$k] .= $y ;
521 array_push ( $td , true ) ;
522 }
523 }
524 }
525
526 # Closing open td, tr && table
527 while ( count ( $td ) > 0 )
528 {
529 if ( array_pop ( $td ) ) $t[] = "</td>" ;
530 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
531 $t[] = "</table>" ;
532 }
533
534 $t = implode ( "\n" , $t ) ;
535 # $t = $this->removeHTMLtags( $t );
536 return $t ;
537 }
538
539 # Parses the text and adds the result to the strip state
540 # Returns the strip tag
541 function stripParse( $text, $linestart, $args )
542 {
543 $text = $this->strip( $text, $this->mStripState );
544 $text = $this->internalParse( $text, $linestart, $args, false );
545 if( $linestart ) {
546 $text = "\n" . $text;
547 }
548 return $this->insertStripItem( $text, $this->mStripState );
549 }
550
551 function internalParse( $text, $linestart, $args = array(), $isMain=true )
552 {
553 $fname = "Parser::internalParse";
554 wfProfileIn( $fname );
555
556 $text = $this->removeHTMLtags( $text );
557 $text = $this->replaceVariables( $text, $args );
558
559 # $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
560
561 $text = $this->doHeadings( $text );
562 if($this->mOptions->getUseDynamicDates()) {
563 global $wgDateFormatter;
564 $text = $wgDateFormatter->reformat( $this->mOptions->getDateFormat(), $text );
565 }
566 $text = $this->replaceExternalLinks( $text );
567 $text = $this->doTokenizedParser ( $text );
568 $text = $this->doTableStuff ( $text ) ;
569 $text = $this->formatHeadings( $text, $isMain );
570 $sk =& $this->mOptions->getSkin();
571 $text = $sk->transformContent( $text );
572
573 if ( !isset ( $this->categoryMagicDone ) ) {
574 $text .= $this->categoryMagic () ;
575 $this->categoryMagicDone = true ;
576 }
577
578 wfProfileOut( $fname );
579 return $text;
580 }
581
582
583 /* private */ function doHeadings( $text )
584 {
585 for ( $i = 6; $i >= 1; --$i ) {
586 $h = substr( "======", 0, $i );
587 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
588 "<h{$i}>\\1</h{$i}>\\2", $text );
589 }
590 return $text;
591 }
592
593 # Note: we have to do external links before the internal ones,
594 # and otherwise take great care in the order of things here, so
595 # that we don't end up interpreting some URLs twice.
596
597 /* private */ function replaceExternalLinks( $text )
598 {
599 $fname = "Parser::replaceExternalLinks";
600 wfProfileIn( $fname );
601 $text = $this->subReplaceExternalLinks( $text, "http", true );
602 $text = $this->subReplaceExternalLinks( $text, "https", true );
603 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
604 $text = $this->subReplaceExternalLinks( $text, "irc", false );
605 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
606 $text = $this->subReplaceExternalLinks( $text, "news", false );
607 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
608 wfProfileOut( $fname );
609 return $text;
610 }
611
612 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
613 {
614 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
615 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
616
617 # this is the list of separators that should be ignored if they
618 # are the last character of an URL but that should be included
619 # if they occur within the URL, e.g. "go to www.foo.com, where .."
620 # in this case, the last comma should not become part of the URL,
621 # but in "www.foo.com/123,2342,32.htm" it should.
622 $sep = ",;\.:";
623 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
624 $images = "gif|png|jpg|jpeg";
625
626 # PLEASE NOTE: The curly braces { } are not part of the regex,
627 # they are interpreted as part of the string (used to tell PHP
628 # that the content of the string should be inserted there).
629 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
630 "((?i){$images})([^{$uc}]|$)/";
631
632 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
633 $sk =& $this->mOptions->getSkin();
634
635 if ( $autonumber and $this->mOptions->getAllowExternalImages() ) { # Use img tags only for HTTP urls
636 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
637 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
638 }
639 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
640 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
641 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
642 "</a>\\5", $s );
643 $s = str_replace( $unique, $protocol, $s );
644
645 $a = explode( "[{$protocol}:", " " . $s );
646 $s = array_shift( $a );
647 $s = substr( $s, 1 );
648
649 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
650 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
651
652 foreach ( $a as $line ) {
653 if ( preg_match( $e1, $line, $m ) ) {
654 $link = "{$protocol}:{$m[1]}";
655 $trail = $m[2];
656 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
657 else { $text = wfEscapeHTML( $link ); }
658 } else if ( preg_match( $e2, $line, $m ) ) {
659 $link = "{$protocol}:{$m[1]}";
660 $text = $m[2];
661 $trail = $m[3];
662 } else {
663 $s .= "[{$protocol}:" . $line;
664 continue;
665 }
666 if( $link == $text || preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
667 $paren = "";
668 } else {
669 # Expand the URL for printable version
670 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
671 }
672 $la = $sk->getExternalLinkAttributes( $link, $text );
673 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
674
675 }
676 return $s;
677 }
678
679 /* private */ function handle4Quotes( &$state, $token )
680 {
681 /* This one makes some assumptions.
682 * '''Caesar''''s army => <strong>Caesar</strong>'s army
683 * ''''Caesar'''' was a roman emperor => '<strong>Caesar</strong>' was a roman emperor
684 * These assumptions might be wrong, but any other assumption might be wrong, too.
685 * So here we go */
686 if ( $state["strong"] !== false ) {
687 return $this->handle3Quotes( $state, $token ) . "'";
688 } else {
689 return "'" . $this->handle3Quotes( $state, $token );
690 }
691 }
692
693
694 /* private */ function handle3Quotes( &$state, $token )
695 {
696 if ( $state["strong"] !== false ) {
697 if ( $state["em"] !== false && $state["em"] > $state["strong"] )
698 {
699 # ''' lala ''lala '''
700 $s = "</em></strong><em>";
701 } else {
702 $s = "</strong>";
703 }
704 $state["strong"] = FALSE;
705 } else {
706 $s = "<strong>";
707 $state["strong"] = $token["pos"];
708 }
709 return $s;
710 }
711
712 /* private */ function handle2Quotes( &$state, $token )
713 {
714 if ( $state["em"] !== false ) {
715 if ( $state["strong"] !== false && $state["strong"] > $state["em"] )
716 {
717 # ''lala'''lala'' ....'''
718 $s = "</strong></em><strong>";
719 } else {
720 $s = "</em>";
721 }
722 $state["em"] = FALSE;
723 } else {
724 $s = "<em>";
725 $state["em"] = $token["pos"];
726
727 }
728 return $s;
729 }
730
731 /* private */ function handle5Quotes( &$state, $token )
732 {
733 $s = "";
734 if ( $state["em"] !== false && $state["strong"] !== false ) {
735 if ( $state["em"] < $state["strong"] ) {
736 $s .= "</strong></em>";
737 } else {
738 $s .= "</em></strong>";
739 }
740 $state["strong"] = $state["em"] = FALSE;
741 } elseif ( $state["em"] !== false ) {
742 $s .= "</em><strong>";
743 $state["em"] = FALSE;
744 $state["strong"] = $token["pos"];
745 } elseif ( $state["strong"] !== false ) {
746 $s .= "</strong><em>";
747 $state["strong"] = FALSE;
748 $state["em"] = $token["pos"];
749 } else { # not $em and not $strong
750 $s .= "<strong><em>";
751 $state["strong"] = $state["em"] = $token["pos"];
752 }
753 return $s;
754 }
755
756 /* private */ function doTokenizedParser( $str )
757 {
758 global $wgLang; # for language specific parser hook
759 global $wgUploadDirectory, $wgUseTimeline;
760
761 $tokenizer=Tokenizer::newFromString( $str );
762 $tokenStack = array();
763
764 $s="";
765 $state["em"] = FALSE;
766 $state["strong"] = FALSE;
767 $tagIsOpen = FALSE;
768 $threeopen = false;
769
770 # The tokenizer splits the text into tokens and returns them one by one.
771 # Every call to the tokenizer returns a new token.
772 while ( $token = $tokenizer->nextToken() )
773 {
774 switch ( $token["type"] )
775 {
776 case "text":
777 # simple text with no further markup
778 $txt = $token["text"];
779 break;
780 case "blank":
781 # Text that contains blanks that have to be converted to
782 # non-breakable spaces for French.
783 # U+202F NARROW NO-BREAK SPACE might be a better choice, but
784 # browser support for Unicode spacing is poor.
785 $txt = str_replace( " ", "&nbsp;", $token["text"] );
786 break;
787 case "[[[":
788 # remember the tag opened with 3 [
789 $threeopen = true;
790 case "[[":
791 # link opening tag.
792 # FIXME : Treat orphaned open tags (stack not empty when text is over)
793 $tagIsOpen = TRUE;
794 array_push( $tokenStack, $token );
795 $txt="";
796 break;
797
798 case "]]]":
799 case "]]":
800 # link close tag.
801 # get text from stack, glue it together, and call the code to handle a
802 # link
803
804 if ( count( $tokenStack ) == 0 )
805 {
806 # stack empty. Found a ]] without an opening [[
807 $txt = "]]";
808 } else {
809 $linkText = "";
810 $lastToken = array_pop( $tokenStack );
811 while ( !(($lastToken["type"] == "[[[") or ($lastToken["type"] == "[[")) )
812 {
813 if( !empty( $lastToken["text"] ) ) {
814 $linkText = $lastToken["text"] . $linkText;
815 }
816 $lastToken = array_pop( $tokenStack );
817 }
818
819 $txt = $linkText ."]]";
820
821 if( isset( $lastToken["text"] ) ) {
822 $prefix = $lastToken["text"];
823 } else {
824 $prefix = "";
825 }
826 $nextToken = $tokenizer->previewToken();
827 if ( $nextToken["type"] == "text" )
828 {
829 # Preview just looks at it. Now we have to fetch it.
830 $nextToken = $tokenizer->nextToken();
831 $txt .= $nextToken["text"];
832 }
833 $txt = $this->handleInternalLink( $this->unstrip($txt,$this->mStripState), $prefix );
834
835 # did the tag start with 3 [ ?
836 if($threeopen) {
837 # show the first as text
838 $txt = "[".$txt;
839 $threeopen=false;
840 }
841
842 }
843 $tagIsOpen = (count( $tokenStack ) != 0);
844 break;
845 case "----":
846 $txt = "\n<hr />\n";
847 break;
848 case "'''":
849 # This and the four next ones handle quotes
850 $txt = $this->handle3Quotes( $state, $token );
851 break;
852 case "''":
853 $txt = $this->handle2Quotes( $state, $token );
854 break;
855 case "'''''":
856 $txt = $this->handle5Quotes( $state, $token );
857 break;
858 case "''''":
859 $txt = $this->handle4Quotes( $state, $token );
860 break;
861 case "":
862 # empty token
863 $txt="";
864 break;
865 case "h":
866 #heading- used to close all unbalanced bold or em tags in this section
867 $txt = '';
868 if( $state['em'] !== false and
869 ( $state['strong'] === false or $state['em'] > $state['strong'] ) )
870 {
871 $s .= '</em>';
872 $state['em'] = false;
873 }
874 if ( $state['strong'] !== false ) $txt .= '</strong>';
875 if ( $state['em'] !== false ) $txt .= '</em>';
876 $state['strong'] = $state['em'] = false;
877 break;
878 case "RFC ":
879 if ( $tagIsOpen ) {
880 $txt = "RFC ";
881 } else {
882 $txt = $this->doMagicRFC( $tokenizer );
883 }
884 break;
885 case "ISBN ":
886 if ( $tagIsOpen ) {
887 $txt = "ISBN ";
888 } else {
889 $txt = $this->doMagicISBN( $tokenizer );
890 }
891 break;
892 case "<timeline>":
893 if ( $wgUseTimeline &&
894 "" != ( $timelinesrc = $tokenizer->readAllUntil("&lt;/timeline&gt;") ) )
895 {
896 $txt = renderTimeline( $timelinesrc );
897 } else {
898 $txt=$token["text"];
899 }
900 break;
901 default:
902 # Call language specific Hook.
903 $txt = $wgLang->processToken( $token, $tokenStack );
904 if ( NULL == $txt ) {
905 # An unkown token. Highlight.
906 $txt = "<font color=\"#FF0000\"><b>".$token["type"]."</b></font>";
907 $txt .= "<font color=\"#FFFF00\"><b>".$token["text"]."</b></font>";
908 }
909 break;
910 }
911 # If we're parsing the interior of a link, don't append the interior to $s,
912 # but push it to the stack so it can be processed when a ]] token is found.
913 if ( $tagIsOpen && $txt != "" ) {
914 $token["type"] = "text";
915 $token["text"] = $txt;
916 array_push( $tokenStack, $token );
917 } else {
918 $s .= $txt;
919 }
920 } #end while
921
922 # make 100% sure all strong and em tags are closed
923 # doBlockLevels often messes the last bit up though, but invalid nesting is better than unclosed tags
924 # tidy solves this though
925 if( $state['em'] !== false and
926 ( $state['strong'] === false or $state['em'] > $state['strong'] ) )
927 {
928 $s .= '</em>';
929 $state['em'] = false;
930 }
931 if ( $state['strong'] !== false ) $s .= '</strong>';
932 if ( $state['em'] !== false ) $s .= '</em>';
933
934 if ( count( $tokenStack ) != 0 )
935 {
936 # still objects on stack. opened [[ tag without closing ]] tag.
937 $txt = "";
938 while ( $lastToken = array_pop( $tokenStack ) )
939 {
940 if ( $lastToken["type"] == "text" )
941 {
942 $txt = $lastToken["text"] . $txt;
943 } else {
944 $txt = $lastToken["type"] . $txt;
945 }
946 }
947 $s .= $txt;
948 }
949 return $s;
950 }
951
952 /* private */ function handleInternalLink( $line, $prefix )
953 {
954 global $wgLang, $wgLinkCache;
955 global $wgNamespacesWithSubpages, $wgLanguageCode;
956 static $fname = "Parser::handleInternalLink" ;
957 wfProfileIn( $fname );
958
959 wfProfileIn( "$fname-setup" );
960 static $tc = FALSE;
961 if ( !$tc ) { $tc = Title::legalChars() . "#"; }
962 $sk =& $this->mOptions->getSkin();
963
964 # Match a link having the form [[namespace:link|alternate]]trail
965 static $e1 = FALSE;
966 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
967 # Match the end of a line for a word that's not followed by whitespace,
968 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
969 #$e2 = "/^(.*)\\b(\\w+)\$/suD";
970 #$e2 = "/^(.*\\s)(\\S+)\$/suD";
971 static $e2 = '/^(.*\s)([a-zA-Z\x80-\xff]+)$/sD';
972
973
974 # Special and Media are pseudo-namespaces; no pages actually exist in them
975 static $image = FALSE;
976 static $special = FALSE;
977 static $media = FALSE;
978 static $category = FALSE;
979 if ( !$image ) { $image = Namespace::getImage(); }
980 if ( !$special ) { $special = Namespace::getSpecial(); }
981 if ( !$media ) { $media = Namespace::getMedia(); }
982 if ( !$category ) { $category = Namespace::getCategory(); }
983
984 $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
985
986 wfProfileOut( "$fname-setup" );
987 $s = "";
988
989 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
990 $text = $m[2];
991 $trail = $m[3];
992 } else { # Invalid form; output directly
993 $s .= $prefix . "[[" . $line ;
994 return $s;
995 }
996
997 /* Valid link forms:
998 Foobar -- normal
999 :Foobar -- override special treatment of prefix (images, language links)
1000 /Foobar -- convert to CurrentPage/Foobar
1001 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1002 */
1003 $c = substr($m[1],0,1);
1004 $noforce = ($c != ":");
1005 if( $c == "/" ) { # subpage
1006 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
1007 $m[1]=substr($m[1],1,strlen($m[1])-2);
1008 $noslash=$m[1];
1009 } else {
1010 $noslash=substr($m[1],1);
1011 }
1012 if(!empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()])) { # subpages allowed here
1013 $link = $this->mTitle->getPrefixedText(). "/" . trim($noslash);
1014 if( "" == $text ) {
1015 $text= $m[1];
1016 } # this might be changed for ugliness reasons
1017 } else {
1018 $link = $noslash; # no subpage allowed, use standard link
1019 }
1020 } elseif( $noforce ) { # no subpage
1021 $link = $m[1];
1022 } else {
1023 $link = substr( $m[1], 1 );
1024 }
1025 $wasblank = ( "" == $text );
1026 if( $wasblank )
1027 $text = $link;
1028
1029 $nt = Title::newFromText( $link );
1030 if( !$nt ) {
1031 $s .= $prefix . "[[" . $line;
1032 return $s;
1033 }
1034 $ns = $nt->getNamespace();
1035 $iw = $nt->getInterWiki();
1036 if( $noforce ) {
1037 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1038 array_push( $this->mOutput->mLanguageLinks, $nt->getPrefixedText() );
1039 $s .= $prefix . $trail ;
1040 return (trim($s) == '')? '': $s;
1041 }
1042 if( $ns == $image ) {
1043 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1044 $wgLinkCache->addImageLinkObj( $nt );
1045 return $s;
1046 }
1047 if ( $ns == $category ) {
1048 $t = $nt->getText() ;
1049 $nnt = Title::newFromText ( Namespace::getCanonicalName($category).":".$t ) ;
1050
1051 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1052 $t = $sk->makeLinkObj( $nnt, $t, "", "" , $prefix );
1053 $wgLinkCache->resume();
1054
1055 $sortkey = $wasblank ? $this->mTitle->getPrefixedText() : $text;
1056 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1057 $this->mOutput->mCategoryLinks[] = $t ;
1058 $s .= $prefix . $trail ;
1059 return $s ;
1060 }
1061 }
1062 if( ( $nt->getPrefixedText() == $this->mTitle->getPrefixedText() ) &&
1063 ( strpos( $link, "#" ) == FALSE ) ) {
1064 # Self-links are handled specially; generally de-link and change to bold.
1065 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, "", $trail );
1066 return $s;
1067 }
1068
1069 if( $ns == $media ) {
1070 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1071 $wgLinkCache->addImageLinkObj( $nt );
1072 return $s;
1073 } elseif( $ns == $special ) {
1074 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, "", $trail );
1075 return $s;
1076 }
1077 $s .= $sk->makeLinkObj( $nt, $text, "", $trail , $prefix );
1078
1079 wfProfileOut( $fname );
1080 return $s;
1081 }
1082
1083 # Some functions here used by doBlockLevels()
1084 #
1085 /* private */ function closeParagraph()
1086 {
1087 $result = "";
1088 if ( '' != $this->mLastSection ) {
1089 $result = "</" . $this->mLastSection . ">\n";
1090 }
1091 $this->mInPre = false;
1092 $this->mLastSection = "";
1093 return $result;
1094 }
1095 # getCommon() returns the length of the longest common substring
1096 # of both arguments, starting at the beginning of both.
1097 #
1098 /* private */ function getCommon( $st1, $st2 )
1099 {
1100 $fl = strlen( $st1 );
1101 $shorter = strlen( $st2 );
1102 if ( $fl < $shorter ) { $shorter = $fl; }
1103
1104 for ( $i = 0; $i < $shorter; ++$i ) {
1105 if ( $st1{$i} != $st2{$i} ) { break; }
1106 }
1107 return $i;
1108 }
1109 # These next three functions open, continue, and close the list
1110 # element appropriate to the prefix character passed into them.
1111 #
1112 /* private */ function openList( $char )
1113 {
1114 $result = $this->closeParagraph();
1115
1116 if ( "*" == $char ) { $result .= "<ul><li>"; }
1117 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1118 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1119 else if ( ";" == $char ) {
1120 $result .= "<dl><dt>";
1121 $this->mDTopen = true;
1122 }
1123 else { $result = "<!-- ERR 1 -->"; }
1124
1125 return $result;
1126 }
1127
1128 /* private */ function nextItem( $char )
1129 {
1130 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1131 else if ( ":" == $char || ";" == $char ) {
1132 $close = "</dd>";
1133 if ( $this->mDTopen ) { $close = "</dt>"; }
1134 if ( ";" == $char ) {
1135 $this->mDTopen = true;
1136 return $close . "<dt>";
1137 } else {
1138 $this->mDTopen = false;
1139 return $close . "<dd>";
1140 }
1141 }
1142 return "<!-- ERR 2 -->";
1143 }
1144
1145 /* private */function closeList( $char )
1146 {
1147 if ( "*" == $char ) { $text = "</li></ul>"; }
1148 else if ( "#" == $char ) { $text = "</li></ol>"; }
1149 else if ( ":" == $char ) {
1150 if ( $this->mDTopen ) {
1151 $this->mDTopen = false;
1152 $text = "</dt></dl>";
1153 } else {
1154 $text = "</dd></dl>";
1155 }
1156 }
1157 else { return "<!-- ERR 3 -->"; }
1158 return $text."\n";
1159 }
1160
1161 /* private */ function doBlockLevels( $text, $linestart ) {
1162 $fname = "Parser::doBlockLevels";
1163 wfProfileIn( $fname );
1164
1165 # Parsing through the text line by line. The main thing
1166 # happening here is handling of block-level elements p, pre,
1167 # and making lists from lines starting with * # : etc.
1168 #
1169 $textLines = explode( "\n", $text );
1170
1171 $lastPrefix = $output = $lastLine = '';
1172 $this->mDTopen = $inBlockElem = false;
1173 $prefixLength = 0;
1174 $paragraphStack = false;
1175
1176 if ( !$linestart ) {
1177 $output .= array_shift( $textLines );
1178 }
1179 foreach ( $textLines as $oLine ) {
1180 $lastPrefixLength = strlen( $lastPrefix );
1181 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1182 $preOpenMatch = preg_match("/<pre/i", $oLine );
1183 if (!$this->mInPre) {
1184 $this->mInPre = !empty($preOpenMatch);
1185 }
1186 if ( !$this->mInPre ) {
1187 # Multiple prefixes may abut each other for nested lists.
1188 $prefixLength = strspn( $oLine, "*#:;" );
1189 $pref = substr( $oLine, 0, $prefixLength );
1190
1191 # eh?
1192 $pref2 = str_replace( ";", ":", $pref );
1193 $t = substr( $oLine, $prefixLength );
1194 } else {
1195 # Don't interpret any other prefixes in preformatted text
1196 $prefixLength = 0;
1197 $pref = $pref2 = '';
1198 $t = $oLine;
1199 }
1200
1201 # List generation
1202 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1203 # Same as the last item, so no need to deal with nesting or opening stuff
1204 $output .= $this->nextItem( substr( $pref, -1 ) );
1205 $paragraphStack = false;
1206
1207 if ( ";" == substr( $pref, -1 ) ) {
1208 # The one nasty exception: definition lists work like this:
1209 # ; title : definition text
1210 # So we check for : in the remainder text to split up the
1211 # title and definition, without b0rking links.
1212 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1213 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1214 $term = $match[1];
1215 $output .= $term . $this->nextItem( ":" );
1216 $t = $match[2];
1217 }
1218 }
1219 } elseif( $prefixLength || $lastPrefixLength ) {
1220 # Either open or close a level...
1221 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1222 $paragraphStack = false;
1223
1224 while( $commonPrefixLength < $lastPrefixLength ) {
1225 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1226 --$lastPrefixLength;
1227 }
1228 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1229 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1230 }
1231 while ( $prefixLength > $commonPrefixLength ) {
1232 $char = substr( $pref, $commonPrefixLength, 1 );
1233 $output .= $this->openList( $char );
1234
1235 if ( ";" == $char ) {
1236 # FIXME: This is dupe of code above
1237 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1238 $term = $match[1];
1239 $output .= $term . $this->nextItem( ":" );
1240 $t = $match[2];
1241 }
1242 }
1243 ++$commonPrefixLength;
1244 }
1245 $lastPrefix = $pref2;
1246 }
1247 if( 0 == $prefixLength ) {
1248 # No prefix (not in list)--go to paragraph mode
1249 $uniq_prefix = UNIQ_PREFIX;
1250 // XXX: use a stack for nestable elements like span, table and div
1251 $openmatch = preg_match("/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<td|<p|<ul|<li)/i", $t );
1252 $closematch = preg_match(
1253 "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|".
1254 "<div|<\\/div|<hr|<\\/td|<\\/pre|<\\/p|".$uniq_prefix."-pre|<\\/li|<\\/ul)/i", $t );
1255 if ( $openmatch or $closematch ) {
1256 $paragraphStack = false;
1257 $output .= $this->closeParagraph();
1258 if($preOpenMatch and !$preCloseMatch) {
1259 $this->mInPre = true;
1260 }
1261 if ( $closematch ) {
1262 $inBlockElem = false;
1263 } else {
1264 $inBlockElem = true;
1265 }
1266 } else if ( !$inBlockElem && !$this->mInPre ) {
1267 if ( " " == $t{0} and trim($t) != '' ) {
1268 // pre
1269 if ($this->mLastSection != 'pre') {
1270 $paragraphStack = false;
1271 $output .= $this->closeParagraph().'<pre>';
1272 $this->mLastSection = 'pre';
1273 }
1274 } else {
1275 // paragraph
1276 if ( '' == trim($t) ) {
1277 if ( $paragraphStack ) {
1278 $output .= $paragraphStack.'<br/>';
1279 $paragraphStack = false;
1280 $this->mLastSection = 'p';
1281 } else {
1282 if ($this->mLastSection != 'p' ) {
1283 $output .= $this->closeParagraph();
1284 $this->mLastSection = '';
1285 $paragraphStack = "<p>";
1286 } else {
1287 $paragraphStack = '</p><p>';
1288 }
1289 }
1290 } else {
1291 if ( $paragraphStack ) {
1292 $output .= $paragraphStack;
1293 $paragraphStack = false;
1294 $this->mLastSection = 'p';
1295 } else if ($this->mLastSection != 'p') {
1296 $output .= $this->closeParagraph().'<p>';
1297 $this->mLastSection = 'p';
1298 }
1299 }
1300 }
1301 }
1302 }
1303 if ($paragraphStack === false) {
1304 $output .= $t."\n";
1305 }
1306 }
1307 while ( $prefixLength ) {
1308 $output .= $this->closeList( $pref2{$prefixLength-1} );
1309 --$prefixLength;
1310 }
1311 if ( "" != $this->mLastSection ) {
1312 $output .= "</" . $this->mLastSection . ">";
1313 $this->mLastSection = "";
1314 }
1315
1316 wfProfileOut( $fname );
1317 return $output;
1318 }
1319
1320 function getVariableValue( $index ) {
1321 global $wgLang, $wgSitename, $wgServer;
1322
1323 switch ( $index ) {
1324 case MAG_CURRENTMONTH:
1325 return date( "m" );
1326 case MAG_CURRENTMONTHNAME:
1327 return $wgLang->getMonthName( date("n") );
1328 case MAG_CURRENTMONTHNAMEGEN:
1329 return $wgLang->getMonthNameGen( date("n") );
1330 case MAG_CURRENTDAY:
1331 return date("j");
1332 case MAG_PAGENAME:
1333 return $this->mTitle->getText();
1334 case MAG_NAMESPACE:
1335 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1336 return $wgLang->getNsText($this->mTitle->getNamespace()); // Patch by Dori
1337 case MAG_CURRENTDAYNAME:
1338 return $wgLang->getWeekdayName( date("w")+1 );
1339 case MAG_CURRENTYEAR:
1340 return date( "Y" );
1341 case MAG_CURRENTTIME:
1342 return $wgLang->time( wfTimestampNow(), false );
1343 case MAG_NUMBEROFARTICLES:
1344 return wfNumberOfArticles();
1345 case MAG_SITENAME:
1346 return $wgSitename;
1347 case MAG_SERVER:
1348 return $wgServer;
1349 default:
1350 return NULL;
1351 }
1352 }
1353
1354 function initialiseVariables()
1355 {
1356 global $wgVariableIDs;
1357 $this->mVariables = array();
1358 foreach ( $wgVariableIDs as $id ) {
1359 $mw =& MagicWord::get( $id );
1360 $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
1361 }
1362 }
1363
1364 /* private */ function replaceVariables( $text, $args = array() )
1365 {
1366 global $wgLang, $wgScript, $wgArticlePath;
1367
1368 $fname = "Parser::replaceVariables";
1369 wfProfileIn( $fname );
1370
1371 $bail = false;
1372 if ( !$this->mVariables ) {
1373 $this->initialiseVariables();
1374 }
1375 $titleChars = Title::legalChars();
1376
1377 # This function is called recursively. To keep track of arguments we need a stack:
1378 array_push( $this->mArgStack, $args );
1379
1380 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1381 $GLOBALS['wgCurParser'] =& $this;
1382
1383 # Argument substitution
1384 if ( $this->mOutputType == OT_HTML ) {
1385 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", "wfArgSubstitution", $text );
1386 }
1387
1388 # Double brace substitution
1389 $regex = "/(\\n?){{([$titleChars]*?)(\\|.*?|)}}/s";
1390 $text = preg_replace_callback( $regex, "wfBraceSubstitution", $text );
1391
1392 array_pop( $this->mArgStack );
1393
1394 return $text;
1395 }
1396
1397 function braceSubstitution( $matches )
1398 {
1399 global $wgLinkCache, $wgLang;
1400 $fname = "Parser::braceSubstitution";
1401 $found = false;
1402 $nowiki = false;
1403 $noparse = false;
1404
1405 $title = NULL;
1406
1407 # $newline is an optional newline character before the braces
1408 # $part1 is the bit before the first |, and must contain only title characters
1409 # $args is a list of arguments, starting from index 0, not including $part1
1410
1411 $newline = $matches[1];
1412 $part1 = $matches[2];
1413 # If the third subpattern matched anything, it will start with |
1414 if ( $matches[3] !== "" ) {
1415 $args = explode( "|", substr( $matches[3], 1 ) );
1416 } else {
1417 $args = array();
1418 }
1419 $argc = count( $args );
1420
1421 # {{{}}}
1422 if ( strpos( $matches[0], "{{{" ) !== false ) {
1423 $text = $matches[0];
1424 $found = true;
1425 $noparse = true;
1426 }
1427
1428 # SUBST
1429 if ( !$found ) {
1430 $mwSubst =& MagicWord::get( MAG_SUBST );
1431 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1432 if ( $this->mOutputType != OT_WIKI ) {
1433 # Invalid SUBST not replaced at PST time
1434 # Return without further processing
1435 $text = $matches[0];
1436 $found = true;
1437 $noparse= true;
1438 }
1439 } elseif ( $this->mOutputType == OT_WIKI ) {
1440 # SUBST not found in PST pass, do nothing
1441 $text = $matches[0];
1442 $found = true;
1443 }
1444 }
1445
1446 # MSG, MSGNW and INT
1447 if ( !$found ) {
1448 # Check for MSGNW:
1449 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1450 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1451 $nowiki = true;
1452 } else {
1453 # Remove obsolete MSG:
1454 $mwMsg =& MagicWord::get( MAG_MSG );
1455 $mwMsg->matchStartAndRemove( $part1 );
1456 }
1457
1458 # Check if it is an internal message
1459 $mwInt =& MagicWord::get( MAG_INT );
1460 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1461 if ( $this->incrementIncludeCount( "int:$part1" ) ) {
1462 $text = wfMsgReal( $part1, $args, true );
1463 $found = true;
1464 }
1465 }
1466 }
1467
1468 # NS
1469 if ( !$found ) {
1470 # Check for NS: (namespace expansion)
1471 $mwNs = MagicWord::get( MAG_NS );
1472 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1473 if ( intval( $part1 ) ) {
1474 $text = $wgLang->getNsText( intval( $part1 ) );
1475 $found = true;
1476 } else {
1477 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1478 if ( !is_null( $index ) ) {
1479 $text = $wgLang->getNsText( $index );
1480 $found = true;
1481 }
1482 }
1483 }
1484 }
1485
1486 # LOCALURL and LOCALURLE
1487 if ( !$found ) {
1488 $mwLocal = MagicWord::get( MAG_LOCALURL );
1489 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1490
1491 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1492 $func = 'getLocalURL';
1493 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1494 $func = 'escapeLocalURL';
1495 } else {
1496 $func = '';
1497 }
1498
1499 if ( $func !== '' ) {
1500 $title = Title::newFromText( $part1 );
1501 if ( !is_null( $title ) ) {
1502 if ( $argc > 0 ) {
1503 $text = $title->$func( $args[0] );
1504 } else {
1505 $text = $title->$func();
1506 }
1507 $found = true;
1508 }
1509 }
1510 }
1511
1512 # Internal variables
1513 if ( !$found && array_key_exists( $part1, $this->mVariables ) ) {
1514 $text = $this->mVariables[$part1];
1515 $found = true;
1516 $this->mOutput->mContainsOldMagic = true;
1517 }
1518 /*
1519 # Arguments input from the caller
1520 $inputArgs = end( $this->mArgStack );
1521 if ( !$found && array_key_exists( $part1, $inputArgs ) ) {
1522 $text = $inputArgs[$part1];
1523 $found = true;
1524 }
1525 */
1526 # Load from database
1527 if ( !$found ) {
1528 $title = Title::newFromText( $part1, NS_TEMPLATE );
1529 if ( !is_null( $title ) && !$title->isExternal() ) {
1530 # Check for excessive inclusion
1531 $dbk = $title->getPrefixedDBkey();
1532 if ( $this->incrementIncludeCount( $dbk ) ) {
1533 $article = new Article( $title );
1534 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1535 if ( $articleContent !== false ) {
1536 $found = true;
1537 $text = $articleContent;
1538
1539 }
1540 }
1541
1542 # If the title is valid but undisplayable, make a link to it
1543 if ( $this->mOutputType == OT_HTML && !$found ) {
1544 $text = "[[" . $title->getPrefixedText() . "]]";
1545 $found = true;
1546 }
1547 }
1548 }
1549
1550 # Recursive parsing, escaping and link table handling
1551 # Only for HTML output
1552 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
1553 $text = wfEscapeWikiText( $text );
1554 } elseif ( $this->mOutputType == OT_HTML && $found && !$noparse) {
1555 # Clean up argument array
1556 $assocArgs = array();
1557 $index = 1;
1558 foreach( $args as $arg ) {
1559 $eqpos = strpos( $arg, "=" );
1560 if ( $eqpos === false ) {
1561 $assocArgs[$index++] = $arg;
1562 } else {
1563 $name = trim( substr( $arg, 0, $eqpos ) );
1564 $value = trim( substr( $arg, $eqpos+1 ) );
1565 if ( $value === false ) {
1566 $value = "";
1567 }
1568 if ( $name !== false ) {
1569 $assocArgs[$name] = $value;
1570 }
1571 }
1572 }
1573
1574 # Do not enter included links in link table
1575 if ( !is_null( $title ) ) {
1576 $wgLinkCache->suspend();
1577 }
1578
1579 # Run full parser on the included text
1580 $text = $this->stripParse( $text, (bool)$newline, $assocArgs );
1581
1582 # Resume the link cache and register the inclusion as a link
1583 if ( !is_null( $title ) ) {
1584 $wgLinkCache->resume();
1585 $wgLinkCache->addLinkObj( $title );
1586 }
1587 }
1588
1589 if ( !$found ) {
1590 return $matches[0];
1591 } else {
1592 return $text;
1593 }
1594 }
1595
1596 # Triple brace replacement -- used for template arguments
1597 function argSubstitution( $matches )
1598 {
1599 $newline = $matches[1];
1600 $arg = trim( $matches[2] );
1601 $text = $matches[0];
1602 $inputArgs = end( $this->mArgStack );
1603
1604 if ( array_key_exists( $arg, $inputArgs ) ) {
1605 $text = $this->stripParse( $inputArgs[$arg], (bool)$newline, array() );
1606 }
1607
1608 return $text;
1609 }
1610
1611 # Returns true if the function is allowed to include this entity
1612 function incrementIncludeCount( $dbk )
1613 {
1614 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
1615 $this->mIncludeCount[$dbk] = 0;
1616 }
1617 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
1618 return true;
1619 } else {
1620 return false;
1621 }
1622 }
1623
1624
1625 # Cleans up HTML, removes dangerous tags and attributes
1626 /* private */ function removeHTMLtags( $text )
1627 {
1628 global $wgUseTidy, $wgUserHtml;
1629 $fname = "Parser::removeHTMLtags";
1630 wfProfileIn( $fname );
1631
1632 if( $wgUserHtml ) {
1633 $htmlpairs = array( # Tags that must be closed
1634 "b", "del", "i", "ins", "u", "font", "big", "small", "sub", "sup", "h1",
1635 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1636 "strike", "strong", "tt", "var", "div", "center",
1637 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1638 "ruby", "rt" , "rb" , "rp", "p"
1639 );
1640 $htmlsingle = array(
1641 "br", "hr", "li", "dt", "dd"
1642 );
1643 $htmlnest = array( # Tags that can be nested--??
1644 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1645 "dl", "font", "big", "small", "sub", "sup"
1646 );
1647 $tabletags = array( # Can only appear inside table
1648 "td", "th", "tr"
1649 );
1650 } else {
1651 $htmlpairs = array();
1652 $htmlsingle = array();
1653 $htmlnest = array();
1654 $tabletags = array();
1655 }
1656
1657 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1658 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1659
1660 $htmlattrs = $this->getHTMLattrs () ;
1661
1662 # Remove HTML comments
1663 $text = preg_replace( "/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU", "$2", $text );
1664
1665 $bits = explode( "<", $text );
1666 $text = array_shift( $bits );
1667 if(!$wgUseTidy) {
1668 $tagstack = array(); $tablestack = array();
1669 foreach ( $bits as $x ) {
1670 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1671 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1672 $x, $regs );
1673 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1674 error_reporting( $prev );
1675
1676 $badtag = 0 ;
1677 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1678 # Check our stack
1679 if ( $slash ) {
1680 # Closing a tag...
1681 if ( ! in_array( $t, $htmlsingle ) &&
1682 ( count($tagstack) && $ot = array_pop( $tagstack ) ) != $t ) {
1683 if(!empty($ot)) array_push( $tagstack, $ot );
1684 $badtag = 1;
1685 } else {
1686 if ( $t == "table" ) {
1687 $tagstack = array_pop( $tablestack );
1688 }
1689 $newparams = "";
1690 }
1691 } else {
1692 # Keep track for later
1693 if ( in_array( $t, $tabletags ) &&
1694 ! in_array( "table", $tagstack ) ) {
1695 $badtag = 1;
1696 } else if ( in_array( $t, $tagstack ) &&
1697 ! in_array ( $t , $htmlnest ) ) {
1698 $badtag = 1 ;
1699 } else if ( ! in_array( $t, $htmlsingle ) ) {
1700 if ( $t == "table" ) {
1701 array_push( $tablestack, $tagstack );
1702 $tagstack = array();
1703 }
1704 array_push( $tagstack, $t );
1705 }
1706 # Strip non-approved attributes from the tag
1707 $newparams = $this->fixTagAttributes($params);
1708
1709 }
1710 if ( ! $badtag ) {
1711 $rest = str_replace( ">", "&gt;", $rest );
1712 $text .= "<$slash$t $newparams$brace$rest";
1713 continue;
1714 }
1715 }
1716 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1717 }
1718 # Close off any remaining tags
1719 while ( $t = array_pop( $tagstack ) ) {
1720 $text .= "</$t>\n";
1721 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1722 }
1723 } else {
1724 # this might be possible using tidy itself
1725 foreach ( $bits as $x ) {
1726 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1727 $x, $regs );
1728 @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1729 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1730 $newparams = $this->fixTagAttributes($params);
1731 $rest = str_replace( ">", "&gt;", $rest );
1732 $text .= "<$slash$t $newparams$brace$rest";
1733 } else {
1734 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1735 }
1736 }
1737 }
1738 wfProfileOut( $fname );
1739 return $text;
1740 }
1741
1742
1743 /*
1744 *
1745 * This function accomplishes several tasks:
1746 * 1) Auto-number headings if that option is enabled
1747 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1748 * 3) Add a Table of contents on the top for users who have enabled the option
1749 * 4) Auto-anchor headings
1750 *
1751 * It loops through all headlines, collects the necessary data, then splits up the
1752 * string and re-inserts the newly formatted headlines.
1753 *
1754 */
1755
1756 /* private */ function formatHeadings( $text, $isMain=true )
1757 {
1758 global $wgInputEncoding;
1759
1760 $doNumberHeadings = $this->mOptions->getNumberHeadings();
1761 $doShowToc = $this->mOptions->getShowToc();
1762 if( !$this->mTitle->userCanEdit() ) {
1763 $showEditLink = 0;
1764 $rightClickHack = 0;
1765 } else {
1766 $showEditLink = $this->mOptions->getEditSection();
1767 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
1768 }
1769
1770 # Inhibit editsection links if requested in the page
1771 $esw =& MagicWord::get( MAG_NOEDITSECTION );
1772 if( $esw->matchAndRemove( $text ) ) {
1773 $showEditLink = 0;
1774 }
1775 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1776 # do not add TOC
1777 $mw =& MagicWord::get( MAG_NOTOC );
1778 if( $mw->matchAndRemove( $text ) ) {
1779 $doShowToc = 0;
1780 }
1781
1782 # never add the TOC to the Main Page. This is an entry page that should not
1783 # be more than 1-2 screens large anyway
1784 if( $this->mTitle->getPrefixedText() == wfMsg("mainpage") ) {
1785 $doShowToc = 0;
1786 }
1787
1788 # Get all headlines for numbering them and adding funky stuff like [edit]
1789 # links - this is for later, but we need the number of headlines right now
1790 $numMatches = preg_match_all( "/<H([1-6])(.*?" . ">)(.*?)<\/H[1-6]>/i", $text, $matches );
1791
1792 # if there are fewer than 4 headlines in the article, do not show TOC
1793 if( $numMatches < 4 ) {
1794 $doShowToc = 0;
1795 }
1796
1797 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1798 # override above conditions and always show TOC
1799 $mw =& MagicWord::get( MAG_FORCETOC );
1800 if ($mw->matchAndRemove( $text ) ) {
1801 $doShowToc = 1;
1802 }
1803
1804
1805 # We need this to perform operations on the HTML
1806 $sk =& $this->mOptions->getSkin();
1807
1808 # headline counter
1809 $headlineCount = 0;
1810
1811 # Ugh .. the TOC should have neat indentation levels which can be
1812 # passed to the skin functions. These are determined here
1813 $toclevel = 0;
1814 $toc = "";
1815 $full = "";
1816 $head = array();
1817 $sublevelCount = array();
1818 $level = 0;
1819 $prevlevel = 0;
1820 foreach( $matches[3] as $headline ) {
1821 $numbering = "";
1822 if( $level ) {
1823 $prevlevel = $level;
1824 }
1825 $level = $matches[1][$headlineCount];
1826 if( ( $doNumberHeadings || $doShowToc ) && $prevlevel && $level > $prevlevel ) {
1827 # reset when we enter a new level
1828 $sublevelCount[$level] = 0;
1829 $toc .= $sk->tocIndent( $level - $prevlevel );
1830 $toclevel += $level - $prevlevel;
1831 }
1832 if( ( $doNumberHeadings || $doShowToc ) && $level < $prevlevel ) {
1833 # reset when we step back a level
1834 $sublevelCount[$level+1]=0;
1835 $toc .= $sk->tocUnindent( $prevlevel - $level );
1836 $toclevel -= $prevlevel - $level;
1837 }
1838 # count number of headlines for each level
1839 @$sublevelCount[$level]++;
1840 if( $doNumberHeadings || $doShowToc ) {
1841 $dot = 0;
1842 for( $i = 1; $i <= $level; $i++ ) {
1843 if( !empty( $sublevelCount[$i] ) ) {
1844 if( $dot ) {
1845 $numbering .= ".";
1846 }
1847 $numbering .= $sublevelCount[$i];
1848 $dot = 1;
1849 }
1850 }
1851 }
1852
1853 # The canonized header is a version of the header text safe to use for links
1854 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1855 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
1856
1857 # strip out HTML
1858 $canonized_headline = preg_replace( "/<.*?" . ">/","",$canonized_headline );
1859 $tocline = trim( $canonized_headline );
1860 $canonized_headline = preg_replace("/[ \\?&\\/<>\\(\\)\\[\\]=,+']+/", '_', urlencode( do_html_entity_decode( $tocline, ENT_COMPAT, $wgInputEncoding ) ) );
1861 # strip out urlencoded &nbsp; (inserted for french spaces, e.g. first space in 'something : something')
1862 $canonized_headline = str_replace('%C2%A0','_', $canonized_headline);
1863 $refer[$headlineCount] = $canonized_headline;
1864
1865 # count how many in assoc. array so we can track dupes in anchors
1866 @$refers[$canonized_headline]++;
1867 $refcount[$headlineCount]=$refers[$canonized_headline];
1868
1869 # Prepend the number to the heading text
1870
1871 if( $doNumberHeadings || $doShowToc ) {
1872 $tocline = $numbering . " " . $tocline;
1873
1874 # Don't number the heading if it is the only one (looks silly)
1875 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1876 # the two are different if the line contains a link
1877 $headline=$numbering . " " . $headline;
1878 }
1879 }
1880
1881 # Create the anchor for linking from the TOC to the section
1882 $anchor = $canonized_headline;
1883 if($refcount[$headlineCount] > 1 ) {
1884 $anchor .= "_" . $refcount[$headlineCount];
1885 }
1886 if( $doShowToc ) {
1887 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1888 }
1889 if( $showEditLink ) {
1890 if ( empty( $head[$headlineCount] ) ) {
1891 $head[$headlineCount] = "";
1892 }
1893 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+1);
1894 }
1895
1896 # Add the edit section span
1897 if( $rightClickHack ) {
1898 $headline = $sk->editSectionScript($headlineCount+1,$headline);
1899 }
1900
1901 # give headline the correct <h#> tag
1902 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1903
1904 $headlineCount++;
1905 }
1906
1907 if( $doShowToc ) {
1908 $toclines = $headlineCount;
1909 $toc .= $sk->tocUnindent( $toclevel );
1910 $toc = $sk->tocTable( $toc );
1911 }
1912
1913 # split up and insert constructed headlines
1914
1915 $blocks = preg_split( "/<H[1-6].*?" . ">.*?<\/H[1-6]>/i", $text );
1916 $i = 0;
1917
1918 foreach( $blocks as $block ) {
1919 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
1920 # This is the [edit] link that appears for the top block of text when
1921 # section editing is enabled
1922
1923 # Disabled because it broke block formatting
1924 # For example, a bullet point in the top line
1925 # $full .= $sk->editSectionLink(0);
1926 }
1927 $full .= $block;
1928 if( $doShowToc && !$i && $isMain) {
1929 # Top anchor now in skin
1930 $full = $full.$toc;
1931 }
1932
1933 if( !empty( $head[$i] ) ) {
1934 $full .= $head[$i];
1935 }
1936 $i++;
1937 }
1938
1939 return $full;
1940 }
1941
1942 /* private */ function doMagicISBN( &$tokenizer )
1943 {
1944 global $wgLang;
1945
1946 # Check whether next token is a text token
1947 # If yes, fetch it and convert the text into a
1948 # Special::BookSources link
1949 $token = $tokenizer->previewToken();
1950 while ( $token["type"] == "" )
1951 {
1952 $tokenizer->nextToken();
1953 $token = $tokenizer->previewToken();
1954 }
1955 if ( $token["type"] == "text" )
1956 {
1957 $token = $tokenizer->nextToken();
1958 $x = $token["text"];
1959 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1960
1961 $isbn = $blank = "" ;
1962 while ( " " == $x{0} ) {
1963 $blank .= " ";
1964 $x = substr( $x, 1 );
1965 }
1966 while ( strstr( $valid, $x{0} ) != false ) {
1967 $isbn .= $x{0};
1968 $x = substr( $x, 1 );
1969 }
1970 $num = str_replace( "-", "", $isbn );
1971 $num = str_replace( " ", "", $num );
1972
1973 if ( "" == $num ) {
1974 $text = "ISBN $blank$x";
1975 } else {
1976 $titleObj = Title::makeTitle( NS_SPECIAL, "Booksources" );
1977 $text = "<a href=\"" .
1978 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
1979 "\" class=\"internal\">ISBN $isbn</a>";
1980 $text .= $x;
1981 }
1982 } else {
1983 $text = "ISBN ";
1984 }
1985 return $text;
1986 }
1987 /* private */ function doMagicRFC( &$tokenizer )
1988 {
1989 global $wgLang;
1990
1991 # Check whether next token is a text token
1992 # If yes, fetch it and convert the text into a
1993 # link to an RFC source
1994 $token = $tokenizer->previewToken();
1995 while ( $token["type"] == "" )
1996 {
1997 $tokenizer->nextToken();
1998 $token = $tokenizer->previewToken();
1999 }
2000 if ( $token["type"] == "text" )
2001 {
2002 $token = $tokenizer->nextToken();
2003 $x = $token["text"];
2004 $valid = "0123456789";
2005
2006 $rfc = $blank = "" ;
2007 while ( " " == $x{0} ) {
2008 $blank .= " ";
2009 $x = substr( $x, 1 );
2010 }
2011 while ( strstr( $valid, $x{0} ) != false ) {
2012 $rfc .= $x{0};
2013 $x = substr( $x, 1 );
2014 }
2015
2016 if ( "" == $rfc ) {
2017 $text .= "RFC $blank$x";
2018 } else {
2019 $url = wfmsg( "rfcurl" );
2020 $url = str_replace( "$1", $rfc, $url);
2021 $sk =& $this->mOptions->getSkin();
2022 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
2023 $text = "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2024 }
2025 } else {
2026 $text = "RFC ";
2027 }
2028 return $text;
2029 }
2030
2031 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true )
2032 {
2033 $this->mOptions = $options;
2034 $this->mTitle =& $title;
2035 $this->mOutputType = OT_WIKI;
2036
2037 if ( $clearState ) {
2038 $this->clearState();
2039 }
2040
2041 $stripState = false;
2042 $pairs = array(
2043 "\r\n" => "\n",
2044 );
2045 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2046 // now with regexes
2047 $pairs = array(
2048 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2049 "/<br *?>/i" => "<br/>",
2050 );
2051 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2052 $text = $this->strip( $text, $stripState, false );
2053 $text = $this->pstPass2( $text, $user );
2054 $text = $this->unstrip( $text, $stripState );
2055 return $text;
2056 }
2057
2058 /* private */ function pstPass2( $text, &$user )
2059 {
2060 global $wgLang, $wgLocaltimezone, $wgCurParser;
2061
2062 # Variable replacement
2063 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2064 $text = $this->replaceVariables( $text );
2065
2066 # Signatures
2067 #
2068 $n = $user->getName();
2069 $k = $user->getOption( "nickname" );
2070 if ( "" == $k ) { $k = $n; }
2071 if(isset($wgLocaltimezone)) {
2072 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
2073 }
2074 /* Note: this is an ugly timezone hack for the European wikis */
2075 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
2076 " (" . date( "T" ) . ")";
2077 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
2078
2079 $text = preg_replace( "/~~~~~/", $d, $text );
2080 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
2081 Namespace::getUser() ) . ":$n|$k]] $d", $text );
2082 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
2083 Namespace::getUser() ) . ":$n|$k]]", $text );
2084
2085 # Context links: [[|name]] and [[name (context)|]]
2086 #
2087 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2088 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2089 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2090 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2091
2092 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2093 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2094 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2095 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2096 # [[ns:page (cont)|]]
2097 $context = "";
2098 $t = $this->mTitle->getText();
2099 if ( preg_match( $conpat, $t, $m ) ) {
2100 $context = $m[2];
2101 }
2102 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
2103 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
2104 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
2105
2106 if ( "" == $context ) {
2107 $text = preg_replace( $p2, "[[\\1]]", $text );
2108 } else {
2109 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2110 }
2111
2112 /*
2113 $mw =& MagicWord::get( MAG_SUBST );
2114 $wgCurParser = $this->fork();
2115 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2116 $this->merge( $wgCurParser );
2117 */
2118
2119 # Trim trailing whitespace
2120 # MAG_END (__END__) tag allows for trailing
2121 # whitespace to be deliberately included
2122 $text = rtrim( $text );
2123 $mw =& MagicWord::get( MAG_END );
2124 $mw->matchAndRemove( $text );
2125
2126 return $text;
2127 }
2128
2129 # Set up some variables which are usually set up in parse()
2130 # so that an external function can call some class members with confidence
2131 function startExternalParse( &$title, $options, $outputType, $clearState = true )
2132 {
2133 $this->mTitle =& $title;
2134 $this->mOptions = $options;
2135 $this->mOutputType = $outputType;
2136 if ( $clearState ) {
2137 $this->clearState();
2138 }
2139 }
2140
2141 function transformMsg( $text, $options ) {
2142 global $wgTitle;
2143 static $executing = false;
2144
2145 # Guard against infinite recursion
2146 if ( $executing ) {
2147 return $text;
2148 }
2149 $executing = true;
2150
2151 $this->mTitle = $wgTitle;
2152 $this->mOptions = $options;
2153 $this->mOutputType = OT_MSG;
2154 $this->clearState();
2155 $text = $this->replaceVariables( $text );
2156
2157 $executing = false;
2158 return $text;
2159 }
2160 }
2161
2162 class ParserOutput
2163 {
2164 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2165
2166 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2167 $containsOldMagic = false )
2168 {
2169 $this->mText = $text;
2170 $this->mLanguageLinks = $languageLinks;
2171 $this->mCategoryLinks = $categoryLinks;
2172 $this->mContainsOldMagic = $containsOldMagic;
2173 }
2174
2175 function getText() { return $this->mText; }
2176 function getLanguageLinks() { return $this->mLanguageLinks; }
2177 function getCategoryLinks() { return $this->mCategoryLinks; }
2178 function containsOldMagic() { return $this->mContainsOldMagic; }
2179 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2180 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2181 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2182 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2183
2184 function merge( $other ) {
2185 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2186 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2187 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2188 }
2189
2190 }
2191
2192 class ParserOptions
2193 {
2194 # All variables are private
2195 var $mUseTeX; # Use texvc to expand <math> tags
2196 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2197 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2198 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2199 var $mAllowExternalImages; # Allow external images inline
2200 var $mSkin; # Reference to the preferred skin
2201 var $mDateFormat; # Date format index
2202 var $mEditSection; # Create "edit section" links
2203 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2204 var $mNumberHeadings; # Automatically number headings
2205 var $mShowToc; # Show table of contents
2206
2207 function getUseTeX() { return $this->mUseTeX; }
2208 function getUseCategoryMagic() { return $this->mUseCategoryMagic; }
2209 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2210 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2211 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2212 function getSkin() { return $this->mSkin; }
2213 function getDateFormat() { return $this->mDateFormat; }
2214 function getEditSection() { return $this->mEditSection; }
2215 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
2216 function getNumberHeadings() { return $this->mNumberHeadings; }
2217 function getShowToc() { return $this->mShowToc; }
2218
2219 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
2220 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic, $x ); }
2221 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
2222 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
2223 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
2224 function setSkin( $x ) { return wfSetRef( $this->mSkin, $x ); }
2225 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
2226 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
2227 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
2228 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
2229 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
2230
2231 /* static */ function newFromUser( &$user )
2232 {
2233 $popts = new ParserOptions;
2234 $popts->initialiseFromUser( $user );
2235 return $popts;
2236 }
2237
2238 function initialiseFromUser( &$userInput )
2239 {
2240 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2241
2242 if ( !$userInput ) {
2243 $user = new User;
2244 $user->setLoaded( true );
2245 } else {
2246 $user =& $userInput;
2247 }
2248
2249 $this->mUseTeX = $wgUseTeX;
2250 $this->mUseCategoryMagic = $wgUseCategoryMagic;
2251 $this->mUseDynamicDates = $wgUseDynamicDates;
2252 $this->mInterwikiMagic = $wgInterwikiMagic;
2253 $this->mAllowExternalImages = $wgAllowExternalImages;
2254 $this->mSkin =& $user->getSkin();
2255 $this->mDateFormat = $user->getOption( "date" );
2256 $this->mEditSection = $user->getOption( "editsection" );
2257 $this->mEditSectionOnRightClick = $user->getOption( "editsectiononrightclick" );
2258 $this->mNumberHeadings = $user->getOption( "numberheadings" );
2259 $this->mShowToc = $user->getOption( "showtoc" );
2260 }
2261
2262
2263 }
2264
2265 # Regex callbacks, used in Parser::replaceVariables
2266 function wfBraceSubstitution( $matches )
2267 {
2268 global $wgCurParser;
2269 return $wgCurParser->braceSubstitution( $matches );
2270 }
2271
2272 function wfArgSubstitution( $matches )
2273 {
2274 global $wgCurParser;
2275 return $wgCurParser->argSubstitution( $matches );
2276 }
2277
2278 ?>