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