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