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