Allow indentation of tables using :{|
[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 # Strip javascript "expression" from stylesheets. Brute force approach:
646 # If anythin offensive is found, all attributes of the HTML tag are dropped
647
648 if( preg_match(
649 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
650 wfMungeToUtf8( $t ) ) )
651 {
652 $t='';
653 }
654
655 return trim ( $t ) ;
656 }
657
658 # interface with html tidy, used if $wgUseTidy = true
659 function tidy ( $text ) {
660 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
661 global $wgInputEncoding, $wgOutputEncoding;
662 $fname = 'Parser::tidy';
663 wfProfileIn( $fname );
664
665 $cleansource = '';
666 switch(strtoupper($wgOutputEncoding)) {
667 case 'ISO-8859-1':
668 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -latin1':' -raw';
669 break;
670 case 'UTF-8':
671 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -utf8':' -raw';
672 break;
673 default:
674 $wgTidyOpts .= ' -raw';
675 }
676
677 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
678 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
679 '<head><title>test</title></head><body>'.$text.'</body></html>';
680 $descriptorspec = array(
681 0 => array('pipe', 'r'),
682 1 => array('pipe', 'w'),
683 2 => array('file', '/dev/null', 'a')
684 );
685 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
686 if (is_resource($process)) {
687 fwrite($pipes[0], $wrappedtext);
688 fclose($pipes[0]);
689 while (!feof($pipes[1])) {
690 $cleansource .= fgets($pipes[1], 1024);
691 }
692 fclose($pipes[1]);
693 $return_value = proc_close($process);
694 }
695
696 wfProfileOut( $fname );
697
698 if( $cleansource == '' && $text != '') {
699 wfDebug( "Tidy error detected!\n" );
700 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
701 } else {
702 return $cleansource;
703 }
704 }
705
706 # parse the wiki syntax used to render tables
707 function doTableStuff ( $t ) {
708 $fname = 'Parser::doTableStuff';
709 wfProfileIn( $fname );
710
711 $t = explode ( "\n" , $t ) ;
712 $td = array () ; # Is currently a td tag open?
713 $ltd = array () ; # Was it TD or TH?
714 $tr = array () ; # Is currently a tr tag open?
715 $ltr = array () ; # tr attributes
716 $indent_level = 0; # indent level of the table
717 foreach ( $t AS $k => $x )
718 {
719 $x = trim ( $x ) ;
720 $fc = substr ( $x , 0 , 1 ) ;
721 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) )
722 {
723 $indent_level = strlen( $matches[1] );
724 $t[$k] = "\n" .
725 str_repeat( "<dl><dd>", $indent_level ) .
726 "<table " . $this->fixTagAttributes ( $matches[2] ) . '>' ;
727 array_push ( $td , false ) ;
728 array_push ( $ltd , '' ) ;
729 array_push ( $tr , false ) ;
730 array_push ( $ltr , '' ) ;
731 }
732 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
733 else if ( '|}' == substr ( $x , 0 , 2 ) )
734 {
735 $z = "</table>\n" ;
736 $l = array_pop ( $ltd ) ;
737 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
738 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
739 array_pop ( $ltr ) ;
740 $t[$k] = $z . str_repeat( "</dd></dl>", $indent_level );
741 }
742 else if ( '|-' == substr ( $x , 0 , 2 ) ) # Allows for |---------------
743 {
744 $x = substr ( $x , 1 ) ;
745 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
746 $z = '' ;
747 $l = array_pop ( $ltd ) ;
748 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
749 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
750 array_pop ( $ltr ) ;
751 $t[$k] = $z ;
752 array_push ( $tr , false ) ;
753 array_push ( $td , false ) ;
754 array_push ( $ltd , '' ) ;
755 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
756 }
757 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) # Caption
758 {
759 if ( '|+' == substr ( $x , 0 , 2 ) )
760 {
761 $fc = '+' ;
762 $x = substr ( $x , 1 ) ;
763 }
764 $after = substr ( $x , 1 ) ;
765 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
766 $after = explode ( '||' , $after ) ;
767 $t[$k] = '' ;
768 foreach ( $after AS $theline )
769 {
770 $z = '' ;
771 if ( $fc != '+' )
772 {
773 $tra = array_pop ( $ltr ) ;
774 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
775 array_push ( $tr , true ) ;
776 array_push ( $ltr , '' ) ;
777 }
778
779 $l = array_pop ( $ltd ) ;
780 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
781 if ( $fc == '|' ) $l = 'td' ;
782 else if ( $fc == '!' ) $l = 'th' ;
783 else if ( $fc == '+' ) $l = 'caption' ;
784 else $l = '' ;
785 array_push ( $ltd , $l ) ;
786 $y = explode ( '|' , $theline , 2 ) ;
787 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
788 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
789 $t[$k] .= $y ;
790 array_push ( $td , true ) ;
791 }
792 }
793 }
794
795 # Closing open td, tr && table
796 while ( count ( $td ) > 0 )
797 {
798 if ( array_pop ( $td ) ) $t[] = '</td>' ;
799 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
800 $t[] = '</table>' ;
801 }
802
803 $t = implode ( "\n" , $t ) ;
804 # $t = $this->removeHTMLtags( $t );
805 wfProfileOut( $fname );
806 return $t ;
807 }
808
809 # Parses the text and adds the result to the strip state
810 # Returns the strip tag
811 function stripParse( $text, $newline, $args )
812 {
813 $text = $this->strip( $text, $this->mStripState );
814 $text = $this->internalParse( $text, (bool)$newline, $args, false );
815 return $newline.$this->insertStripItem( $text, $this->mStripState );
816 }
817
818 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
819 $fname = 'Parser::internalParse';
820 wfProfileIn( $fname );
821
822 $text = $this->removeHTMLtags( $text );
823 $text = $this->replaceVariables( $text, $args );
824
825 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
826
827 $text = $this->doHeadings( $text );
828 if($this->mOptions->getUseDynamicDates()) {
829 global $wgDateFormatter;
830 $text = $wgDateFormatter->reformat( $this->mOptions->getDateFormat(), $text );
831 }
832 $text = $this->doAllQuotes( $text );
833 // $text = $this->doExponent( $text );
834 $text = $this->replaceExternalLinks( $text );
835 $text = $this->doMagicLinks( $text );
836 $text = $this->replaceInternalLinks ( $text );
837 $text = $this->replaceInternalLinks ( $text );
838 //$text = $this->doTokenizedParser ( $text );
839 $text = $this->doTableStuff( $text );
840 $text = $this->formatHeadings( $text, $isMain );
841 $sk =& $this->mOptions->getSkin();
842 $text = $sk->transformContent( $text );
843
844 if ( $isMain && !isset ( $this->categoryMagicDone ) ) {
845 $text .= $this->categoryMagic () ;
846 $this->categoryMagicDone = true ;
847 }
848
849 wfProfileOut( $fname );
850 return $text;
851 }
852
853 /* private */ function &doMagicLinks( &$text ) {
854 $text = $this->magicISBN( $text );
855 $text = $this->magicGEO( $text );
856 $text = $this->magicRFC( $text );
857 return $text;
858 }
859
860 # Parse ^^ tokens and return html
861 /* private */ function doExponent ( $text )
862 {
863 $fname = 'Parser::doExponent';
864 wfProfileIn( $fname);
865 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
866 wfProfileOut( $fname);
867 return $text;
868 }
869
870 # Parse headers and return html
871 /* private */ function doHeadings( $text ) {
872 $fname = 'Parser::doHeadings';
873 wfProfileIn( $fname );
874 for ( $i = 6; $i >= 1; --$i ) {
875 $h = substr( '======', 0, $i );
876 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
877 "<h{$i}>\\1</h{$i}>\\2", $text );
878 }
879 wfProfileOut( $fname );
880 return $text;
881 }
882
883 /* private */ function doAllQuotes( $text ) {
884 $fname = 'Parser::doAllQuotes';
885 wfProfileIn( $fname );
886 $outtext = '';
887 $lines = explode( "\n", $text );
888 foreach ( $lines as $line ) {
889 $outtext .= $this->doQuotes ( '', $line, '' ) . "\n";
890 }
891 $outtext = substr($outtext, 0,-1);
892 wfProfileOut( $fname );
893 return $outtext;
894 }
895
896 /* private */ function doQuotes( $pre, $text, $mode ) {
897 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
898 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
899 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
900 if ( substr ($m[2], 0, 1) == '\'' ) {
901 $m[2] = substr ($m[2], 1);
902 if ($mode == 'em') {
903 return $this->doQuotes ( $m[1], $m[2], ($m[1] == '') ? 'both' : 'emstrong' );
904 } else if ($mode == 'strong') {
905 return $m1_strong . $this->doQuotes ( '', $m[2], '' );
906 } else if (($mode == 'emstrong') || ($mode == 'both')) {
907 return $this->doQuotes ( '', $pre.$m1_strong.$m[2], 'em' );
908 } else if ($mode == 'strongem') {
909 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( '', $m[2], 'em' );
910 } else {
911 return $m[1] . $this->doQuotes ( '', $m[2], 'strong' );
912 }
913 } else {
914 if ($mode == 'strong') {
915 return $this->doQuotes ( $m[1], $m[2], ($m[1] == '') ? 'both' : 'strongem' );
916 } else if ($mode == 'em') {
917 return $m1_em . $this->doQuotes ( '', $m[2], '' );
918 } else if ($mode == 'emstrong') {
919 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( '', $m[2], 'strong' );
920 } else if (($mode == 'strongem') || ($mode == 'both')) {
921 return $this->doQuotes ( '', $pre.$m1_em.$m[2], 'strong' );
922 } else {
923 return $m[1] . $this->doQuotes ( '', $m[2], 'em' );
924 }
925 }
926 } else {
927 $text_strong = ($text == '') ? '' : "<strong>{$text}</strong>";
928 $text_em = ($text == '') ? '' : "<em>{$text}</em>";
929 if ($mode == '') {
930 return $pre . $text;
931 } else if ($mode == 'em') {
932 return $pre . $text_em;
933 } else if ($mode == 'strong') {
934 return $pre . $text_strong;
935 } else if ($mode == 'strongem') {
936 return (($pre == '') && ($text == '')) ? '' : "<strong>{$pre}{$text_em}</strong>";
937 } else {
938 return (($pre == '') && ($text == '')) ? '' : "<em>{$pre}{$text_strong}</em>";
939 }
940 }
941 }
942
943 # Note: we have to do external links before the internal ones,
944 # and otherwise take great care in the order of things here, so
945 # that we don't end up interpreting some URLs twice.
946
947 /* private */ function replaceExternalLinks( $text ) {
948 $fname = 'Parser::replaceExternalLinks';
949 wfProfileIn( $fname );
950 $text = $this->subReplaceExternalLinks( $text, 'http', true );
951 $text = $this->subReplaceExternalLinks( $text, 'https', true );
952 $text = $this->subReplaceExternalLinks( $text, 'ftp', false );
953 $text = $this->subReplaceExternalLinks( $text, 'irc', false );
954 $text = $this->subReplaceExternalLinks( $text, 'gopher', false );
955 $text = $this->subReplaceExternalLinks( $text, 'news', false );
956 $text = $this->subReplaceExternalLinks( $text, 'mailto', false );
957 wfProfileOut( $fname );
958 return $text;
959 }
960
961 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber ) {
962 $unique = '4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3';
963 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
964
965 # this is the list of separators that should be ignored if they
966 # are the last character of an URL but that should be included
967 # if they occur within the URL, e.g. "go to www.foo.com, where .."
968 # in this case, the last comma should not become part of the URL,
969 # but in "www.foo.com/123,2342,32.htm" it should.
970 $sep = ",;\.:";
971 $fnc = 'A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF';
972 $images = 'gif|png|jpg|jpeg';
973
974 # PLEASE NOTE: The curly braces { } are not part of the regex,
975 # they are interpreted as part of the string (used to tell PHP
976 # that the content of the string should be inserted there).
977 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
978 "((?i){$images})([^{$uc}]|$)/";
979
980 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
981 $sk =& $this->mOptions->getSkin();
982
983 if ( $autonumber and $this->mOptions->getAllowExternalImages() ) { # Use img tags only for HTTP urls
984 $s = preg_replace( $e1, '\\1' . $sk->makeImage( "{$unique}:\\3" .
985 '/\\4.\\5', '\\4.\\5' ) . '\\6', $s );
986 }
987 $s = preg_replace( $e2, '\\1' . "<a href=\"{$unique}:\\3\"" .
988 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
989 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
990 '</a>\\5', $s );
991 $s = str_replace( $unique, $protocol, $s );
992
993 $a = explode( "[{$protocol}:", " " . $s );
994 $s = array_shift( $a );
995 $s = substr( $s, 1 );
996
997 # Regexp for URL in square brackets
998 $e1 = "/^([{$uc}{$sep}]+)\\](.*)\$/sD";
999 # Regexp for URL with link text in square brackets
1000 $e2 = "/^([{$uc}{$sep}]+)\\s+([^\\]]+)\\](.*)\$/sD";
1001
1002 foreach ( $a as $line ) {
1003
1004 # CASE 1: Link in square brackets, e.g.
1005 # some text [http://domain.tld/some.link] more text
1006 if ( preg_match( $e1, $line, $m ) ) {
1007 $link = "{$protocol}:{$m[1]}";
1008 $trail = $m[2];
1009 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
1010 else { $text = wfEscapeHTML( $link ); }
1011 }
1012
1013 # CASE 2: Link with link text and text directly following it, e.g.
1014 # This is a collection of [http://domain.tld/some.link link]s
1015 else if ( preg_match( $e2, $line, $m ) ) {
1016 $link = "{$protocol}:{$m[1]}";
1017 $text = $m[2];
1018 $dtrail = '';
1019 $trail = $m[3];
1020 if ( preg_match( wfMsg ('linktrail'), $trail, $m2 ) ) {
1021 $dtrail = $m2[1];
1022 $trail = $m2[2];
1023 }
1024 }
1025
1026 # CASE 3: Nothing matches, just output the source text
1027 else {
1028 $s .= "[{$protocol}:" . $line;
1029 continue;
1030 }
1031
1032 if( $link == $text || preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $link ) ) {
1033 $paren = '';
1034 } else {
1035 # Expand the URL for printable version
1036 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $link ) . "</i>)</span>";
1037 }
1038 $la = $sk->getExternalLinkAttributes( $link, $text );
1039 $s .= "<a href='{$link}'{$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
1040
1041 }
1042 return $s;
1043 }
1044
1045
1046 /* private */ function replaceInternalLinks( $s ) {
1047 global $wgLang, $wgLinkCache;
1048 global $wgNamespacesWithSubpages, $wgLanguageCode;
1049 static $fname = 'Parser::replaceInternalLinks' ;
1050 wfProfileIn( $fname );
1051
1052 wfProfileIn( $fname.'-setup' );
1053 static $tc = FALSE;
1054 # the % is needed to support urlencoded titles as well
1055 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1056 $sk =& $this->mOptions->getSkin();
1057
1058 $isRedirect = false ;
1059 if ( trim ( substr ( $s , 0 , 10 ) ) == '#REDIRECT' ) $isRedirect = true ;
1060 $a = explode( '[[', ' ' . $s );
1061 $s = array_shift( $a );
1062 $s = substr( $s, 1 );
1063
1064 # Match a link having the form [[namespace:link|alternate]]trail
1065 static $e1 = FALSE;
1066 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1067 # Match the end of a line for a word that's not followed by whitespace,
1068 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1069 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1070
1071 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
1072 # Special and Media are pseudo-namespaces; no pages actually exist in them
1073 static $image = FALSE;
1074 static $special = FALSE;
1075 static $media = FALSE;
1076 static $category = FALSE;
1077 if ( !$image ) { $image = Namespace::getImage(); }
1078 if ( !$special ) { $special = Namespace::getSpecial(); }
1079 if ( !$media ) { $media = Namespace::getMedia(); }
1080 if ( !$category ) { $category = Namespace::getCategory(); }
1081
1082 $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
1083
1084 if ( $useLinkPrefixExtension ) {
1085 if ( preg_match( $e2, $s, $m ) ) {
1086 $first_prefix = $m[2];
1087 $s = $m[1];
1088 } else {
1089 $first_prefix = false;
1090 }
1091 } else {
1092 $prefix = '';
1093 }
1094
1095 wfProfileOut( $fname.'-setup' );
1096
1097 foreach ( $a as $line ) {
1098 wfProfileIn( $fname.'-prefixhandling' );
1099 if ( $useLinkPrefixExtension ) {
1100 if ( preg_match( $e2, $s, $m ) ) {
1101 $prefix = $m[2];
1102 $s = $m[1];
1103 } else {
1104 $prefix='';
1105 }
1106 # first link
1107 if($first_prefix) {
1108 $prefix = $first_prefix;
1109 $first_prefix = false;
1110 }
1111 }
1112 wfProfileOut( $fname.'-prefixhandling' );
1113
1114 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1115 $text = $m[2];
1116 # fix up urlencoded title texts
1117 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1118 $trail = $m[3];
1119 } else { # Invalid form; output directly
1120 $s .= $prefix . '[[' . $line ;
1121 continue;
1122 }
1123
1124 /* Valid link forms:
1125 Foobar -- normal
1126 :Foobar -- override special treatment of prefix (images, language links)
1127 /Foobar -- convert to CurrentPage/Foobar
1128 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1129 */
1130 $c = substr($m[1],0,1);
1131 $noforce = ($c != ':');
1132 if( $c == '/' ) { # subpage
1133 if(substr($m[1],-1,1)=='/') { # / at end means we don't want the slash to be shown
1134 $m[1]=substr($m[1],1,strlen($m[1])-2);
1135 $noslash=$m[1];
1136 } else {
1137 $noslash=substr($m[1],1);
1138 }
1139 if(!empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()])) { # subpages allowed here
1140 $link = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1141 if( '' == $text ) {
1142 $text= $m[1];
1143 } # this might be changed for ugliness reasons
1144 } else {
1145 $link = $noslash; # no subpage allowed, use standard link
1146 }
1147 } elseif( $noforce ) { # no subpage
1148 $link = $m[1];
1149 } else {
1150 $link = substr( $m[1], 1 );
1151 }
1152 $wasblank = ( '' == $text );
1153 if( $wasblank )
1154 $text = $link;
1155
1156 $nt = Title::newFromText( $link );
1157 if( !$nt ) {
1158 $s .= $prefix . '[[' . $line;
1159 continue;
1160 }
1161 $ns = $nt->getNamespace();
1162 $iw = $nt->getInterWiki();
1163 if( $noforce ) {
1164 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1165 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1166 $tmp = $prefix . $trail ;
1167 $s .= (trim($tmp) == '')? '': $tmp;
1168 continue;
1169 }
1170 if ( $ns == $image ) {
1171 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1172 $wgLinkCache->addImageLinkObj( $nt );
1173 continue;
1174 }
1175 if ( $ns == $category && !$isRedirect ) {
1176 $t = $nt->getText() ;
1177 $nnt = Title::newFromText ( Namespace::getCanonicalName($category).":".$t ) ;
1178
1179 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1180 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1181 $wgLinkCache->resume();
1182
1183 $sortkey = $wasblank ? $this->mTitle->getPrefixedText() : $text;
1184 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1185 $this->mOutput->mCategoryLinks[] = $t ;
1186 $s .= $prefix . $trail ;
1187 continue;
1188 }
1189 }
1190 if( ( $nt->getPrefixedText() == $this->mTitle->getPrefixedText() ) &&
1191 ( strpos( $link, '#' ) == FALSE ) ) {
1192 # Self-links are handled specially; generally de-link and change to bold.
1193 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1194 continue;
1195 }
1196
1197 if( $ns == $media ) {
1198 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1199 $wgLinkCache->addImageLinkObj( $nt );
1200 continue;
1201 } elseif( $ns == $special ) {
1202 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1203 continue;
1204 }
1205 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1206 }
1207 wfProfileOut( $fname );
1208 return $s;
1209 }
1210
1211 # Some functions here used by doBlockLevels()
1212 #
1213 /* private */ function closeParagraph() {
1214 $result = '';
1215 if ( '' != $this->mLastSection ) {
1216 $result = '</' . $this->mLastSection . ">\n";
1217 }
1218 $this->mInPre = false;
1219 $this->mLastSection = '';
1220 return $result;
1221 }
1222 # getCommon() returns the length of the longest common substring
1223 # of both arguments, starting at the beginning of both.
1224 #
1225 /* private */ function getCommon( $st1, $st2 ) {
1226 $fl = strlen( $st1 );
1227 $shorter = strlen( $st2 );
1228 if ( $fl < $shorter ) { $shorter = $fl; }
1229
1230 for ( $i = 0; $i < $shorter; ++$i ) {
1231 if ( $st1{$i} != $st2{$i} ) { break; }
1232 }
1233 return $i;
1234 }
1235 # These next three functions open, continue, and close the list
1236 # element appropriate to the prefix character passed into them.
1237 #
1238 /* private */ function openList( $char )
1239 {
1240 $result = $this->closeParagraph();
1241
1242 if ( '*' == $char ) { $result .= '<ul><li>'; }
1243 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1244 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1245 else if ( ';' == $char ) {
1246 $result .= '<dl><dt>';
1247 $this->mDTopen = true;
1248 }
1249 else { $result = '<!-- ERR 1 -->'; }
1250
1251 return $result;
1252 }
1253
1254 /* private */ function nextItem( $char ) {
1255 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1256 else if ( ':' == $char || ';' == $char ) {
1257 $close = "</dd>";
1258 if ( $this->mDTopen ) { $close = '</dt>'; }
1259 if ( ';' == $char ) {
1260 $this->mDTopen = true;
1261 return $close . '<dt>';
1262 } else {
1263 $this->mDTopen = false;
1264 return $close . '<dd>';
1265 }
1266 }
1267 return '<!-- ERR 2 -->';
1268 }
1269
1270 /* private */function closeList( $char ) {
1271 if ( '*' == $char ) { $text = '</li></ul>'; }
1272 else if ( '#' == $char ) { $text = '</li></ol>'; }
1273 else if ( ':' == $char ) {
1274 if ( $this->mDTopen ) {
1275 $this->mDTopen = false;
1276 $text = '</dt></dl>';
1277 } else {
1278 $text = '</dd></dl>';
1279 }
1280 }
1281 else { return '<!-- ERR 3 -->'; }
1282 return $text."\n";
1283 }
1284
1285 /* private */ function doBlockLevels( $text, $linestart ) {
1286 $fname = 'Parser::doBlockLevels';
1287 wfProfileIn( $fname );
1288
1289 # Parsing through the text line by line. The main thing
1290 # happening here is handling of block-level elements p, pre,
1291 # and making lists from lines starting with * # : etc.
1292 #
1293 $textLines = explode( "\n", $text );
1294
1295 $lastPrefix = $output = $lastLine = '';
1296 $this->mDTopen = $inBlockElem = false;
1297 $prefixLength = 0;
1298 $paragraphStack = false;
1299
1300 if ( !$linestart ) {
1301 $output .= array_shift( $textLines );
1302 }
1303 foreach ( $textLines as $oLine ) {
1304 $lastPrefixLength = strlen( $lastPrefix );
1305 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1306 $preOpenMatch = preg_match("/<pre/i", $oLine );
1307 if ( !$this->mInPre ) {
1308 # Multiple prefixes may abut each other for nested lists.
1309 $prefixLength = strspn( $oLine, '*#:;' );
1310 $pref = substr( $oLine, 0, $prefixLength );
1311
1312 # eh?
1313 $pref2 = str_replace( ';', ':', $pref );
1314 $t = substr( $oLine, $prefixLength );
1315 $this->mInPre = !empty($preOpenMatch);
1316 } else {
1317 # Don't interpret any other prefixes in preformatted text
1318 $prefixLength = 0;
1319 $pref = $pref2 = '';
1320 $t = $oLine;
1321 }
1322
1323 # List generation
1324 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1325 # Same as the last item, so no need to deal with nesting or opening stuff
1326 $output .= $this->nextItem( substr( $pref, -1 ) );
1327 $paragraphStack = false;
1328
1329 if ( ";" == substr( $pref, -1 ) ) {
1330 # The one nasty exception: definition lists work like this:
1331 # ; title : definition text
1332 # So we check for : in the remainder text to split up the
1333 # title and definition, without b0rking links.
1334 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1335 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1336 $term = $match[1];
1337 $output .= $term . $this->nextItem( ':' );
1338 $t = $match[2];
1339 }
1340 }
1341 } elseif( $prefixLength || $lastPrefixLength ) {
1342 # Either open or close a level...
1343 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1344 $paragraphStack = false;
1345
1346 while( $commonPrefixLength < $lastPrefixLength ) {
1347 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1348 --$lastPrefixLength;
1349 }
1350 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1351 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1352 }
1353 while ( $prefixLength > $commonPrefixLength ) {
1354 $char = substr( $pref, $commonPrefixLength, 1 );
1355 $output .= $this->openList( $char );
1356
1357 if ( ';' == $char ) {
1358 # FIXME: This is dupe of code above
1359 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1360 $term = $match[1];
1361 $output .= $term . $this->nextItem( ":" );
1362 $t = $match[2];
1363 }
1364 }
1365 ++$commonPrefixLength;
1366 }
1367 $lastPrefix = $pref2;
1368 }
1369 if( 0 == $prefixLength ) {
1370 # No prefix (not in list)--go to paragraph mode
1371 $uniq_prefix = UNIQ_PREFIX;
1372 // XXX: use a stack for nestable elements like span, table and div
1373 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1374 $closematch = preg_match(
1375 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1376 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1377 if ( $openmatch or $closematch ) {
1378 $paragraphStack = false;
1379 $output .= $this->closeParagraph();
1380 if($preOpenMatch and !$preCloseMatch) {
1381 $this->mInPre = true;
1382 }
1383 if ( $closematch ) {
1384 $inBlockElem = false;
1385 } else {
1386 $inBlockElem = true;
1387 }
1388 } else if ( !$inBlockElem && !$this->mInPre ) {
1389 if ( " " == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1390 // pre
1391 if ($this->mLastSection != 'pre') {
1392 $paragraphStack = false;
1393 $output .= $this->closeParagraph().'<pre>';
1394 $this->mLastSection = 'pre';
1395 }
1396 } else {
1397 // paragraph
1398 if ( '' == trim($t) ) {
1399 if ( $paragraphStack ) {
1400 $output .= $paragraphStack.'<br />';
1401 $paragraphStack = false;
1402 $this->mLastSection = 'p';
1403 } else {
1404 if ($this->mLastSection != 'p' ) {
1405 $output .= $this->closeParagraph();
1406 $this->mLastSection = '';
1407 $paragraphStack = '<p>';
1408 } else {
1409 $paragraphStack = '</p><p>';
1410 }
1411 }
1412 } else {
1413 if ( $paragraphStack ) {
1414 $output .= $paragraphStack;
1415 $paragraphStack = false;
1416 $this->mLastSection = 'p';
1417 } else if ($this->mLastSection != 'p') {
1418 $output .= $this->closeParagraph().'<p>';
1419 $this->mLastSection = 'p';
1420 }
1421 }
1422 }
1423 }
1424 }
1425 if ($paragraphStack === false) {
1426 $output .= $t."\n";
1427 }
1428 }
1429 while ( $prefixLength ) {
1430 $output .= $this->closeList( $pref2{$prefixLength-1} );
1431 --$prefixLength;
1432 }
1433 if ( '' != $this->mLastSection ) {
1434 $output .= '</' . $this->mLastSection . '>';
1435 $this->mLastSection = '';
1436 }
1437
1438 wfProfileOut( $fname );
1439 return $output;
1440 }
1441
1442 # Return value of a magic variable (like PAGENAME)
1443 function getVariableValue( $index ) {
1444 global $wgLang, $wgSitename, $wgServer;
1445
1446 switch ( $index ) {
1447 case MAG_CURRENTMONTH:
1448 return $wgLang->formatNum( date( 'm' ) );
1449 case MAG_CURRENTMONTHNAME:
1450 return $wgLang->getMonthName( date('n') );
1451 case MAG_CURRENTMONTHNAMEGEN:
1452 return $wgLang->getMonthNameGen( date('n') );
1453 case MAG_CURRENTDAY:
1454 return $wgLang->formatNum( date('j') );
1455 case MAG_PAGENAME:
1456 return $this->mTitle->getText();
1457 case MAG_NAMESPACE:
1458 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1459 return $wgLang->getNsText($this->mTitle->getNamespace()); // Patch by Dori
1460 case MAG_CURRENTDAYNAME:
1461 return $wgLang->getWeekdayName( date('w')+1 );
1462 case MAG_CURRENTYEAR:
1463 return $wgLang->formatNum( date( 'Y' ) );
1464 case MAG_CURRENTTIME:
1465 return $wgLang->time( wfTimestampNow(), false );
1466 case MAG_NUMBEROFARTICLES:
1467 return $wgLang->formatNum( wfNumberOfArticles() );
1468 case MAG_SITENAME:
1469 return $wgSitename;
1470 case MAG_SERVER:
1471 return $wgServer;
1472 default:
1473 return NULL;
1474 }
1475 }
1476
1477 # initialise the magic variables (like CURRENTMONTHNAME)
1478 function initialiseVariables() {
1479 global $wgVariableIDs;
1480 $this->mVariables = array();
1481 foreach ( $wgVariableIDs as $id ) {
1482 $mw =& MagicWord::get( $id );
1483 $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
1484 }
1485 }
1486
1487 /* private */ function replaceVariables( $text, $args = array() ) {
1488 global $wgLang, $wgScript, $wgArticlePath;
1489
1490 # Prevent too big inclusions
1491 if(strlen($text)> MAX_INCLUDE_SIZE)
1492 return $text;
1493
1494 $fname = 'Parser::replaceVariables';
1495 wfProfileIn( $fname );
1496
1497 $bail = false;
1498 $titleChars = Title::legalChars();
1499 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1500
1501 # This function is called recursively. To keep track of arguments we need a stack:
1502 array_push( $this->mArgStack, $args );
1503
1504 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1505 $GLOBALS['wgCurParser'] =& $this;
1506
1507
1508 if ( $this->mOutputType == OT_HTML ) {
1509 # Variable substitution
1510 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1511
1512 # Argument substitution
1513 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1514 }
1515 # Template substitution
1516 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1517 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1518
1519 array_pop( $this->mArgStack );
1520
1521 wfProfileOut( $fname );
1522 return $text;
1523 }
1524
1525 function variableSubstitution( $matches ) {
1526 if ( !$this->mVariables ) {
1527 $this->initialiseVariables();
1528 }
1529 if ( array_key_exists( $matches[1], $this->mVariables ) ) {
1530 $text = $this->mVariables[$matches[1]];
1531 $this->mOutput->mContainsOldMagic = true;
1532 } else {
1533 $text = $matches[0];
1534 }
1535 return $text;
1536 }
1537
1538 # Split template arguments
1539 function getTemplateArgs( $argsString ) {
1540 if ( $argsString === '' ) {
1541 return array();
1542 }
1543
1544 $args = explode( '|', substr( $argsString, 1 ) );
1545
1546 # If any of the arguments contains a '[[' but no ']]', it needs to be
1547 # merged with the next arg because the '|' character between belongs
1548 # to the link syntax and not the template parameter syntax.
1549 $argc = count($args);
1550 $i = 0;
1551 for ( $i = 0; $i < $argc-1; $i++ ) {
1552 if ( substr_count ( $args[$i], "[[" ) != substr_count ( $args[$i], "]]" ) ) {
1553 $args[$i] .= "|".$args[$i+1];
1554 array_splice($args, $i+1, 1);
1555 $i--;
1556 $argc--;
1557 }
1558 }
1559
1560 return $args;
1561 }
1562
1563 function braceSubstitution( $matches ) {
1564 global $wgLinkCache, $wgLang;
1565 $fname = 'Parser::braceSubstitution';
1566 $found = false;
1567 $nowiki = false;
1568 $noparse = false;
1569
1570 $title = NULL;
1571
1572 # $newline is an optional newline character before the braces
1573 # $part1 is the bit before the first |, and must contain only title characters
1574 # $args is a list of arguments, starting from index 0, not including $part1
1575
1576 $newline = $matches[1];
1577 $part1 = $matches[2];
1578 # If the third subpattern matched anything, it will start with |
1579
1580 $args = $this->getTemplateArgs($matches[3]);
1581 $argc = count( $args );
1582
1583 # {{{}}}
1584 if ( strpos( $matches[0], '{{{' ) !== false ) {
1585 $text = $matches[0];
1586 $found = true;
1587 $noparse = true;
1588 }
1589
1590 # SUBST
1591 if ( !$found ) {
1592 $mwSubst =& MagicWord::get( MAG_SUBST );
1593 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1594 if ( $this->mOutputType != OT_WIKI ) {
1595 # Invalid SUBST not replaced at PST time
1596 # Return without further processing
1597 $text = $matches[0];
1598 $found = true;
1599 $noparse= true;
1600 }
1601 } elseif ( $this->mOutputType == OT_WIKI ) {
1602 # SUBST not found in PST pass, do nothing
1603 $text = $matches[0];
1604 $found = true;
1605 }
1606 }
1607
1608 # MSG, MSGNW and INT
1609 if ( !$found ) {
1610 # Check for MSGNW:
1611 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1612 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1613 $nowiki = true;
1614 } else {
1615 # Remove obsolete MSG:
1616 $mwMsg =& MagicWord::get( MAG_MSG );
1617 $mwMsg->matchStartAndRemove( $part1 );
1618 }
1619
1620 # Check if it is an internal message
1621 $mwInt =& MagicWord::get( MAG_INT );
1622 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1623 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1624 $text = wfMsgReal( $part1, $args, true );
1625 $found = true;
1626 }
1627 }
1628 }
1629
1630 # NS
1631 if ( !$found ) {
1632 # Check for NS: (namespace expansion)
1633 $mwNs = MagicWord::get( MAG_NS );
1634 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1635 if ( intval( $part1 ) ) {
1636 $text = $wgLang->getNsText( intval( $part1 ) );
1637 $found = true;
1638 } else {
1639 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1640 if ( !is_null( $index ) ) {
1641 $text = $wgLang->getNsText( $index );
1642 $found = true;
1643 }
1644 }
1645 }
1646 }
1647
1648 # LOCALURL and LOCALURLE
1649 if ( !$found ) {
1650 $mwLocal = MagicWord::get( MAG_LOCALURL );
1651 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1652
1653 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1654 $func = 'getLocalURL';
1655 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1656 $func = 'escapeLocalURL';
1657 } else {
1658 $func = '';
1659 }
1660
1661 if ( $func !== '' ) {
1662 $title = Title::newFromText( $part1 );
1663 if ( !is_null( $title ) ) {
1664 if ( $argc > 0 ) {
1665 $text = $title->$func( $args[0] );
1666 } else {
1667 $text = $title->$func();
1668 }
1669 $found = true;
1670 }
1671 }
1672 }
1673
1674 # Internal variables
1675 if ( !$this->mVariables ) {
1676 $this->initialiseVariables();
1677 }
1678 if ( !$found && array_key_exists( $part1, $this->mVariables ) ) {
1679 $text = $this->mVariables[$part1];
1680 $found = true;
1681 $this->mOutput->mContainsOldMagic = true;
1682 }
1683
1684 # Template table test
1685
1686 # Did we encounter this template already? If yes, it is in the cache
1687 # and we need to check for loops.
1688 if ( isset( $this->mTemplates[$part1] ) ) {
1689 # Infinite loop test
1690 if ( isset( $this->mTemplatePath[$part1] ) ) {
1691 $noparse = true;
1692 $found = true;
1693 }
1694 # set $text to cached message.
1695 $text = $this->mTemplates[$part1];
1696 $found = true;
1697 }
1698
1699 # Load from database
1700 if ( !$found ) {
1701 $title = Title::newFromText( $part1, NS_TEMPLATE );
1702 if ( !is_null( $title ) && !$title->isExternal() ) {
1703 # Check for excessive inclusion
1704 $dbk = $title->getPrefixedDBkey();
1705 if ( $this->incrementIncludeCount( $dbk ) ) {
1706 # This should never be reached.
1707 $article = new Article( $title );
1708 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1709 if ( $articleContent !== false ) {
1710 $found = true;
1711 $text = $articleContent;
1712
1713 }
1714 }
1715
1716 # If the title is valid but undisplayable, make a link to it
1717 if ( $this->mOutputType == OT_HTML && !$found ) {
1718 $text = '[[' . $title->getPrefixedText() . ']]';
1719 $found = true;
1720 }
1721
1722 # Template cache array insertion
1723 $this->mTemplates[$part1] = $text;
1724 }
1725 }
1726
1727 # Recursive parsing, escaping and link table handling
1728 # Only for HTML output
1729 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
1730 $text = wfEscapeWikiText( $text );
1731 } elseif ( $this->mOutputType == OT_HTML && $found && !$noparse) {
1732 # Clean up argument array
1733 $assocArgs = array();
1734 $index = 1;
1735 foreach( $args as $arg ) {
1736 $eqpos = strpos( $arg, '=' );
1737 if ( $eqpos === false ) {
1738 $assocArgs[$index++] = $arg;
1739 } else {
1740 $name = trim( substr( $arg, 0, $eqpos ) );
1741 $value = trim( substr( $arg, $eqpos+1 ) );
1742 if ( $value === false ) {
1743 $value = '';
1744 }
1745 if ( $name !== false ) {
1746 $assocArgs[$name] = $value;
1747 }
1748 }
1749 }
1750
1751 # Do not enter included links in link table
1752 if ( !is_null( $title ) ) {
1753 $wgLinkCache->suspend();
1754 }
1755
1756 # Add a new element to the templace recursion path
1757 $this->mTemplatePath[$part1] = 1;
1758
1759 # Run full parser on the included text
1760 $text = $this->stripParse( $text, $newline, $assocArgs );
1761
1762 # Resume the link cache and register the inclusion as a link
1763 if ( !is_null( $title ) ) {
1764 $wgLinkCache->resume();
1765 $wgLinkCache->addLinkObj( $title );
1766 }
1767 }
1768 # Empties the template path
1769 $this->mTemplatePath = array();
1770
1771 if ( !$found ) {
1772 return $matches[0];
1773 } else {
1774 return $text;
1775 }
1776 }
1777
1778 # Triple brace replacement -- used for template arguments
1779 function argSubstitution( $matches ) {
1780 $newline = $matches[1];
1781 $arg = trim( $matches[2] );
1782 $text = $matches[0];
1783 $inputArgs = end( $this->mArgStack );
1784
1785 if ( array_key_exists( $arg, $inputArgs ) ) {
1786 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1787 }
1788
1789 return $text;
1790 }
1791
1792 # Returns true if the function is allowed to include this entity
1793 function incrementIncludeCount( $dbk ) {
1794 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
1795 $this->mIncludeCount[$dbk] = 0;
1796 }
1797 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
1798 return true;
1799 } else {
1800 return false;
1801 }
1802 }
1803
1804
1805 # Cleans up HTML, removes dangerous tags and attributes
1806 /* private */ function removeHTMLtags( $text ) {
1807 global $wgUseTidy, $wgUserHtml;
1808 $fname = 'Parser::removeHTMLtags';
1809 wfProfileIn( $fname );
1810
1811 if( $wgUserHtml ) {
1812 $htmlpairs = array( # Tags that must be closed
1813 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1814 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1815 'strike', 'strong', 'tt', 'var', 'div', 'center',
1816 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1817 'ruby', 'rt' , 'rb' , 'rp', 'p'
1818 );
1819 $htmlsingle = array(
1820 'br', 'hr', 'li', 'dt', 'dd'
1821 );
1822 $htmlnest = array( # Tags that can be nested--??
1823 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1824 'dl', 'font', 'big', 'small', 'sub', 'sup'
1825 );
1826 $tabletags = array( # Can only appear inside table
1827 'td', 'th', 'tr'
1828 );
1829 } else {
1830 $htmlpairs = array();
1831 $htmlsingle = array();
1832 $htmlnest = array();
1833 $tabletags = array();
1834 }
1835
1836 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1837 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1838
1839 $htmlattrs = $this->getHTMLattrs () ;
1840
1841 # Remove HTML comments
1842 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
1843
1844 $bits = explode( '<', $text );
1845 $text = array_shift( $bits );
1846 if(!$wgUseTidy) {
1847 $tagstack = array(); $tablestack = array();
1848 foreach ( $bits as $x ) {
1849 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1850 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1851 $x, $regs );
1852 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1853 error_reporting( $prev );
1854
1855 $badtag = 0 ;
1856 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1857 # Check our stack
1858 if ( $slash ) {
1859 # Closing a tag...
1860 if ( ! in_array( $t, $htmlsingle ) &&
1861 ( $ot = @array_pop( $tagstack ) ) != $t ) {
1862 @array_push( $tagstack, $ot );
1863 $badtag = 1;
1864 } else {
1865 if ( $t == 'table' ) {
1866 $tagstack = array_pop( $tablestack );
1867 }
1868 $newparams = '';
1869 }
1870 } else {
1871 # Keep track for later
1872 if ( in_array( $t, $tabletags ) &&
1873 ! in_array( 'table', $tagstack ) ) {
1874 $badtag = 1;
1875 } else if ( in_array( $t, $tagstack ) &&
1876 ! in_array ( $t , $htmlnest ) ) {
1877 $badtag = 1 ;
1878 } else if ( ! in_array( $t, $htmlsingle ) ) {
1879 if ( $t == 'table' ) {
1880 array_push( $tablestack, $tagstack );
1881 $tagstack = array();
1882 }
1883 array_push( $tagstack, $t );
1884 }
1885 # Strip non-approved attributes from the tag
1886 $newparams = $this->fixTagAttributes($params);
1887
1888 }
1889 if ( ! $badtag ) {
1890 $rest = str_replace( '>', '&gt;', $rest );
1891 $text .= "<$slash$t $newparams$brace$rest";
1892 continue;
1893 }
1894 }
1895 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
1896 }
1897 # Close off any remaining tags
1898 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
1899 $text .= "</$t>\n";
1900 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
1901 }
1902 } else {
1903 # this might be possible using tidy itself
1904 foreach ( $bits as $x ) {
1905 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1906 $x, $regs );
1907 @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1908 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1909 $newparams = $this->fixTagAttributes($params);
1910 $rest = str_replace( '>', '&gt;', $rest );
1911 $text .= "<$slash$t $newparams$brace$rest";
1912 } else {
1913 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
1914 }
1915 }
1916 }
1917 wfProfileOut( $fname );
1918 return $text;
1919 }
1920
1921
1922 /*
1923 *
1924 * This function accomplishes several tasks:
1925 * 1) Auto-number headings if that option is enabled
1926 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1927 * 3) Add a Table of contents on the top for users who have enabled the option
1928 * 4) Auto-anchor headings
1929 *
1930 * It loops through all headlines, collects the necessary data, then splits up the
1931 * string and re-inserts the newly formatted headlines.
1932 *
1933 */
1934
1935 /* private */ function formatHeadings( $text, $isMain=true ) {
1936 global $wgInputEncoding, $wgMaxTocLevel;
1937
1938 $doNumberHeadings = $this->mOptions->getNumberHeadings();
1939 $doShowToc = $this->mOptions->getShowToc();
1940 $forceTocHere = false;
1941 if( !$this->mTitle->userCanEdit() ) {
1942 $showEditLink = 0;
1943 $rightClickHack = 0;
1944 } else {
1945 $showEditLink = $this->mOptions->getEditSection();
1946 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
1947 }
1948
1949 # Inhibit editsection links if requested in the page
1950 $esw =& MagicWord::get( MAG_NOEDITSECTION );
1951 if( $esw->matchAndRemove( $text ) ) {
1952 $showEditLink = 0;
1953 }
1954 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1955 # do not add TOC
1956 $mw =& MagicWord::get( MAG_NOTOC );
1957 if( $mw->matchAndRemove( $text ) ) {
1958 $doShowToc = 0;
1959 }
1960
1961 # never add the TOC to the Main Page. This is an entry page that should not
1962 # be more than 1-2 screens large anyway
1963 if( $this->mTitle->getPrefixedText() == wfMsg('mainpage') ) {
1964 $doShowToc = 0;
1965 }
1966
1967 # Get all headlines for numbering them and adding funky stuff like [edit]
1968 # links - this is for later, but we need the number of headlines right now
1969 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
1970
1971 # if there are fewer than 4 headlines in the article, do not show TOC
1972 if( $numMatches < 4 ) {
1973 $doShowToc = 0;
1974 }
1975
1976 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
1977 # override above conditions and always show TOC at that place
1978 $mw =& MagicWord::get( MAG_TOC );
1979 if ($mw->match( $text ) ) {
1980 $doShowToc = 1;
1981 $forceTocHere = true;
1982 } else {
1983 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1984 # override above conditions and always show TOC above first header
1985 $mw =& MagicWord::get( MAG_FORCETOC );
1986 if ($mw->matchAndRemove( $text ) ) {
1987 $doShowToc = 1;
1988 }
1989 }
1990
1991
1992
1993 # We need this to perform operations on the HTML
1994 $sk =& $this->mOptions->getSkin();
1995
1996 # headline counter
1997 $headlineCount = 0;
1998
1999 # Ugh .. the TOC should have neat indentation levels which can be
2000 # passed to the skin functions. These are determined here
2001 $toclevel = 0;
2002 $toc = '';
2003 $full = '';
2004 $head = array();
2005 $sublevelCount = array();
2006 $level = 0;
2007 $prevlevel = 0;
2008 foreach( $matches[3] as $headline ) {
2009 $numbering = '';
2010 if( $level ) {
2011 $prevlevel = $level;
2012 }
2013 $level = $matches[1][$headlineCount];
2014 if( ( $doNumberHeadings || $doShowToc ) && $prevlevel && $level > $prevlevel ) {
2015 # reset when we enter a new level
2016 $sublevelCount[$level] = 0;
2017 $toc .= $sk->tocIndent( $level - $prevlevel );
2018 $toclevel += $level - $prevlevel;
2019 }
2020 if( ( $doNumberHeadings || $doShowToc ) && $level < $prevlevel ) {
2021 # reset when we step back a level
2022 $sublevelCount[$level+1]=0;
2023 $toc .= $sk->tocUnindent( $prevlevel - $level );
2024 $toclevel -= $prevlevel - $level;
2025 }
2026 # count number of headlines for each level
2027 @$sublevelCount[$level]++;
2028 if( $doNumberHeadings || $doShowToc ) {
2029 $dot = 0;
2030 for( $i = 1; $i <= $level; $i++ ) {
2031 if( !empty( $sublevelCount[$i] ) ) {
2032 if( $dot ) {
2033 $numbering .= '.';
2034 }
2035 $numbering .= $sublevelCount[$i];
2036 $dot = 1;
2037 }
2038 }
2039 }
2040
2041 # The canonized header is a version of the header text safe to use for links
2042 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2043 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2044 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState );
2045
2046 # strip out HTML
2047 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2048 $tocline = trim( $canonized_headline );
2049 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
2050 $replacearray = array(
2051 '%3A' => ':',
2052 '%' => '.'
2053 );
2054 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2055 $refer[$headlineCount] = $canonized_headline;
2056
2057 # count how many in assoc. array so we can track dupes in anchors
2058 @$refers[$canonized_headline]++;
2059 $refcount[$headlineCount]=$refers[$canonized_headline];
2060
2061 # Prepend the number to the heading text
2062
2063 if( $doNumberHeadings || $doShowToc ) {
2064 $tocline = $numbering . ' ' . $tocline;
2065
2066 # Don't number the heading if it is the only one (looks silly)
2067 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2068 # the two are different if the line contains a link
2069 $headline=$numbering . ' ' . $headline;
2070 }
2071 }
2072
2073 # Create the anchor for linking from the TOC to the section
2074 $anchor = $canonized_headline;
2075 if($refcount[$headlineCount] > 1 ) {
2076 $anchor .= '_' . $refcount[$headlineCount];
2077 }
2078 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2079 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2080 }
2081 if( $showEditLink ) {
2082 if ( empty( $head[$headlineCount] ) ) {
2083 $head[$headlineCount] = '';
2084 }
2085 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+1);
2086 }
2087
2088 # Add the edit section span
2089 if( $rightClickHack ) {
2090 $headline = $sk->editSectionScript($headlineCount+1,$headline);
2091 }
2092
2093 # give headline the correct <h#> tag
2094 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
2095
2096 $headlineCount++;
2097 }
2098
2099 if( $doShowToc ) {
2100 $toclines = $headlineCount;
2101 $toc .= $sk->tocUnindent( $toclevel );
2102 $toc = $sk->tocTable( $toc );
2103 }
2104
2105 # split up and insert constructed headlines
2106
2107 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2108 $i = 0;
2109
2110 foreach( $blocks as $block ) {
2111 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2112 # This is the [edit] link that appears for the top block of text when
2113 # section editing is enabled
2114
2115 # Disabled because it broke block formatting
2116 # For example, a bullet point in the top line
2117 # $full .= $sk->editSectionLink(0);
2118 }
2119 $full .= $block;
2120 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2121 # Top anchor now in skin
2122 $full = $full.$toc;
2123 }
2124
2125 if( !empty( $head[$i] ) ) {
2126 $full .= $head[$i];
2127 }
2128 $i++;
2129 }
2130 if($forceTocHere) {
2131 $mw =& MagicWord::get( MAG_TOC );
2132 return $mw->replace( $toc, $full );
2133 } else {
2134 return $full;
2135 }
2136 }
2137
2138 # Return an HTML link for the "ISBN 123456" text
2139 /* private */ function magicISBN( $text ) {
2140 global $wgLang;
2141 $fname = 'Parser::magicISBN';
2142 wfProfileIn( $fname );
2143
2144 $a = split( 'ISBN ', " $text" );
2145 if ( count ( $a ) < 2 ) {
2146 wfProfileOut( $fname );
2147 return $text;
2148 }
2149 $text = substr( array_shift( $a ), 1);
2150 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2151
2152 foreach ( $a as $x ) {
2153 $isbn = $blank = '' ;
2154 while ( ' ' == $x{0} ) {
2155 $blank .= ' ';
2156 $x = substr( $x, 1 );
2157 }
2158 while ( strstr( $valid, $x{0} ) != false ) {
2159 $isbn .= $x{0};
2160 $x = substr( $x, 1 );
2161 }
2162 $num = str_replace( '-', '', $isbn );
2163 $num = str_replace( ' ', '', $num );
2164
2165 if ( '' == $num ) {
2166 $text .= "ISBN $blank$x";
2167 } else {
2168 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2169 $text .= '<a href="' .
2170 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
2171 "\" class=\"internal\">ISBN $isbn</a>";
2172 $text .= $x;
2173 }
2174 }
2175 wfProfileOut( $fname );
2176 return $text;
2177 }
2178
2179 # Return an HTML link for the "GEO ..." text
2180 /* private */ function magicGEO( $text ) {
2181 global $wgLang, $wgUseGeoMode;
2182 if ( !isset ( $wgUseGeoMode ) || !$wgUseGeoMode ) return $text ;
2183 $fname = 'Parser::magicGEO';
2184 wfProfileIn( $fname );
2185
2186 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2187 $directions = array ( "N" => "North" , "S" => "South" , "E" => "East" , "W" => "West" ) ;
2188 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2189 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2190 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2191 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2192
2193 $a = split( 'GEO ', " $text" );
2194 if ( count ( $a ) < 2 ) {
2195 wfProfileOut( $fname );
2196 return $text;
2197 }
2198 $text = substr( array_shift( $a ), 1);
2199 $valid = '0123456789.+-:';
2200
2201 foreach ( $a as $x ) {
2202 $geo = $blank = '' ;
2203 while ( ' ' == $x{0} ) {
2204 $blank .= ' ';
2205 $x = substr( $x, 1 );
2206 }
2207 while ( strstr( $valid, $x{0} ) != false ) {
2208 $geo .= $x{0};
2209 $x = substr( $x, 1 );
2210 }
2211 $num = str_replace( '+', '', $geo );
2212 $num = str_replace( ' ', '', $num );
2213
2214 if ( '' == $num || count ( explode ( ":" , $num , 3 ) ) < 2 ) {
2215 $text .= "GEO $blank$x";
2216 } else {
2217 $titleObj = Title::makeTitle( NS_SPECIAL, 'Geo' );
2218 $text .= '<a href="' .
2219 $titleObj->escapeLocalUrl( "coordinates={$num}" ) .
2220 "\" class=\"internal\">GEO $geo</a>";
2221 $text .= $x;
2222 }
2223 }
2224 wfProfileOut( $fname );
2225 return $text;
2226 }
2227
2228 # Return an HTML link for the "RFC 1234" text
2229 /* private */ function magicRFC( $text ) {
2230 global $wgLang;
2231
2232 $a = split( 'RFC ', ' '.$text );
2233 if ( count ( $a ) < 2 ) return $text;
2234 $text = substr( array_shift( $a ), 1);
2235 $valid = '0123456789';
2236
2237 foreach ( $a as $x ) {
2238 $rfc = $blank = '' ;
2239 while ( ' ' == $x{0} ) {
2240 $blank .= ' ';
2241 $x = substr( $x, 1 );
2242 }
2243 while ( strstr( $valid, $x{0} ) != false ) {
2244 $rfc .= $x{0};
2245 $x = substr( $x, 1 );
2246 }
2247
2248 if ( '' == $rfc ) {
2249 $text .= "RFC $blank$x";
2250 } else {
2251 $url = wfmsg( 'rfcurl' );
2252 $url = str_replace( '$1', $rfc, $url);
2253 $sk =& $this->mOptions->getSkin();
2254 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
2255 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2256 }
2257 }
2258 return $text;
2259 }
2260
2261 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2262 $this->mOptions = $options;
2263 $this->mTitle =& $title;
2264 $this->mOutputType = OT_WIKI;
2265
2266 if ( $clearState ) {
2267 $this->clearState();
2268 }
2269
2270 $stripState = false;
2271 $pairs = array(
2272 "\r\n" => "\n",
2273 );
2274 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2275 // now with regexes
2276 /*
2277 $pairs = array(
2278 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2279 "/<br *?>/i" => "<br />",
2280 );
2281 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2282 */
2283 $text = $this->strip( $text, $stripState, false );
2284 $text = $this->pstPass2( $text, $user );
2285 $text = $this->unstrip( $text, $stripState );
2286 $text = $this->unstripNoWiki( $text, $stripState );
2287 return $text;
2288 }
2289
2290 /* private */ function pstPass2( $text, &$user ) {
2291 global $wgLang, $wgLocaltimezone, $wgCurParser;
2292
2293 # Variable replacement
2294 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2295 $text = $this->replaceVariables( $text );
2296
2297 # Signatures
2298 #
2299 $n = $user->getName();
2300 $k = $user->getOption( 'nickname' );
2301 if ( '' == $k ) { $k = $n; }
2302 if(isset($wgLocaltimezone)) {
2303 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2304 }
2305 /* Note: this is an ugly timezone hack for the European wikis */
2306 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2307 ' (' . date( 'T' ) . ')';
2308 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2309
2310 $text = preg_replace( '/~~~~~/', $d, $text );
2311 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText(
2312 Namespace::getUser() ) . ":$n|$k]] $d", $text );
2313 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText(
2314 Namespace::getUser() ) . ":$n|$k]]", $text );
2315
2316 # Context links: [[|name]] and [[name (context)|]]
2317 #
2318 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2319 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2320 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2321 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2322
2323 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2324 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2325 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2326 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2327 # [[ns:page (cont)|]]
2328 $context = "";
2329 $t = $this->mTitle->getText();
2330 if ( preg_match( $conpat, $t, $m ) ) {
2331 $context = $m[2];
2332 }
2333 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2334 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2335 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2336
2337 if ( '' == $context ) {
2338 $text = preg_replace( $p2, '[[\\1]]', $text );
2339 } else {
2340 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2341 }
2342
2343 /*
2344 $mw =& MagicWord::get( MAG_SUBST );
2345 $wgCurParser = $this->fork();
2346 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2347 $this->merge( $wgCurParser );
2348 */
2349
2350 # Trim trailing whitespace
2351 # MAG_END (__END__) tag allows for trailing
2352 # whitespace to be deliberately included
2353 $text = rtrim( $text );
2354 $mw =& MagicWord::get( MAG_END );
2355 $mw->matchAndRemove( $text );
2356
2357 return $text;
2358 }
2359
2360 # Set up some variables which are usually set up in parse()
2361 # so that an external function can call some class members with confidence
2362 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2363 $this->mTitle =& $title;
2364 $this->mOptions = $options;
2365 $this->mOutputType = $outputType;
2366 if ( $clearState ) {
2367 $this->clearState();
2368 }
2369 }
2370
2371 function transformMsg( $text, $options ) {
2372 global $wgTitle;
2373 static $executing = false;
2374
2375 # Guard against infinite recursion
2376 if ( $executing ) {
2377 return $text;
2378 }
2379 $executing = true;
2380
2381 $this->mTitle = $wgTitle;
2382 $this->mOptions = $options;
2383 $this->mOutputType = OT_MSG;
2384 $this->clearState();
2385 $text = $this->replaceVariables( $text );
2386
2387 $executing = false;
2388 return $text;
2389 }
2390
2391 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2392 # Callback will be called with the text within
2393 # Transform and return the text within
2394 function setHook( $tag, $callback ) {
2395 $oldVal = @$this->mTagHooks[$tag];
2396 $this->mTagHooks[$tag] = $callback;
2397 return $oldVal;
2398 }
2399 }
2400
2401 class ParserOutput
2402 {
2403 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2404 var $mCacheTime; # Used in ParserCache
2405
2406 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2407 $containsOldMagic = false )
2408 {
2409 $this->mText = $text;
2410 $this->mLanguageLinks = $languageLinks;
2411 $this->mCategoryLinks = $categoryLinks;
2412 $this->mContainsOldMagic = $containsOldMagic;
2413 $this->mCacheTime = "";
2414 }
2415
2416 function getText() { return $this->mText; }
2417 function getLanguageLinks() { return $this->mLanguageLinks; }
2418 function getCategoryLinks() { return $this->mCategoryLinks; }
2419 function getCacheTime() { return $this->mCacheTime; }
2420 function containsOldMagic() { return $this->mContainsOldMagic; }
2421 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2422 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2423 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2424 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2425 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2426
2427 function merge( $other ) {
2428 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2429 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2430 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2431 }
2432
2433 }
2434
2435 class ParserOptions
2436 {
2437 # All variables are private
2438 var $mUseTeX; # Use texvc to expand <math> tags
2439 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2440 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2441 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2442 var $mAllowExternalImages; # Allow external images inline
2443 var $mSkin; # Reference to the preferred skin
2444 var $mDateFormat; # Date format index
2445 var $mEditSection; # Create "edit section" links
2446 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2447 var $mNumberHeadings; # Automatically number headings
2448 var $mShowToc; # Show table of contents
2449
2450 function getUseTeX() { return $this->mUseTeX; }
2451 function getUseCategoryMagic() { return $this->mUseCategoryMagic; }
2452 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2453 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2454 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2455 function getSkin() { return $this->mSkin; }
2456 function getDateFormat() { return $this->mDateFormat; }
2457 function getEditSection() { return $this->mEditSection; }
2458 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
2459 function getNumberHeadings() { return $this->mNumberHeadings; }
2460 function getShowToc() { return $this->mShowToc; }
2461
2462 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
2463 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic, $x ); }
2464 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
2465 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
2466 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
2467 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
2468 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
2469 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
2470 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
2471 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
2472
2473 function setSkin( &$x ) { $this->mSkin =& $x; }
2474
2475 /* static */ function newFromUser( &$user ) {
2476 $popts = new ParserOptions;
2477 $popts->initialiseFromUser( $user );
2478 return $popts;
2479 }
2480
2481 function initialiseFromUser( &$userInput ) {
2482 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2483
2484 if ( !$userInput ) {
2485 $user = new User;
2486 $user->setLoaded( true );
2487 } else {
2488 $user =& $userInput;
2489 }
2490
2491 $this->mUseTeX = $wgUseTeX;
2492 $this->mUseCategoryMagic = $wgUseCategoryMagic;
2493 $this->mUseDynamicDates = $wgUseDynamicDates;
2494 $this->mInterwikiMagic = $wgInterwikiMagic;
2495 $this->mAllowExternalImages = $wgAllowExternalImages;
2496 $this->mSkin =& $user->getSkin();
2497 $this->mDateFormat = $user->getOption( 'date' );
2498 $this->mEditSection = $user->getOption( 'editsection' );
2499 $this->mEditSectionOnRightClick = $user->getOption( 'editsectiononrightclick' );
2500 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
2501 $this->mShowToc = $user->getOption( 'showtoc' );
2502 }
2503
2504
2505 }
2506
2507 # Regex callbacks, used in Parser::replaceVariables
2508 function wfBraceSubstitution( $matches )
2509 {
2510 global $wgCurParser;
2511 return $wgCurParser->braceSubstitution( $matches );
2512 }
2513
2514 function wfArgSubstitution( $matches )
2515 {
2516 global $wgCurParser;
2517 return $wgCurParser->argSubstitution( $matches );
2518 }
2519
2520 function wfVariableSubstitution( $matches )
2521 {
2522 global $wgCurParser;
2523 return $wgCurParser->variableSubstitution( $matches );
2524 }
2525
2526 ?>