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