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