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