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