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