5d0aa976a2a63c05ec762255f79941ca71710c1e
[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 style="clear:both;"/>\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
499 # Clean up spare ampersands; note that we probably ought to be
500 # more careful about named entities.
501 $text = preg_replace(
502 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/',
503 '&amp;',
504 $text );
505
506 $text .= $this->categoryMagic () ;
507
508 # needs to be called last
509 $text = $this->doBlockLevels( $text, $linestart );
510
511 wfProfileOut( $fname );
512 return $text;
513 }
514
515
516 /* private */ function doHeadings( $text )
517 {
518 for ( $i = 6; $i >= 1; --$i ) {
519 $h = substr( "======", 0, $i );
520 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
521 "<h{$i}>\\1</h{$i}>\\2", $text );
522 }
523 return $text;
524 }
525
526 # Note: we have to do external links before the internal ones,
527 # and otherwise take great care in the order of things here, so
528 # that we don't end up interpreting some URLs twice.
529
530 /* private */ function replaceExternalLinks( $text )
531 {
532 $fname = "Parser::replaceExternalLinks";
533 wfProfileIn( $fname );
534 $text = $this->subReplaceExternalLinks( $text, "http", true );
535 $text = $this->subReplaceExternalLinks( $text, "https", true );
536 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
537 $text = $this->subReplaceExternalLinks( $text, "irc", false );
538 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
539 $text = $this->subReplaceExternalLinks( $text, "news", false );
540 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
541 wfProfileOut( $fname );
542 return $text;
543 }
544
545 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
546 {
547 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
548 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
549
550 # this is the list of separators that should be ignored if they
551 # are the last character of an URL but that should be included
552 # if they occur within the URL, e.g. "go to www.foo.com, where .."
553 # in this case, the last comma should not become part of the URL,
554 # but in "www.foo.com/123,2342,32.htm" it should.
555 $sep = ",;\.:";
556 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
557 $images = "gif|png|jpg|jpeg";
558
559 # PLEASE NOTE: The curly braces { } are not part of the regex,
560 # they are interpreted as part of the string (used to tell PHP
561 # that the content of the string should be inserted there).
562 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
563 "((?i){$images})([^{$uc}]|$)/";
564
565 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
566 $sk =& $this->mOptions->getSkin();
567
568 if ( $autonumber and $this->mOptions->getAllowExternalImages() ) { # Use img tags only for HTTP urls
569 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
570 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
571 }
572 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
573 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
574 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
575 "</a>\\5", $s );
576 $s = str_replace( $unique, $protocol, $s );
577
578 $a = explode( "[{$protocol}:", " " . $s );
579 $s = array_shift( $a );
580 $s = substr( $s, 1 );
581
582 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
583 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
584
585 foreach ( $a as $line ) {
586 if ( preg_match( $e1, $line, $m ) ) {
587 $link = "{$protocol}:{$m[1]}";
588 $trail = $m[2];
589 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
590 else { $text = wfEscapeHTML( $link ); }
591 } else if ( preg_match( $e2, $line, $m ) ) {
592 $link = "{$protocol}:{$m[1]}";
593 $text = $m[2];
594 $trail = $m[3];
595 } else {
596 $s .= "[{$protocol}:" . $line;
597 continue;
598 }
599 if( $link == $text || preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
600 $paren = "";
601 } else {
602 # Expand the URL for printable version
603 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
604 }
605 $la = $sk->getExternalLinkAttributes( $link, $text );
606 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
607
608 }
609 return $s;
610 }
611
612 /* private */ function handle3Quotes( &$state, $token )
613 {
614 if ( $state["strong"] !== false ) {
615 if ( $state["em"] !== false && $state["em"] > $state["strong"] )
616 {
617 # ''' lala ''lala '''
618 $s = "</em></strong><em>";
619 } else {
620 $s = "</strong>";
621 }
622 $state["strong"] = FALSE;
623 } else {
624 $s = "<strong>";
625 $state["strong"] = isset($token["pos"]) ? $token["pos"] : true;
626 }
627 return $s;
628 }
629
630 /* private */ function handle2Quotes( &$state, $token )
631 {
632 if ( $state["em"] !== false ) {
633 if ( $state["strong"] !== false && $state["strong"] > $state["em"] )
634 {
635 # ''lala'''lala'' ....'''
636 $s = "</strong></em><strong>";
637 } else {
638 $s = "</em>";
639 }
640 $state["em"] = FALSE;
641 } else {
642 $s = "<em>";
643 $state["em"] = isset($token["pos"]) ? $token["pos"] : true;
644
645 }
646 return $s;
647 }
648
649 /* private */ function handle5Quotes( &$state, $token )
650 {
651 $s = "";
652 if ( $state["em"] !== false && $state["strong"] !== false ) {
653 if ( $state["em"] < $state["strong"] ) {
654 $s .= "</strong></em>";
655 } else {
656 $s .= "</em></strong>";
657 }
658 $state["strong"] = $state["em"] = FALSE;
659 } elseif ( $state["em"] !== false ) {
660 $s .= "</em><strong>";
661 $state["em"] = FALSE;
662 $state["strong"] = $token["pos"];
663 } elseif ( $state["strong"] !== false ) {
664 $s .= "</strong><em>";
665 $state["strong"] = FALSE;
666 $state["em"] = $token["pos"];
667 } else { # not $em and not $strong
668 $s .= "<strong><em>";
669 $state["strong"] = $state["em"] = isset($token["pos"]) ? $token["pos"] : true;
670 }
671 return $s;
672 }
673
674 /* private */ function doTokenizedParser( $str )
675 {
676 global $wgLang; # for language specific parser hook
677
678 $tokenizer=Tokenizer::newFromString( $str );
679 $tokenStack = array();
680
681 $s="";
682 $state["em"] = FALSE;
683 $state["strong"] = FALSE;
684 $tagIsOpen = FALSE;
685 $threeopen = false;
686
687 # The tokenizer splits the text into tokens and returns them one by one.
688 # Every call to the tokenizer returns a new token.
689 while ( $token = $tokenizer->nextToken() )
690 {
691 switch ( $token["type"] )
692 {
693 case "text":
694 # simple text with no further markup
695 $txt = $token["text"];
696 break;
697 case "[[[":
698 # remember the tag opened with 3 [
699 $threeopen = true;
700 case "[[":
701 # link opening tag.
702 # FIXME : Treat orphaned open tags (stack not empty when text is over)
703 $tagIsOpen = TRUE;
704 array_push( $tokenStack, $token );
705 $txt="";
706 break;
707
708 case "]]]":
709 case "]]":
710 # link close tag.
711 # get text from stack, glue it together, and call the code to handle a
712 # link
713
714 if ( count( $tokenStack ) == 0 )
715 {
716 # stack empty. Found a ]] without an opening [[
717 $txt = "]]";
718 } else {
719 $linkText = "";
720 $lastToken = array_pop( $tokenStack );
721 while ( !(($lastToken["type"] == "[[[") or ($lastToken["type"] == "[[")) )
722 {
723 if( !empty( $lastToken["text"] ) ) {
724 $linkText = $lastToken["text"] . $linkText;
725 }
726 $lastToken = array_pop( $tokenStack );
727 }
728
729 $txt = $linkText ."]]";
730
731 if( isset( $lastToken["text"] ) ) {
732 $prefix = $lastToken["text"];
733 } else {
734 $prefix = "";
735 }
736 $nextToken = $tokenizer->previewToken();
737 if ( $nextToken["type"] == "text" )
738 {
739 # Preview just looks at it. Now we have to fetch it.
740 $nextToken = $tokenizer->nextToken();
741 $txt .= $nextToken["text"];
742 }
743 $fakestate = $this->mStripState;
744 $txt = $this->handleInternalLink( $this->unstrip($txt,$fakestate), $prefix );
745
746 # did the tag start with 3 [ ?
747 if($threeopen) {
748 # show the first as text
749 $txt = "[".$txt;
750 $threeopen=false;
751 }
752
753 }
754 $tagIsOpen = (count( $tokenStack ) != 0);
755 break;
756 case "----":
757 $txt = "\n<hr />\n";
758 break;
759 case "'''":
760 # This and the three next ones handle quotes
761 $txt = $this->handle3Quotes( $state, $token );
762 break;
763 case "''":
764 $txt = $this->handle2Quotes( $state, $token );
765 break;
766 case "'''''":
767 $txt = $this->handle5Quotes( $state, $token );
768 break;
769 case "":
770 # empty token
771 $txt="";
772 break;
773 case "RFC ":
774 if ( $tagIsOpen ) {
775 $txt = "RFC ";
776 } else {
777 $txt = $this->doMagicRFC( $tokenizer );
778 }
779 break;
780 case "ISBN ":
781 if ( $tagIsOpen ) {
782 $txt = "ISBN ";
783 } else {
784 $txt = $this->doMagicISBN( $tokenizer );
785 }
786 break;
787 default:
788 # Call language specific Hook.
789 $txt = $wgLang->processToken( $token, $tokenStack );
790 if ( NULL == $txt ) {
791 # An unkown token. Highlight.
792 $txt = "<font color=\"#FF0000\"><b>".$token["type"]."</b></font>";
793 $txt .= "<font color=\"#FFFF00\"><b>".$token["text"]."</b></font>";
794 }
795 break;
796 }
797 # If we're parsing the interior of a link, don't append the interior to $s,
798 # but push it to the stack so it can be processed when a ]] token is found.
799 if ( $tagIsOpen && $txt != "" ) {
800 $token["type"] = "text";
801 $token["text"] = $txt;
802 array_push( $tokenStack, $token );
803 } else {
804 $s .= $txt;
805 }
806 } #end while
807 if ( count( $tokenStack ) != 0 )
808 {
809 # still objects on stack. opened [[ tag without closing ]] tag.
810 $txt = "";
811 while ( $lastToken = array_pop( $tokenStack ) )
812 {
813 if ( $lastToken["type"] == "text" )
814 {
815 $txt = $lastToken["text"] . $txt;
816 } else {
817 $txt = $lastToken["type"] . $txt;
818 }
819 }
820 $s .= $txt;
821 }
822 return $s;
823 }
824
825 /* private */ function handleInternalLink( $line, $prefix )
826 {
827 global $wgLang, $wgLinkCache;
828 global $wgNamespacesWithSubpages, $wgLanguageCode;
829 static $fname = "Parser::handleInternalLink" ;
830 wfProfileIn( $fname );
831
832 wfProfileIn( "$fname-setup" );
833 static $tc = FALSE;
834 if ( !$tc ) { $tc = Title::legalChars() . "#"; }
835 $sk =& $this->mOptions->getSkin();
836
837 # Match a link having the form [[namespace:link|alternate]]trail
838 static $e1 = FALSE;
839 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
840 # Match the end of a line for a word that's not followed by whitespace,
841 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
842 #$e2 = "/^(.*)\\b(\\w+)\$/suD";
843 #$e2 = "/^(.*\\s)(\\S+)\$/suD";
844 static $e2 = '/^(.*\s)([a-zA-Z\x80-\xff]+)$/sD';
845
846
847 # Special and Media are pseudo-namespaces; no pages actually exist in them
848 static $image = FALSE;
849 static $special = FALSE;
850 static $media = FALSE;
851 static $category = FALSE;
852 if ( !$image ) { $image = Namespace::getImage(); }
853 if ( !$special ) { $special = Namespace::getSpecial(); }
854 if ( !$media ) { $media = Namespace::getMedia(); }
855 if ( !$category ) { $category = wfMsg ( "category" ) ; }
856
857 $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
858
859 wfProfileOut( "$fname-setup" );
860 $s = "";
861
862 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
863 $text = $m[2];
864 $trail = $m[3];
865 } else { # Invalid form; output directly
866 $s .= $prefix . "[[" . $line ;
867 return $s;
868 }
869
870 /* Valid link forms:
871 Foobar -- normal
872 :Foobar -- override special treatment of prefix (images, language links)
873 /Foobar -- convert to CurrentPage/Foobar
874 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
875 */
876 $c = substr($m[1],0,1);
877 $noforce = ($c != ":");
878 if( $c == "/" ) { # subpage
879 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
880 $m[1]=substr($m[1],1,strlen($m[1])-2);
881 $noslash=$m[1];
882 } else {
883 $noslash=substr($m[1],1);
884 }
885 if($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]) { # subpages allowed here
886 $link = $this->mTitle->getPrefixedText(). "/" . trim($noslash);
887 if( "" == $text ) {
888 $text= $m[1];
889 } # this might be changed for ugliness reasons
890 } else {
891 $link = $noslash; # no subpage allowed, use standard link
892 }
893 } elseif( $noforce ) { # no subpage
894 $link = $m[1];
895 } else {
896 $link = substr( $m[1], 1 );
897 }
898 if( "" == $text )
899 $text = $link;
900
901 $nt = Title::newFromText( $link );
902 if( !$nt ) {
903 $s .= $prefix . "[[" . $line;
904 return $s;
905 }
906 $ns = $nt->getNamespace();
907 $iw = $nt->getInterWiki();
908 if( $noforce ) {
909 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
910 array_push( $this->mOutput->mLanguageLinks, $nt->getPrefixedText() );
911 return (trim($s) == '')? '': $s;
912 }
913 if( $ns == $image ) {
914 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
915 $wgLinkCache->addImageLinkObj( $nt );
916 return $s;
917 }
918 }
919 if( ( $nt->getPrefixedText() == $this->mTitle->getPrefixedText() ) &&
920 ( strpos( $link, "#" ) == FALSE ) ) {
921 $s .= $prefix . "<strong>" . $text . "</strong>" . $trail;
922 return $s;
923 }
924
925 # Category feature
926 $catns = strtoupper ( $nt->getDBkey () ) ;
927 $catns = explode ( ":" , $catns ) ;
928 if ( count ( $catns ) > 1 ) $catns = array_shift ( $catns ) ;
929 else $catns = "" ;
930 if ( $catns == strtoupper($category) && $this->mOptions->getUseCategoryMagic() ) {
931 $t = explode ( ":" , $nt->getText() ) ;
932 array_shift ( $t ) ;
933 $t = implode ( ":" , $t ) ;
934 $t = $wgLang->ucFirst ( $t ) ;
935 $nnt = Title::newFromText ( $category.":".$t ) ;
936 $t = $sk->makeLinkObj( $nnt, $t, "", $trail , $prefix );
937 $this->mOutput->mCategoryLinks[] = $t ;
938 $s .= $prefix . $trail ;
939 return $s ;
940 }
941
942 if( $ns == $media ) {
943 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
944 $wgLinkCache->addImageLinkObj( $nt );
945 return $s;
946 } elseif( $ns == $special ) {
947 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, "", $trail );
948 return $s;
949 }
950 $s .= $sk->makeLinkObj( $nt, $text, "", $trail , $prefix );
951
952 wfProfileOut( $fname );
953 return $s;
954 }
955
956 # Some functions here used by doBlockLevels()
957 #
958 /* private */ function closeParagraph()
959 {
960 $result = "";
961 if ( '' != $this->mLastSection ) {
962 $result = "</" . $this->mLastSection . ">\n";
963 }
964 $this->mLastSection = "";
965 return $result;
966 }
967 # getCommon() returns the length of the longest common substring
968 # of both arguments, starting at the beginning of both.
969 #
970 /* private */ function getCommon( $st1, $st2 )
971 {
972 $fl = strlen( $st1 );
973 $shorter = strlen( $st2 );
974 if ( $fl < $shorter ) { $shorter = $fl; }
975
976 for ( $i = 0; $i < $shorter; ++$i ) {
977 if ( $st1{$i} != $st2{$i} ) { break; }
978 }
979 return $i;
980 }
981 # These next three functions open, continue, and close the list
982 # element appropriate to the prefix character passed into them.
983 #
984 /* private */ function openList( $char )
985 {
986 $result = $this->closeParagraph();
987
988 if ( "*" == $char ) { $result .= "<ul><li>"; }
989 else if ( "#" == $char ) { $result .= "<ol><li>"; }
990 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
991 else if ( ";" == $char ) {
992 $result .= "<dl><dt>";
993 $this->mDTopen = true;
994 }
995 else { $result = "<!-- ERR 1 -->"; }
996
997 return $result;
998 }
999
1000 /* private */ function nextItem( $char )
1001 {
1002 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1003 else if ( ":" == $char || ";" == $char ) {
1004 $close = "</dd>";
1005 if ( $this->mDTopen ) { $close = "</dt>"; }
1006 if ( ";" == $char ) {
1007 $this->mDTopen = true;
1008 return $close . "<dt>";
1009 } else {
1010 $this->mDTopen = false;
1011 return $close . "<dd>";
1012 }
1013 }
1014 return "<!-- ERR 2 -->";
1015 }
1016
1017 /* private */function closeList( $char )
1018 {
1019 if ( "*" == $char ) { $text = "</li></ul>"; }
1020 else if ( "#" == $char ) { $text = "</li></ol>"; }
1021 else if ( ":" == $char ) {
1022 if ( $this->mDTopen ) {
1023 $this->mDTopen = false;
1024 $text = "</dt></dl>";
1025 } else {
1026 $text = "</dd></dl>";
1027 }
1028 }
1029 else { return "<!-- ERR 3 -->"; }
1030 return $text."\n";
1031 }
1032
1033 /* private */ function doBlockLevels( $text, $linestart )
1034 {
1035 $fname = "Parser::doBlockLevels";
1036 wfProfileIn( $fname );
1037 # Parsing through the text line by line. The main thing
1038 # happening here is handling of block-level elements p, pre,
1039 # and making lists from lines starting with * # : etc.
1040 #
1041 $a = explode( "\n", $text );
1042 $lastPref = $text = $lastLine = '';
1043 $this->mDTopen = $inBlockElem = false;
1044
1045 if ( ! $linestart ) { $text .= array_shift( $a ); }
1046 foreach ( $a as $t ) {
1047 if ( "" != $text ) { $text .= "\n"; }
1048
1049 $oLine = $t;
1050 $opl = strlen( $lastPref );
1051 $npl = strspn( $t, "*#:;" );
1052 $pref = substr( $t, 0, $npl );
1053 $pref2 = str_replace( ";", ":", $pref );
1054 $t = substr( $t, $npl );
1055
1056 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1057 $text .= $this->nextItem( substr( $pref, -1 ) );
1058
1059 if ( ";" == substr( $pref, -1 ) ) {
1060 $cpos = strpos( $t, ":" );
1061 if ( ! ( false === $cpos ) ) {
1062 $term = substr( $t, 0, $cpos );
1063 $text .= $term . $this->nextItem( ":" );
1064 $t = substr( $t, $cpos + 1 );
1065 }
1066 }
1067 } else if (0 != $npl || 0 != $opl) {
1068 $cpl = $this->getCommon( $pref, $lastPref );
1069
1070 while ( $cpl < $opl ) {
1071 $text .= $this->closeList( $lastPref{$opl-1} );
1072 --$opl;
1073 }
1074 if ( $npl <= $cpl && $cpl > 0 ) {
1075 $text .= $this->nextItem( $pref{$cpl-1} );
1076 }
1077 while ( $npl > $cpl ) {
1078 $char = substr( $pref, $cpl, 1 );
1079 $text .= $this->openList( $char );
1080
1081 if ( ";" == $char ) {
1082 $cpos = strpos( $t, ":" );
1083 if ( ! ( false === $cpos ) ) {
1084 $term = substr( $t, 0, $cpos );
1085 $text .= $term . $this->nextItem( ":" );
1086 $t = substr( $t, $cpos + 1 );
1087 }
1088 }
1089 ++$cpl;
1090 }
1091 $lastPref = $pref2;
1092 }
1093 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1094 $uniq_prefix = UNIQ_PREFIX;
1095 // XXX: use a stack for nestable elements like span, table and div
1096 $openmatch = preg_match("/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<div|<pre|<tr|<td|<p)/i", $t );
1097 $closematch = preg_match(
1098 "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|".
1099 "<\\/div|<hr|<\\/td|<\\/pre|<\\/p|".$uniq_prefix."-pre)/i", $t );
1100 if ( $openmatch or $closematch ) {
1101 $text .= $this->closeParagraph();
1102 if ( $closematch ) {
1103 $inBlockElem = false;
1104 } else {
1105 $inBlockElem = true;
1106 }
1107 } else if ( !$inBlockElem ) {
1108 if ( " " == $t{0} ) {
1109 $newSection = "pre";
1110 if ($this->mLastSection != 'pre') {
1111 $text .= $this->closeParagraph();
1112 $text .= "<" . $newSection . ">";
1113 $this->mLastSection = $newSection;
1114 }
1115 } else {
1116 $newSection = "p";
1117 if ( ''==trim($t) && ( '' != trim($lastLine) )) {
1118 $text .= $this->closeParagraph();
1119 $text .= "<" . $newSection . ">";
1120 $this->mLastSection = $newSection;
1121 }
1122 }
1123
1124 }
1125 }
1126 $lastLine = $t;
1127 $text .= $t;
1128 }
1129 while ( $npl ) {
1130 $text .= $this->closeList( $pref2{$npl-1} );
1131 --$npl;
1132 }
1133 if ( "" != $this->mLastSection ) {
1134 $text .= "</" . $this->mLastSection . ">";
1135 $this->mLastSection = "";
1136 }
1137 wfProfileOut( $fname );
1138 return $text;
1139 }
1140
1141 function getVariableValue( $index ) {
1142 global $wgLang, $wgSitename, $wgServer;
1143
1144 switch ( $index ) {
1145 case MAG_CURRENTMONTH:
1146 return date( "m" );
1147 case MAG_CURRENTMONTHNAME:
1148 return $wgLang->getMonthName( date("n") );
1149 case MAG_CURRENTMONTHNAMEGEN:
1150 return $wgLang->getMonthNameGen( date("n") );
1151 case MAG_CURRENTDAY:
1152 return date("j");
1153 case MAG_CURRENTDAYNAME:
1154 return $wgLang->getWeekdayName( date("w")+1 );
1155 case MAG_CURRENTYEAR:
1156 return date( "Y" );
1157 case MAG_CURRENTTIME:
1158 return $wgLang->time( wfTimestampNow(), false );
1159 case MAG_NUMBEROFARTICLES:
1160 return wfNumberOfArticles();
1161 case MAG_SITENAME:
1162 return $wgSitename;
1163 case MAG_SERVER:
1164 return $wgServer;
1165 default:
1166 return NULL;
1167 }
1168 }
1169
1170 function initialiseVariables()
1171 {
1172 global $wgVariableIDs;
1173 $this->mVariables = array();
1174 foreach ( $wgVariableIDs as $id ) {
1175 $mw =& MagicWord::get( $id );
1176 $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
1177 }
1178 }
1179
1180 /* private */ function replaceVariables( $text )
1181 {
1182 global $wgLang, $wgCurParser;
1183 global $wgScript, $wgArticlePath;
1184
1185 $fname = "Parser::replaceVariables";
1186 wfProfileIn( $fname );
1187
1188 $bail = false;
1189 if ( !$this->mVariables ) {
1190 $this->initialiseVariables();
1191 }
1192 $titleChars = Title::legalChars();
1193 $regex = "/{{([$titleChars\\|]*?)}}/s";
1194
1195 # "Recursive" variable expansion: run it through a couple of passes
1196 for ( $i=0; $i<MAX_INCLUDE_REPEAT && !$bail; $i++ ) {
1197 $oldText = $text;
1198
1199 # It's impossible to rebind a global in PHP
1200 # Instead, we run the substitution on a copy, then merge the changed fields back in
1201 $wgCurParser = $this->fork();
1202
1203 $text = preg_replace_callback( $regex, "wfBraceSubstitution", $text );
1204 if ( $oldText == $text ) {
1205 $bail = true;
1206 }
1207 $this->merge( $wgCurParser );
1208 }
1209
1210 return $text;
1211 }
1212
1213 # Returns a copy of this object except with various variables cleared
1214 # This copy can be re-merged with the parent after operations on the copy
1215 function fork()
1216 {
1217 $copy = $this;
1218 $copy->mOutput = new ParserOutput;
1219 return $copy;
1220 }
1221
1222 # Merges a copy split off with fork()
1223 function merge( &$copy )
1224 {
1225 # Output objects
1226 $this->mOutput->merge( $copy->mOutput );
1227
1228 # Include throttling arrays
1229 foreach( $copy->mIncludeCount as $dbk => $count ) {
1230 if ( array_key_exists( $dbk, $this->mIncludeCount ) ) {
1231 $this->mIncludeCount[$dbk] += $count;
1232 } else {
1233 $this->mIncludeCount[$dbk] = $count;
1234 }
1235 }
1236
1237 # Strip states
1238 foreach( $copy->mStripState as $dictName => $contentDict ) {
1239 $this->mStripState[$dictName] += $contentDict;
1240 }
1241 }
1242
1243 function braceSubstitution( $matches )
1244 {
1245 global $wgLinkCache, $wgLang;
1246 $fname = "Parser::braceSubstitution";
1247 $found = false;
1248 $nowiki = false;
1249
1250 $text = $matches[1];
1251
1252 # SUBST
1253 $mwSubst =& MagicWord::get( MAG_SUBST );
1254 if ( $mwSubst->matchStartAndRemove( $text ) ) {
1255 if ( $this->mOutputType != OT_WIKI ) {
1256 # Invalid SUBST not replaced at PST time
1257 # Return without further processing
1258 $text = $matches[0];
1259 $found = true;
1260 }
1261 } elseif ( $this->mOutputType == OT_WIKI ) {
1262 # SUBST not found in PST pass, do nothing
1263 $text = $matches[0];
1264 $found = true;
1265 }
1266
1267 # MSG, MSGNW and INT
1268 if ( !$found ) {
1269 # Check for MSGNW:
1270 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1271 if ( $mwMsgnw->matchStartAndRemove( $text ) ) {
1272 $nowiki = true;
1273 } else {
1274 # Remove obsolete MSG:
1275 $mwMsg =& MagicWord::get( MAG_MSG );
1276 $mwMsg->matchStartAndRemove( $text );
1277 }
1278
1279 # Check if it is an internal message
1280 $mwInt =& MagicWord::get( MAG_INT );
1281 if ( $mwInt->matchStartAndRemove( $text ) ) {
1282 $text = wfMsg( $text );
1283 $found = true;
1284 }
1285 }
1286
1287 # NS
1288 if ( !$found ) {
1289 # Check for NS: (namespace expansion)
1290 $mwNs = MagicWord::get( MAG_NS );
1291 if ( $mwNs->matchStartAndRemove( $text ) ) {
1292 if ( intval( $text ) ) {
1293 $text = $wgLang->getNsText( intval( $text ) );
1294 $found = true;
1295 } else {
1296 $index = Namespace::getCanonicalIndex( strtolower( $text ) );
1297 if ( !is_null( $index ) ) {
1298 $text = $wgLang->getNsText( $index );
1299 $found = true;
1300 }
1301 }
1302 }
1303 }
1304
1305 # LOCALURL and LOCALURLE
1306 if ( !$found ) {
1307 $mwLocal = MagicWord::get( MAG_LOCALURL );
1308 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1309
1310 if ( $mwLocal->matchStartAndRemove( $text ) ) {
1311 $func = 'getLocalURL';
1312 } elseif ( $mwLocalE->matchStartAndRemove( $text ) ) {
1313 $func = 'escapeLocalURL';
1314 } else {
1315 $func = '';
1316 }
1317
1318 if ( $func !== '' ) {
1319 $args = explode( "|", $text );
1320 $n = count( $args );
1321 if ( $n > 0 ) {
1322 $title = Title::newFromText( $args[0] );
1323 if ( !is_null( $title ) ) {
1324 if ( $n > 1 ) {
1325 $text = $title->$func( $args[1] );
1326 } else {
1327 $text = $title->$func();
1328 }
1329 $found = true;
1330 }
1331 }
1332 }
1333 }
1334
1335 # Check for a match against internal variables
1336 if ( !$found && array_key_exists( $text, $this->mVariables ) ) {
1337 $text = $this->mVariables[$text];
1338 $found = true;
1339 $this->mOutput->mContainsOldMagic = true;
1340 }
1341
1342 # Load from database
1343 if ( !$found ) {
1344 $title = Title::newFromText( $text, NS_TEMPLATE );
1345 if ( is_object( $title ) && !$title->isExternal() ) {
1346 # Check for excessive inclusion
1347 $dbk = $title->getPrefixedDBkey();
1348 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
1349 $this->mIncludeCount[$dbk] = 0;
1350 }
1351 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
1352 $article = new Article( $title );
1353 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1354 if ( $articleContent !== false ) {
1355 $found = true;
1356 $text = $articleContent;
1357
1358 # Escaping and link table handling
1359 # Not required for preSaveTransform()
1360 if ( $this->mOutputType == OT_HTML ) {
1361 if ( $nowiki ) {
1362 $text = wfEscapeWikiText( $text );
1363 } else {
1364 $text = $this->removeHTMLtags( $text );
1365 }
1366 # Do not enter included links in link table
1367 $wgLinkCache->suspend();
1368
1369 # Run full parser on the included text
1370 $text = $this->strip( $text, $this->mStripState );
1371 $text = $this->doWikiPass2( $text, true );
1372
1373 # Add the result to the strip state for re-inclusion after
1374 # the rest of the processing
1375 $text = $this->insertStripItem( $text, $this->mStripState );
1376
1377 # Resume the link cache and register the inclusion as a link
1378 $wgLinkCache->resume();
1379 $wgLinkCache->addLinkObj( $title );
1380
1381 }
1382 }
1383 }
1384
1385 # If the title is valid but undisplayable, make a link to it
1386 if ( $this->mOutputType == OT_HTML && !$found ) {
1387 $text = "[[" . $title->getPrefixedText() . "]]";
1388 $found = true;
1389 }
1390 }
1391 }
1392
1393 if ( !$found ) {
1394 return $matches[0];
1395 } else {
1396 return $text;
1397 }
1398 }
1399
1400 # Cleans up HTML, removes dangerous tags and attributes
1401 /* private */ function removeHTMLtags( $text )
1402 {
1403 $fname = "Parser::removeHTMLtags";
1404 wfProfileIn( $fname );
1405 $htmlpairs = array( # Tags that must be closed
1406 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1407 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1408 "strike", "strong", "tt", "var", "div", "center",
1409 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1410 "ruby", "rt" , "rb" , "rp", "p"
1411 );
1412 $htmlsingle = array(
1413 "br", "hr", "li", "dt", "dd"
1414 );
1415 $htmlnest = array( # Tags that can be nested--??
1416 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1417 "dl", "font", "big", "small", "sub", "sup"
1418 );
1419 $tabletags = array( # Can only appear inside table
1420 "td", "th", "tr"
1421 );
1422
1423 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1424 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1425
1426 $htmlattrs = $this->getHTMLattrs () ;
1427
1428 # Remove HTML comments
1429 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1430
1431 $bits = explode( "<", $text );
1432 $text = array_shift( $bits );
1433 $tagstack = array(); $tablestack = array();
1434
1435 foreach ( $bits as $x ) {
1436 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1437 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1438 $x, $regs );
1439 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1440 error_reporting( $prev );
1441
1442 $badtag = 0 ;
1443 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1444 # Check our stack
1445 if ( $slash ) {
1446 # Closing a tag...
1447 if ( ! in_array( $t, $htmlsingle ) &&
1448 ( $ot = array_pop( $tagstack ) ) != $t ) {
1449 array_push( $tagstack, $ot );
1450 $badtag = 1;
1451 } else {
1452 if ( $t == "table" ) {
1453 $tagstack = array_pop( $tablestack );
1454 }
1455 $newparams = "";
1456 }
1457 } else {
1458 # Keep track for later
1459 if ( in_array( $t, $tabletags ) &&
1460 ! in_array( "table", $tagstack ) ) {
1461 $badtag = 1;
1462 } else if ( in_array( $t, $tagstack ) &&
1463 ! in_array ( $t , $htmlnest ) ) {
1464 $badtag = 1 ;
1465 } else if ( ! in_array( $t, $htmlsingle ) ) {
1466 if ( $t == "table" ) {
1467 array_push( $tablestack, $tagstack );
1468 $tagstack = array();
1469 }
1470 array_push( $tagstack, $t );
1471 }
1472 # Strip non-approved attributes from the tag
1473 $newparams = $this->fixTagAttributes($params);
1474
1475 }
1476 if ( ! $badtag ) {
1477 $rest = str_replace( ">", "&gt;", $rest );
1478 $text .= "<$slash$t $newparams$brace$rest";
1479 continue;
1480 }
1481 }
1482 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1483 }
1484 # Close off any remaining tags
1485 while ( $t = array_pop( $tagstack ) ) {
1486 $text .= "</$t>\n";
1487 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1488 }
1489 wfProfileOut( $fname );
1490 return $text;
1491 }
1492
1493 /*
1494 *
1495 * This function accomplishes several tasks:
1496 * 1) Auto-number headings if that option is enabled
1497 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1498 * 3) Add a Table of contents on the top for users who have enabled the option
1499 * 4) Auto-anchor headings
1500 *
1501 * It loops through all headlines, collects the necessary data, then splits up the
1502 * string and re-inserts the newly formatted headlines.
1503 *
1504 */
1505
1506 /* private */ function formatHeadings( $text )
1507 {
1508 $doNumberHeadings = $this->mOptions->getNumberHeadings();
1509 $doShowToc = $this->mOptions->getShowToc();
1510 if( !$this->mTitle->userCanEdit() ) {
1511 $showEditLink = 0;
1512 $rightClickHack = 0;
1513 } else {
1514 $showEditLink = $this->mOptions->getEditSection();
1515 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
1516 }
1517
1518 # Inhibit editsection links if requested in the page
1519 $esw =& MagicWord::get( MAG_NOEDITSECTION );
1520 if( $esw->matchAndRemove( $text ) ) {
1521 $showEditLink = 0;
1522 }
1523 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1524 # do not add TOC
1525 $mw =& MagicWord::get( MAG_NOTOC );
1526 if( $mw->matchAndRemove( $text ) ) {
1527 $doShowToc = 0;
1528 }
1529
1530 # never add the TOC to the Main Page. This is an entry page that should not
1531 # be more than 1-2 screens large anyway
1532 if( $this->mTitle->getPrefixedText() == wfMsg("mainpage") ) {
1533 $doShowToc = 0;
1534 }
1535
1536 # Get all headlines for numbering them and adding funky stuff like [edit]
1537 # links - this is for later, but we need the number of headlines right now
1538 $numMatches = preg_match_all( "/<H([1-6])(.*?" . ">)(.*?)<\/H[1-6]>/i", $text, $matches );
1539
1540 # if there are fewer than 4 headlines in the article, do not show TOC
1541 if( $numMatches < 4 ) {
1542 $doShowToc = 0;
1543 }
1544
1545 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1546 # override above conditions and always show TOC
1547 $mw =& MagicWord::get( MAG_FORCETOC );
1548 if ($mw->matchAndRemove( $text ) ) {
1549 $doShowToc = 1;
1550 }
1551
1552
1553 # We need this to perform operations on the HTML
1554 $sk =& $this->mOptions->getSkin();
1555
1556 # headline counter
1557 $headlineCount = 0;
1558
1559 # Ugh .. the TOC should have neat indentation levels which can be
1560 # passed to the skin functions. These are determined here
1561 $toclevel = 0;
1562 $toc = "";
1563 $full = "";
1564 $head = array();
1565 $sublevelCount = array();
1566 $level = 0;
1567 $prevlevel = 0;
1568 foreach( $matches[3] as $headline ) {
1569 $numbering = "";
1570 if( $level ) {
1571 $prevlevel = $level;
1572 }
1573 $level = $matches[1][$headlineCount];
1574 if( ( $doNumberHeadings || $doShowToc ) && $prevlevel && $level > $prevlevel ) {
1575 # reset when we enter a new level
1576 $sublevelCount[$level] = 0;
1577 $toc .= $sk->tocIndent( $level - $prevlevel );
1578 $toclevel += $level - $prevlevel;
1579 }
1580 if( ( $doNumberHeadings || $doShowToc ) && $level < $prevlevel ) {
1581 # reset when we step back a level
1582 $sublevelCount[$level+1]=0;
1583 $toc .= $sk->tocUnindent( $prevlevel - $level );
1584 $toclevel -= $prevlevel - $level;
1585 }
1586 # count number of headlines for each level
1587 @$sublevelCount[$level]++;
1588 if( $doNumberHeadings || $doShowToc ) {
1589 $dot = 0;
1590 for( $i = 1; $i <= $level; $i++ ) {
1591 if( !empty( $sublevelCount[$i] ) ) {
1592 if( $dot ) {
1593 $numbering .= ".";
1594 }
1595 $numbering .= $sublevelCount[$i];
1596 $dot = 1;
1597 }
1598 }
1599 }
1600
1601 # The canonized header is a version of the header text safe to use for links
1602 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1603 $canonized_headline = Parser::unstrip( $headline, $this->mStripState );
1604
1605 # strip out HTML
1606 $canonized_headline = preg_replace( "/<.*?" . ">/","",$canonized_headline );
1607 $tocline = trim( $canonized_headline );
1608 $canonized_headline = preg_replace("/[ &\\/<>\\(\\)\\[\\]=,+']+/", '_', html_entity_decode( $tocline));
1609 $refer[$headlineCount] = $canonized_headline;
1610
1611 # count how many in assoc. array so we can track dupes in anchors
1612 @$refers[$canonized_headline]++;
1613 $refcount[$headlineCount]=$refers[$canonized_headline];
1614
1615 # Prepend the number to the heading text
1616
1617 if( $doNumberHeadings || $doShowToc ) {
1618 $tocline = $numbering . " " . $tocline;
1619
1620 # Don't number the heading if it is the only one (looks silly)
1621 if( $doNumberHeadings && count( $matches[3] ) > 1) {
1622 # the two are different if the line contains a link
1623 $headline=$numbering . " " . $headline;
1624 }
1625 }
1626
1627 # Create the anchor for linking from the TOC to the section
1628 $anchor = $canonized_headline;
1629 if($refcount[$headlineCount] > 1 ) {
1630 $anchor .= "_" . $refcount[$headlineCount];
1631 }
1632 if( $doShowToc ) {
1633 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
1634 }
1635 if( $showEditLink ) {
1636 if ( empty( $head[$headlineCount] ) ) {
1637 $head[$headlineCount] = "";
1638 }
1639 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+1);
1640 }
1641
1642 # Add the edit section span
1643 if( $rightClickHack ) {
1644 $headline = $sk->editSectionScript($headlineCount+1,$headline);
1645 }
1646
1647 # give headline the correct <h#> tag
1648 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
1649
1650 $headlineCount++;
1651 }
1652
1653 if( $doShowToc ) {
1654 $toclines = $headlineCount;
1655 $toc .= $sk->tocUnindent( $toclevel );
1656 $toc = $sk->tocTable( $toc );
1657 }
1658
1659 # split up and insert constructed headlines
1660
1661 $blocks = preg_split( "/<H[1-6].*?" . ">.*?<\/H[1-6]>/i", $text );
1662 $i = 0;
1663
1664 foreach( $blocks as $block ) {
1665 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
1666 # This is the [edit] link that appears for the top block of text when
1667 # section editing is enabled
1668 $full .= $sk->editSectionLink(0);
1669 }
1670 $full .= $block;
1671 if( $doShowToc && !$i) {
1672 # Top anchor now in skin
1673 $full = $full.$toc;
1674 }
1675
1676 if( !empty( $head[$i] ) ) {
1677 $full .= $head[$i];
1678 }
1679 $i++;
1680 }
1681
1682 return $full;
1683 }
1684
1685 /* private */ function doMagicISBN( &$tokenizer )
1686 {
1687 global $wgLang;
1688
1689 # Check whether next token is a text token
1690 # If yes, fetch it and convert the text into a
1691 # Special::BookSources link
1692 $token = $tokenizer->previewToken();
1693 while ( $token["type"] == "" )
1694 {
1695 $tokenizer->nextToken();
1696 $token = $tokenizer->previewToken();
1697 }
1698 if ( $token["type"] == "text" )
1699 {
1700 $token = $tokenizer->nextToken();
1701 $x = $token["text"];
1702 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1703
1704 $isbn = $blank = "" ;
1705 while ( " " == $x{0} ) {
1706 $blank .= " ";
1707 $x = substr( $x, 1 );
1708 }
1709 while ( strstr( $valid, $x{0} ) != false ) {
1710 $isbn .= $x{0};
1711 $x = substr( $x, 1 );
1712 }
1713 $num = str_replace( "-", "", $isbn );
1714 $num = str_replace( " ", "", $num );
1715
1716 if ( "" == $num ) {
1717 $text = "ISBN $blank$x";
1718 } else {
1719 $titleObj = Title::makeTitle( NS_SPECIAL, "Booksources" );
1720 $text = "<a href=\"" .
1721 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
1722 "\" class=\"internal\">ISBN $isbn</a>";
1723 $text .= $x;
1724 }
1725 } else {
1726 $text = "ISBN ";
1727 }
1728 return $text;
1729 }
1730 /* private */ function doMagicRFC( &$tokenizer )
1731 {
1732 global $wgLang;
1733
1734 # Check whether next token is a text token
1735 # If yes, fetch it and convert the text into a
1736 # link to an RFC source
1737 $token = $tokenizer->previewToken();
1738 while ( $token["type"] == "" )
1739 {
1740 $tokenizer->nextToken();
1741 $token = $tokenizer->previewToken();
1742 }
1743 if ( $token["type"] == "text" )
1744 {
1745 $token = $tokenizer->nextToken();
1746 $x = $token["text"];
1747 $valid = "0123456789";
1748
1749 $rfc = $blank = "" ;
1750 while ( " " == $x{0} ) {
1751 $blank .= " ";
1752 $x = substr( $x, 1 );
1753 }
1754 while ( strstr( $valid, $x{0} ) != false ) {
1755 $rfc .= $x{0};
1756 $x = substr( $x, 1 );
1757 }
1758
1759 if ( "" == $rfc ) {
1760 $text .= "RFC $blank$x";
1761 } else {
1762 $url = wfmsg( "rfcurl" );
1763 $url = str_replace( "$1", $rfc, $url);
1764 $sk =& $this->mOptions->getSkin();
1765 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
1766 $text = "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
1767 }
1768 } else {
1769 $text = "RFC ";
1770 }
1771 return $text;
1772 }
1773
1774 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true )
1775 {
1776 $this->mOptions = $options;
1777 $this->mTitle =& $title;
1778 $this->mOutputType = OT_WIKI;
1779
1780 if ( $clearState ) {
1781 $this->clearState();
1782 }
1783
1784 $stripState = false;
1785 $pairs = array(
1786 "\r\n" => "\n",
1787 );
1788 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
1789 // now with regexes
1790 $pairs = array(
1791 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
1792 "/<br *?>/i" => "<br/>",
1793 );
1794 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
1795 $text = $this->strip( $text, $stripState, false );
1796 $text = $this->pstPass2( $text, $user );
1797 $text = $this->unstrip( $text, $stripState );
1798 return $text;
1799 }
1800
1801 /* private */ function pstPass2( $text, &$user )
1802 {
1803 global $wgLang, $wgLocaltimezone, $wgCurParser;
1804
1805 # Variable replacement
1806 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
1807 $text = $this->replaceVariables( $text );
1808
1809 # Signatures
1810 #
1811 $n = $user->getName();
1812 $k = $user->getOption( "nickname" );
1813 if ( "" == $k ) { $k = $n; }
1814 if(isset($wgLocaltimezone)) {
1815 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1816 }
1817 /* Note: this is an ugly timezone hack for the European wikis */
1818 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1819 " (" . date( "T" ) . ")";
1820 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1821
1822 $text = preg_replace( "/~~~~~/", $d, $text );
1823 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1824 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1825 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1826 Namespace::getUser() ) . ":$n|$k]]", $text );
1827
1828 # Context links: [[|name]] and [[name (context)|]]
1829 #
1830 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1831 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1832 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
1833 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1834
1835 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1836 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1837 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
1838 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
1839 # [[ns:page (cont)|]]
1840 $context = "";
1841 $t = $this->mTitle->getText();
1842 if ( preg_match( $conpat, $t, $m ) ) {
1843 $context = $m[2];
1844 }
1845 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1846 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1847 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1848
1849 if ( "" == $context ) {
1850 $text = preg_replace( $p2, "[[\\1]]", $text );
1851 } else {
1852 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1853 }
1854
1855 /*
1856 $mw =& MagicWord::get( MAG_SUBST );
1857 $wgCurParser = $this->fork();
1858 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
1859 $this->merge( $wgCurParser );
1860 */
1861
1862 # Trim trailing whitespace
1863 # MAG_END (__END__) tag allows for trailing
1864 # whitespace to be deliberately included
1865 $text = rtrim( $text );
1866 $mw =& MagicWord::get( MAG_END );
1867 $mw->matchAndRemove( $text );
1868
1869 return $text;
1870 }
1871
1872 # Set up some variables which are usually set up in parse()
1873 # so that an external function can call some class members with confidence
1874 function startExternalParse( &$title, $options, $outputType, $clearState = true )
1875 {
1876 $this->mTitle =& $title;
1877 $this->mOptions = $options;
1878 $this->mOutputType = $outputType;
1879 if ( $clearState ) {
1880 $this->clearState();
1881 }
1882 }
1883
1884 function transformMsg( $text, $options ) {
1885 global $wgTitle;
1886 static $executing = false;
1887
1888 # Guard against infinite recursion
1889 if ( $executing ) {
1890 return $text;
1891 }
1892 $executing = true;
1893
1894 $this->mTitle = $wgTitle;
1895 $this->mOptions = $options;
1896 $this->mOutputType = OT_MSG;
1897 $this->clearState();
1898 $text = $this->replaceVariables( $text );
1899
1900 $executing = false;
1901 return $text;
1902 }
1903 }
1904
1905 class ParserOutput
1906 {
1907 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
1908
1909 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
1910 $containsOldMagic = false )
1911 {
1912 $this->mText = $text;
1913 $this->mLanguageLinks = $languageLinks;
1914 $this->mCategoryLinks = $categoryLinks;
1915 $this->mContainsOldMagic = $containsOldMagic;
1916 }
1917
1918 function getText() { return $this->mText; }
1919 function getLanguageLinks() { return $this->mLanguageLinks; }
1920 function getCategoryLinks() { return $this->mCategoryLinks; }
1921 function containsOldMagic() { return $this->mContainsOldMagic; }
1922 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
1923 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
1924 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
1925 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
1926
1927 function merge( $other ) {
1928 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
1929 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
1930 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
1931 }
1932
1933 }
1934
1935 class ParserOptions
1936 {
1937 # All variables are private
1938 var $mUseTeX; # Use texvc to expand <math> tags
1939 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
1940 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
1941 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
1942 var $mAllowExternalImages; # Allow external images inline
1943 var $mSkin; # Reference to the preferred skin
1944 var $mDateFormat; # Date format index
1945 var $mEditSection; # Create "edit section" links
1946 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
1947 var $mNumberHeadings; # Automatically number headings
1948 var $mShowToc; # Show table of contents
1949
1950 function getUseTeX() { return $this->mUseTeX; }
1951 function getUseCategoryMagic() { return $this->mUseCategoryMagic; }
1952 function getUseDynamicDates() { return $this->mUseDynamicDates; }
1953 function getInterwikiMagic() { return $this->mInterwikiMagic; }
1954 function getAllowExternalImages() { return $this->mAllowExternalImages; }
1955 function getSkin() { return $this->mSkin; }
1956 function getDateFormat() { return $this->mDateFormat; }
1957 function getEditSection() { return $this->mEditSection; }
1958 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
1959 function getNumberHeadings() { return $this->mNumberHeadings; }
1960 function getShowToc() { return $this->mShowToc; }
1961
1962 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
1963 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic, $x ); }
1964 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
1965 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
1966 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
1967 function setSkin( $x ) { return wfSetRef( $this->mSkin, $x ); }
1968 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
1969 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
1970 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
1971 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
1972 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
1973
1974 /* static */ function newFromUser( &$user )
1975 {
1976 $popts = new ParserOptions;
1977 $popts->initialiseFromUser( &$user );
1978 return $popts;
1979 }
1980
1981 function initialiseFromUser( &$userInput )
1982 {
1983 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
1984
1985 if ( !$userInput ) {
1986 $user = new User;
1987 $user->setLoaded( true );
1988 } else {
1989 $user =& $userInput;
1990 }
1991
1992 $this->mUseTeX = $wgUseTeX;
1993 $this->mUseCategoryMagic = $wgUseCategoryMagic;
1994 $this->mUseDynamicDates = $wgUseDynamicDates;
1995 $this->mInterwikiMagic = $wgInterwikiMagic;
1996 $this->mAllowExternalImages = $wgAllowExternalImages;
1997 $this->mSkin =& $user->getSkin();
1998 $this->mDateFormat = $user->getOption( "date" );
1999 $this->mEditSection = $user->getOption( "editsection" );
2000 $this->mEditSectionOnRightClick = $user->getOption( "editsectiononrightclick" );
2001 $this->mNumberHeadings = $user->getOption( "numberheadings" );
2002 $this->mShowToc = $user->getOption( "showtoc" );
2003 }
2004
2005
2006 }
2007
2008 # Regex callbacks, used in Parser::replaceVariables
2009 function wfBraceSubstitution( $matches )
2010 {
2011 global $wgCurParser;
2012 return $wgCurParser->braceSubstitution( $matches );
2013 }
2014
2015 ?>