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