870ed18e62a612b363707820142dab4b72a6ae4c
[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, $wgWhitelistEdit;
244 if( $wgRawHtml && $wgWhitelistEdit ) {
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 == 'i')
765 { $output .= '</i>'; $state = ''; }
766 else if ($state == 'bi')
767 { $output .= '</i>'; $state = 'b'; }
768 else if ($state == 'ib')
769 { $output .= '</b></i><b>'; $state = 'b'; }
770 else if ($state == 'both')
771 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
772 else # $state can be 'b' or ''
773 { $output .= '<i>'; $state .= 'i'; }
774 }
775 else if (strlen ($r) == 3)
776 {
777 if ($state == 'b')
778 { $output .= '</b>'; $state = ''; }
779 else if ($state == 'bi')
780 { $output .= '</i></b><i>'; $state = 'i'; }
781 else if ($state == 'ib')
782 { $output .= '</b>'; $state = 'i'; }
783 else if ($state == 'both')
784 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
785 else # $state can be 'i' or ''
786 { $output .= '<b>'; $state .= 'b'; }
787 }
788 else if (strlen ($r) == 5)
789 {
790 if ($state == 'b')
791 { $output .= '</b><i>'; $state = 'i'; }
792 else if ($state == 'i')
793 { $output .= '</i><b>'; $state = 'b'; }
794 else if ($state == 'bi')
795 { $output .= '</i></b>'; $state = ''; }
796 else if ($state == 'ib')
797 { $output .= '</b></i>'; $state = ''; }
798 else if ($state == 'both')
799 { $output .= '<i><b>'.$buffer.'</b></i>'; $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 == 'b' || $state == 'ib')
808 $output .= '</b>';
809 if ($state == 'i' || $state == 'bi' || $state == 'ib')
810 $output .= '</i>';
811 if ($state == 'bi')
812 $output .= '</b>';
813 if ($state == 'both')
814 $output .= '<b><i>'.$buffer.'</i></b>';
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 if ( $wasblank ) {
1109 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1110 $sortkey = $this->mTitle->getText();
1111 } else {
1112 $sortkey = $this->mTitle->getPrefixedText();
1113 }
1114 } else {
1115 $sortkey = $text;
1116 }
1117 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1118 $this->mOutput->mCategoryLinks[] = $t ;
1119 $s .= $prefix . $trail ;
1120 continue;
1121 }
1122 }
1123
1124 if( ( $nt->getPrefixedText() === $this->mTitle->getPrefixedText() ) &&
1125 ( strpos( $link, '#' ) === FALSE ) ) {
1126 # Self-links are handled specially; generally de-link and change to bold.
1127 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1128 continue;
1129 }
1130
1131 if( $ns == NS_MEDIA ) {
1132 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1133 $wgLinkCache->addImageLinkObj( $nt );
1134 continue;
1135 } elseif( $ns == NS_SPECIAL ) {
1136 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1137 continue;
1138 }
1139 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1140 }
1141 wfProfileOut( $fname );
1142 return $s;
1143 }
1144
1145 # Some functions here used by doBlockLevels()
1146 #
1147 /* private */ function closeParagraph() {
1148 $result = '';
1149 if ( '' != $this->mLastSection ) {
1150 $result = '</' . $this->mLastSection . ">\n";
1151 }
1152 $this->mInPre = false;
1153 $this->mLastSection = '';
1154 return $result;
1155 }
1156 # getCommon() returns the length of the longest common substring
1157 # of both arguments, starting at the beginning of both.
1158 #
1159 /* private */ function getCommon( $st1, $st2 ) {
1160 $fl = strlen( $st1 );
1161 $shorter = strlen( $st2 );
1162 if ( $fl < $shorter ) { $shorter = $fl; }
1163
1164 for ( $i = 0; $i < $shorter; ++$i ) {
1165 if ( $st1{$i} != $st2{$i} ) { break; }
1166 }
1167 return $i;
1168 }
1169 # These next three functions open, continue, and close the list
1170 # element appropriate to the prefix character passed into them.
1171 #
1172 /* private */ function openList( $char ) {
1173 $result = $this->closeParagraph();
1174
1175 if ( '*' == $char ) { $result .= '<ul><li>'; }
1176 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1177 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1178 else if ( ';' == $char ) {
1179 $result .= '<dl><dt>';
1180 $this->mDTopen = true;
1181 }
1182 else { $result = '<!-- ERR 1 -->'; }
1183
1184 return $result;
1185 }
1186
1187 /* private */ function nextItem( $char ) {
1188 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1189 else if ( ':' == $char || ';' == $char ) {
1190 $close = '</dd>';
1191 if ( $this->mDTopen ) { $close = '</dt>'; }
1192 if ( ';' == $char ) {
1193 $this->mDTopen = true;
1194 return $close . '<dt>';
1195 } else {
1196 $this->mDTopen = false;
1197 return $close . '<dd>';
1198 }
1199 }
1200 return '<!-- ERR 2 -->';
1201 }
1202
1203 /* private */ function closeList( $char ) {
1204 if ( '*' == $char ) { $text = '</li></ul>'; }
1205 else if ( '#' == $char ) { $text = '</li></ol>'; }
1206 else if ( ':' == $char ) {
1207 if ( $this->mDTopen ) {
1208 $this->mDTopen = false;
1209 $text = '</dt></dl>';
1210 } else {
1211 $text = '</dd></dl>';
1212 }
1213 }
1214 else { return '<!-- ERR 3 -->'; }
1215 return $text."\n";
1216 }
1217
1218 /* private */ function doBlockLevels( $text, $linestart ) {
1219 $fname = 'Parser::doBlockLevels';
1220 wfProfileIn( $fname );
1221
1222 # Parsing through the text line by line. The main thing
1223 # happening here is handling of block-level elements p, pre,
1224 # and making lists from lines starting with * # : etc.
1225 #
1226 $textLines = explode( "\n", $text );
1227
1228 $lastPrefix = $output = $lastLine = '';
1229 $this->mDTopen = $inBlockElem = false;
1230 $prefixLength = 0;
1231 $paragraphStack = false;
1232
1233 if ( !$linestart ) {
1234 $output .= array_shift( $textLines );
1235 }
1236 foreach ( $textLines as $oLine ) {
1237 $lastPrefixLength = strlen( $lastPrefix );
1238 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1239 $preOpenMatch = preg_match('/<pre/i', $oLine );
1240 if ( !$this->mInPre ) {
1241 # Multiple prefixes may abut each other for nested lists.
1242 $prefixLength = strspn( $oLine, '*#:;' );
1243 $pref = substr( $oLine, 0, $prefixLength );
1244
1245 # eh?
1246 $pref2 = str_replace( ';', ':', $pref );
1247 $t = substr( $oLine, $prefixLength );
1248 $this->mInPre = !empty($preOpenMatch);
1249 } else {
1250 # Don't interpret any other prefixes in preformatted text
1251 $prefixLength = 0;
1252 $pref = $pref2 = '';
1253 $t = $oLine;
1254 }
1255
1256 # List generation
1257 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1258 # Same as the last item, so no need to deal with nesting or opening stuff
1259 $output .= $this->nextItem( substr( $pref, -1 ) );
1260 $paragraphStack = false;
1261
1262 if ( substr( $pref, -1 ) == ';') {
1263 # The one nasty exception: definition lists work like this:
1264 # ; title : definition text
1265 # So we check for : in the remainder text to split up the
1266 # title and definition, without b0rking links.
1267 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1268 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1269 $term = $match[1];
1270 $output .= $term . $this->nextItem( ':' );
1271 $t = $match[2];
1272 }
1273 }
1274 } elseif( $prefixLength || $lastPrefixLength ) {
1275 # Either open or close a level...
1276 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1277 $paragraphStack = false;
1278
1279 while( $commonPrefixLength < $lastPrefixLength ) {
1280 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1281 --$lastPrefixLength;
1282 }
1283 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1284 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1285 }
1286 while ( $prefixLength > $commonPrefixLength ) {
1287 $char = substr( $pref, $commonPrefixLength, 1 );
1288 $output .= $this->openList( $char );
1289
1290 if ( ';' == $char ) {
1291 # FIXME: This is dupe of code above
1292 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1293 $term = $match[1];
1294 $output .= $term . $this->nextItem( ':' );
1295 $t = $match[2];
1296 }
1297 }
1298 ++$commonPrefixLength;
1299 }
1300 $lastPrefix = $pref2;
1301 }
1302 if( 0 == $prefixLength ) {
1303 # No prefix (not in list)--go to paragraph mode
1304 $uniq_prefix = UNIQ_PREFIX;
1305 // XXX: use a stack for nestable elements like span, table and div
1306 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1307 $closematch = preg_match(
1308 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1309 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1310 if ( $openmatch or $closematch ) {
1311 $paragraphStack = false;
1312 $output .= $this->closeParagraph();
1313 if($preOpenMatch and !$preCloseMatch) {
1314 $this->mInPre = true;
1315 }
1316 if ( $closematch ) {
1317 $inBlockElem = false;
1318 } else {
1319 $inBlockElem = true;
1320 }
1321 } else if ( !$inBlockElem && !$this->mInPre ) {
1322 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1323 // pre
1324 if ($this->mLastSection != 'pre') {
1325 $paragraphStack = false;
1326 $output .= $this->closeParagraph().'<pre>';
1327 $this->mLastSection = 'pre';
1328 }
1329 $t = substr( $t, 1 );
1330 } else {
1331 // paragraph
1332 if ( '' == trim($t) ) {
1333 if ( $paragraphStack ) {
1334 $output .= $paragraphStack.'<br />';
1335 $paragraphStack = false;
1336 $this->mLastSection = 'p';
1337 } else {
1338 if ($this->mLastSection != 'p' ) {
1339 $output .= $this->closeParagraph();
1340 $this->mLastSection = '';
1341 $paragraphStack = '<p>';
1342 } else {
1343 $paragraphStack = '</p><p>';
1344 }
1345 }
1346 } else {
1347 if ( $paragraphStack ) {
1348 $output .= $paragraphStack;
1349 $paragraphStack = false;
1350 $this->mLastSection = 'p';
1351 } else if ($this->mLastSection != 'p') {
1352 $output .= $this->closeParagraph().'<p>';
1353 $this->mLastSection = 'p';
1354 }
1355 }
1356 }
1357 }
1358 }
1359 if ($paragraphStack === false) {
1360 $output .= $t."\n";
1361 }
1362 }
1363 while ( $prefixLength ) {
1364 $output .= $this->closeList( $pref2{$prefixLength-1} );
1365 --$prefixLength;
1366 }
1367 if ( '' != $this->mLastSection ) {
1368 $output .= '</' . $this->mLastSection . '>';
1369 $this->mLastSection = '';
1370 }
1371
1372 wfProfileOut( $fname );
1373 return $output;
1374 }
1375
1376 # Return value of a magic variable (like PAGENAME)
1377 function getVariableValue( $index ) {
1378 global $wgLang, $wgSitename, $wgServer;
1379
1380 switch ( $index ) {
1381 case MAG_CURRENTMONTH:
1382 return $wgLang->formatNum( date( 'm' ) );
1383 case MAG_CURRENTMONTHNAME:
1384 return $wgLang->getMonthName( date('n') );
1385 case MAG_CURRENTMONTHNAMEGEN:
1386 return $wgLang->getMonthNameGen( date('n') );
1387 case MAG_CURRENTDAY:
1388 return $wgLang->formatNum( date('j') );
1389 case MAG_PAGENAME:
1390 return $this->mTitle->getText();
1391 case MAG_PAGENAMEE:
1392 return $this->mTitle->getPartialURL();
1393 case MAG_NAMESPACE:
1394 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1395 return $wgLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1396 case MAG_CURRENTDAYNAME:
1397 return $wgLang->getWeekdayName( date('w')+1 );
1398 case MAG_CURRENTYEAR:
1399 return $wgLang->formatNum( date( 'Y' ) );
1400 case MAG_CURRENTTIME:
1401 return $wgLang->time( wfTimestampNow(), false );
1402 case MAG_NUMBEROFARTICLES:
1403 return $wgLang->formatNum( wfNumberOfArticles() );
1404 case MAG_SITENAME:
1405 return $wgSitename;
1406 case MAG_SERVER:
1407 return $wgServer;
1408 default:
1409 return NULL;
1410 }
1411 }
1412
1413 # initialise the magic variables (like CURRENTMONTHNAME)
1414 function initialiseVariables() {
1415 global $wgVariableIDs;
1416 $this->mVariables = array();
1417 foreach ( $wgVariableIDs as $id ) {
1418 $mw =& MagicWord::get( $id );
1419 $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
1420 }
1421 }
1422
1423 /* private */ function replaceVariables( $text, $args = array() ) {
1424 global $wgLang, $wgScript, $wgArticlePath;
1425
1426 # Prevent too big inclusions
1427 if(strlen($text)> MAX_INCLUDE_SIZE)
1428 return $text;
1429
1430 $fname = 'Parser::replaceVariables';
1431 wfProfileIn( $fname );
1432
1433 $bail = false;
1434 $titleChars = Title::legalChars();
1435 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1436
1437 # This function is called recursively. To keep track of arguments we need a stack:
1438 array_push( $this->mArgStack, $args );
1439
1440 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1441 $GLOBALS['wgCurParser'] =& $this;
1442
1443 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_MSG ) {
1444 # Variable substitution
1445 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1446 }
1447
1448 if ( $this->mOutputType == OT_HTML ) {
1449 # Argument substitution
1450 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1451 }
1452 # Template substitution
1453 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1454 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1455
1456 array_pop( $this->mArgStack );
1457
1458 wfProfileOut( $fname );
1459 return $text;
1460 }
1461
1462 function variableSubstitution( $matches ) {
1463 if ( !$this->mVariables ) {
1464 $this->initialiseVariables();
1465 }
1466 if ( array_key_exists( $matches[1], $this->mVariables ) ) {
1467 $text = $this->mVariables[$matches[1]];
1468 $this->mOutput->mContainsOldMagic = true;
1469 } else {
1470 $text = $matches[0];
1471 }
1472 return $text;
1473 }
1474
1475 # Split template arguments
1476 function getTemplateArgs( $argsString ) {
1477 if ( $argsString === '' ) {
1478 return array();
1479 }
1480
1481 $args = explode( '|', substr( $argsString, 1 ) );
1482
1483 # If any of the arguments contains a '[[' but no ']]', it needs to be
1484 # merged with the next arg because the '|' character between belongs
1485 # to the link syntax and not the template parameter syntax.
1486 $argc = count($args);
1487 $i = 0;
1488 for ( $i = 0; $i < $argc-1; $i++ ) {
1489 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1490 $args[$i] .= '|'.$args[$i+1];
1491 array_splice($args, $i+1, 1);
1492 $i--;
1493 $argc--;
1494 }
1495 }
1496
1497 return $args;
1498 }
1499
1500 function braceSubstitution( $matches ) {
1501 global $wgLinkCache, $wgLang;
1502 $fname = 'Parser::braceSubstitution';
1503 $found = false;
1504 $nowiki = false;
1505 $noparse = false;
1506
1507 $title = NULL;
1508
1509 # $newline is an optional newline character before the braces
1510 # $part1 is the bit before the first |, and must contain only title characters
1511 # $args is a list of arguments, starting from index 0, not including $part1
1512
1513 $newline = $matches[1];
1514 $part1 = $matches[2];
1515 # If the third subpattern matched anything, it will start with |
1516
1517 $args = $this->getTemplateArgs($matches[3]);
1518 $argc = count( $args );
1519
1520 # {{{}}}
1521 if ( strpos( $matches[0], '{{{' ) !== false ) {
1522 $text = $matches[0];
1523 $found = true;
1524 $noparse = true;
1525 }
1526
1527 # SUBST
1528 if ( !$found ) {
1529 $mwSubst =& MagicWord::get( MAG_SUBST );
1530 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1531 if ( $this->mOutputType != OT_WIKI ) {
1532 # Invalid SUBST not replaced at PST time
1533 # Return without further processing
1534 $text = $matches[0];
1535 $found = true;
1536 $noparse= true;
1537 }
1538 } elseif ( $this->mOutputType == OT_WIKI ) {
1539 # SUBST not found in PST pass, do nothing
1540 $text = $matches[0];
1541 $found = true;
1542 }
1543 }
1544
1545 # MSG, MSGNW and INT
1546 if ( !$found ) {
1547 # Check for MSGNW:
1548 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1549 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1550 $nowiki = true;
1551 } else {
1552 # Remove obsolete MSG:
1553 $mwMsg =& MagicWord::get( MAG_MSG );
1554 $mwMsg->matchStartAndRemove( $part1 );
1555 }
1556
1557 # Check if it is an internal message
1558 $mwInt =& MagicWord::get( MAG_INT );
1559 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1560 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1561 $text = wfMsgReal( $part1, $args, true );
1562 $found = true;
1563 }
1564 }
1565 }
1566
1567 # NS
1568 if ( !$found ) {
1569 # Check for NS: (namespace expansion)
1570 $mwNs = MagicWord::get( MAG_NS );
1571 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1572 if ( intval( $part1 ) ) {
1573 $text = $wgLang->getNsText( intval( $part1 ) );
1574 $found = true;
1575 } else {
1576 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1577 if ( !is_null( $index ) ) {
1578 $text = $wgLang->getNsText( $index );
1579 $found = true;
1580 }
1581 }
1582 }
1583 }
1584
1585 # LOCALURL and LOCALURLE
1586 if ( !$found ) {
1587 $mwLocal = MagicWord::get( MAG_LOCALURL );
1588 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1589
1590 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1591 $func = 'getLocalURL';
1592 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1593 $func = 'escapeLocalURL';
1594 } else {
1595 $func = '';
1596 }
1597
1598 if ( $func !== '' ) {
1599 $title = Title::newFromText( $part1 );
1600 if ( !is_null( $title ) ) {
1601 if ( $argc > 0 ) {
1602 $text = $title->$func( $args[0] );
1603 } else {
1604 $text = $title->$func();
1605 }
1606 $found = true;
1607 }
1608 }
1609 }
1610
1611 # Internal variables
1612 if ( !$this->mVariables ) {
1613 $this->initialiseVariables();
1614 }
1615 if ( !$found && array_key_exists( $part1, $this->mVariables ) ) {
1616 $text = $this->mVariables[$part1];
1617 $found = true;
1618 $this->mOutput->mContainsOldMagic = true;
1619 }
1620
1621 # GRAMMAR
1622 if ( !$found && $argc == 1 ) {
1623 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
1624 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1625 $text = $wgLang->convertGrammar( $args[0], $part1 );
1626 $found = true;
1627 }
1628 }
1629
1630 # Template table test
1631
1632 # Did we encounter this template already? If yes, it is in the cache
1633 # and we need to check for loops.
1634 if ( isset( $this->mTemplates[$part1] ) ) {
1635 # Infinite loop test
1636 if ( isset( $this->mTemplatePath[$part1] ) ) {
1637 $noparse = true;
1638 $found = true;
1639 }
1640 # set $text to cached message.
1641 $text = $this->mTemplates[$part1];
1642 $found = true;
1643 }
1644
1645 # Load from database
1646 if ( !$found ) {
1647 $title = Title::newFromText( $part1, NS_TEMPLATE );
1648 if ( !is_null( $title ) && !$title->isExternal() ) {
1649 # Check for excessive inclusion
1650 $dbk = $title->getPrefixedDBkey();
1651 if ( $this->incrementIncludeCount( $dbk ) ) {
1652 # This should never be reached.
1653 $article = new Article( $title );
1654 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1655 if ( $articleContent !== false ) {
1656 $found = true;
1657 $text = $articleContent;
1658 }
1659 }
1660
1661 # If the title is valid but undisplayable, make a link to it
1662 if ( $this->mOutputType == OT_HTML && !$found ) {
1663 $text = '[['.$title->getPrefixedText().']]';
1664 $found = true;
1665 }
1666
1667 # Template cache array insertion
1668 $this->mTemplates[$part1] = $text;
1669 }
1670 }
1671
1672 # Recursive parsing, escaping and link table handling
1673 # Only for HTML output
1674 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
1675 $text = wfEscapeWikiText( $text );
1676 } elseif ( $this->mOutputType == OT_HTML && $found && !$noparse) {
1677 # Clean up argument array
1678 $assocArgs = array();
1679 $index = 1;
1680 foreach( $args as $arg ) {
1681 $eqpos = strpos( $arg, '=' );
1682 if ( $eqpos === false ) {
1683 $assocArgs[$index++] = $arg;
1684 } else {
1685 $name = trim( substr( $arg, 0, $eqpos ) );
1686 $value = trim( substr( $arg, $eqpos+1 ) );
1687 if ( $value === false ) {
1688 $value = '';
1689 }
1690 if ( $name !== false ) {
1691 $assocArgs[$name] = $value;
1692 }
1693 }
1694 }
1695
1696 # Do not enter included links in link table
1697 if ( !is_null( $title ) ) {
1698 $wgLinkCache->suspend();
1699 }
1700
1701 # Add a new element to the templace recursion path
1702 $this->mTemplatePath[$part1] = 1;
1703
1704 $text = $this->stripParse( $text, $newline, $assocArgs );
1705
1706 # Resume the link cache and register the inclusion as a link
1707 if ( !is_null( $title ) ) {
1708 $wgLinkCache->resume();
1709 $wgLinkCache->addLinkObj( $title );
1710 }
1711 }
1712
1713 # Empties the template path
1714 $this->mTemplatePath = array();
1715
1716 if ( !$found ) {
1717 return $matches[0];
1718 } else {
1719 return $text;
1720 }
1721 }
1722
1723 # Triple brace replacement -- used for template arguments
1724 function argSubstitution( $matches ) {
1725 $newline = $matches[1];
1726 $arg = trim( $matches[2] );
1727 $text = $matches[0];
1728 $inputArgs = end( $this->mArgStack );
1729
1730 if ( array_key_exists( $arg, $inputArgs ) ) {
1731 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1732 }
1733
1734 return $text;
1735 }
1736
1737 # Returns true if the function is allowed to include this entity
1738 function incrementIncludeCount( $dbk ) {
1739 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
1740 $this->mIncludeCount[$dbk] = 0;
1741 }
1742 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
1743 return true;
1744 } else {
1745 return false;
1746 }
1747 }
1748
1749
1750 # Cleans up HTML, removes dangerous tags and attributes
1751 /* private */ function removeHTMLtags( $text ) {
1752 global $wgUseTidy, $wgUserHtml;
1753 $fname = 'Parser::removeHTMLtags';
1754 wfProfileIn( $fname );
1755
1756 if( $wgUserHtml ) {
1757 $htmlpairs = array( # Tags that must be closed
1758 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1759 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1760 'strike', 'strong', 'tt', 'var', 'div', 'center',
1761 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1762 'ruby', 'rt' , 'rb' , 'rp', 'p'
1763 );
1764 $htmlsingle = array(
1765 'br', 'hr', 'li', 'dt', 'dd'
1766 );
1767 $htmlnest = array( # Tags that can be nested--??
1768 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1769 'dl', 'font', 'big', 'small', 'sub', 'sup'
1770 );
1771 $tabletags = array( # Can only appear inside table
1772 'td', 'th', 'tr'
1773 );
1774 } else {
1775 $htmlpairs = array();
1776 $htmlsingle = array();
1777 $htmlnest = array();
1778 $tabletags = array();
1779 }
1780
1781 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1782 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1783
1784 $htmlattrs = $this->getHTMLattrs () ;
1785
1786 # Remove HTML comments
1787 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
1788
1789 $bits = explode( '<', $text );
1790 $text = array_shift( $bits );
1791 if(!$wgUseTidy) {
1792 $tagstack = array(); $tablestack = array();
1793 foreach ( $bits as $x ) {
1794 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1795 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1796 $x, $regs );
1797 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1798 error_reporting( $prev );
1799
1800 $badtag = 0 ;
1801 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1802 # Check our stack
1803 if ( $slash ) {
1804 # Closing a tag...
1805 if ( ! in_array( $t, $htmlsingle ) &&
1806 ( $ot = @array_pop( $tagstack ) ) != $t ) {
1807 @array_push( $tagstack, $ot );
1808 $badtag = 1;
1809 } else {
1810 if ( $t == 'table' ) {
1811 $tagstack = array_pop( $tablestack );
1812 }
1813 $newparams = '';
1814 }
1815 } else {
1816 # Keep track for later
1817 if ( in_array( $t, $tabletags ) &&
1818 ! in_array( 'table', $tagstack ) ) {
1819 $badtag = 1;
1820 } else if ( in_array( $t, $tagstack ) &&
1821 ! in_array ( $t , $htmlnest ) ) {
1822 $badtag = 1 ;
1823 } else if ( ! in_array( $t, $htmlsingle ) ) {
1824 if ( $t == 'table' ) {
1825 array_push( $tablestack, $tagstack );
1826 $tagstack = array();
1827 }
1828 array_push( $tagstack, $t );
1829 }
1830 # Strip non-approved attributes from the tag
1831 $newparams = $this->fixTagAttributes($params);
1832
1833 }
1834 if ( ! $badtag ) {
1835 $rest = str_replace( '>', '&gt;', $rest );
1836 $text .= "<$slash$t $newparams$brace$rest";
1837 continue;
1838 }
1839 }
1840 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
1841 }
1842 # Close off any remaining tags
1843 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
1844 $text .= "</$t>\n";
1845 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
1846 }
1847 } else {
1848 # this might be possible using tidy itself
1849 foreach ( $bits as $x ) {
1850 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
1851 $x, $regs );
1852 @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1853 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1854 $newparams = $this->fixTagAttributes($params);
1855 $rest = str_replace( '>', '&gt;', $rest );
1856 $text .= "<$slash$t $newparams$brace$rest";
1857 } else {
1858 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
1859 }
1860 }
1861 }
1862 wfProfileOut( $fname );
1863 return $text;
1864 }
1865
1866
1867 # This function accomplishes several tasks:
1868 # 1) Auto-number headings if that option is enabled
1869 # 2) Add an [edit] link to sections for logged in users who have enabled the option
1870 # 3) Add a Table of contents on the top for users who have enabled the option
1871 # 4) Auto-anchor headings
1872 #
1873 # It loops through all headlines, collects the necessary data, then splits up the
1874 # string and re-inserts the newly formatted headlines.
1875 /* private */ function formatHeadings( $text, $isMain=true ) {
1876 global $wgInputEncoding, $wgMaxTocLevel, $wgLang;
1877
1878 $doNumberHeadings = $this->mOptions->getNumberHeadings();
1879 $doShowToc = $this->mOptions->getShowToc();
1880 $forceTocHere = false;
1881 if( !$this->mTitle->userCanEdit() ) {
1882 $showEditLink = 0;
1883 $rightClickHack = 0;
1884 } else {
1885 $showEditLink = $this->mOptions->getEditSection();
1886 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
1887 }
1888
1889 # Inhibit editsection links if requested in the page
1890 $esw =& MagicWord::get( MAG_NOEDITSECTION );
1891 if( $esw->matchAndRemove( $text ) ) {
1892 $showEditLink = 0;
1893 }
1894 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1895 # do not add TOC
1896 $mw =& MagicWord::get( MAG_NOTOC );
1897 if( $mw->matchAndRemove( $text ) ) {
1898 $doShowToc = 0;
1899 }
1900
1901 # never add the TOC to the Main Page. This is an entry page that should not
1902 # be more than 1-2 screens large anyway
1903 if( $this->mTitle->getPrefixedText() == wfMsg('mainpage') ) {
1904 $doShowToc = 0;
1905 }
1906
1907 # Get all headlines for numbering them and adding funky stuff like [edit]
1908 # links - this is for later, but we need the number of headlines right now
1909 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
1910
1911 # if there are fewer than 4 headlines in the article, do not show TOC
1912 if( $numMatches < 4 ) {
1913 $doShowToc = 0;
1914 }
1915
1916 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
1917 # override above conditions and always show TOC at that place
1918 $mw =& MagicWord::get( MAG_TOC );
1919 if ($mw->match( $text ) ) {
1920 $doShowToc = 1;
1921 $forceTocHere = true;
1922 } else {
1923 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
1924 # override above conditions and always show TOC above first header
1925 $mw =& MagicWord::get( MAG_FORCETOC );
1926 if ($mw->matchAndRemove( $text ) ) {
1927 $doShowToc = 1;
1928 }
1929 }
1930
1931
1932
1933 # We need this to perform operations on the HTML
1934 $sk =& $this->mOptions->getSkin();
1935
1936 # headline counter
1937 $headlineCount = 0;
1938
1939 # Ugh .. the TOC should have neat indentation levels which can be
1940 # passed to the skin functions. These are determined here
1941 $toclevel = 0;
1942 $toc = '';
1943 $full = '';
1944 $head = array();
1945 $sublevelCount = array();
1946 $level = 0;
1947 $prevlevel = 0;
1948 foreach( $matches[3] as $headline ) {
1949 $numbering = '';
1950 if( $level ) {
1951 $prevlevel = $level;
1952 }
1953 $level = $matches[1][$headlineCount];
1954 if( ( $doNumberHeadings || $doShowToc ) && $prevlevel && $level > $prevlevel ) {
1955 # reset when we enter a new level
1956 $sublevelCount[$level] = 0;
1957 $toc .= $sk->tocIndent( $level - $prevlevel );
1958 $toclevel += $level - $prevlevel;
1959 }
1960 if( ( $doNumberHeadings || $doShowToc ) && $level < $prevlevel ) {
1961 # reset when we step back a level
1962 $sublevelCount[$level+1]=0;
1963 $toc .= $sk->tocUnindent( $prevlevel - $level );
1964 $toclevel -= $prevlevel - $level;
1965 }
1966 # count number of headlines for each level
1967 @$sublevelCount[$level]++;
1968 if( $doNumberHeadings || $doShowToc ) {
1969 $dot = 0;
1970 for( $i = 1; $i <= $level; $i++ ) {
1971 if( !empty( $sublevelCount[$i] ) ) {
1972 if( $dot ) {
1973 $numbering .= '.';
1974 }
1975 $numbering .= $wgLang->formatNum( $sublevelCount[$i] );
1976 $dot = 1;
1977 }
1978 }
1979 }
1980
1981 # The canonized header is a version of the header text safe to use for links
1982 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
1983 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
1984 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState );
1985
1986 # Remove link placeholders by the link text.
1987 # <!--LINK namespace page_title link text with suffix-->
1988 # turns into
1989 # link text with suffix
1990 $canonized_headline = preg_replace( '/<!--LINK [0-9]* [^ ]* *(.*?)-->/','$1', $canonized_headline );
1991 # strip out HTML
1992 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
1993 $tocline = trim( $canonized_headline );
1994 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
1995 $replacearray = array(
1996 '%3A' => ':',
1997 '%' => '.'
1998 );
1999 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2000 $refer[$headlineCount] = $canonized_headline;
2001
2002 # count how many in assoc. array so we can track dupes in anchors
2003 @$refers[$canonized_headline]++;
2004 $refcount[$headlineCount]=$refers[$canonized_headline];
2005
2006 # Prepend the number to the heading text
2007
2008 if( $doNumberHeadings || $doShowToc ) {
2009 $tocline = $numbering . ' ' . $tocline;
2010
2011 # Don't number the heading if it is the only one (looks silly)
2012 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2013 # the two are different if the line contains a link
2014 $headline=$numbering . ' ' . $headline;
2015 }
2016 }
2017
2018 # Create the anchor for linking from the TOC to the section
2019 $anchor = $canonized_headline;
2020 if($refcount[$headlineCount] > 1 ) {
2021 $anchor .= '_' . $refcount[$headlineCount];
2022 }
2023 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2024 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2025 }
2026 if( $showEditLink ) {
2027 if ( empty( $head[$headlineCount] ) ) {
2028 $head[$headlineCount] = '';
2029 }
2030 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+1);
2031 }
2032
2033 # Add the edit section span
2034 if( $rightClickHack ) {
2035 $headline = $sk->editSectionScript($headlineCount+1,$headline);
2036 }
2037
2038 # give headline the correct <h#> tag
2039 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2040
2041 $headlineCount++;
2042 }
2043
2044 if( $doShowToc ) {
2045 $toclines = $headlineCount;
2046 $toc .= $sk->tocUnindent( $toclevel );
2047 $toc = $sk->tocTable( $toc );
2048 }
2049
2050 # split up and insert constructed headlines
2051
2052 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2053 $i = 0;
2054
2055 foreach( $blocks as $block ) {
2056 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2057 # This is the [edit] link that appears for the top block of text when
2058 # section editing is enabled
2059
2060 # Disabled because it broke block formatting
2061 # For example, a bullet point in the top line
2062 # $full .= $sk->editSectionLink(0);
2063 }
2064 $full .= $block;
2065 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2066 # Top anchor now in skin
2067 $full = $full.$toc;
2068 }
2069
2070 if( !empty( $head[$i] ) ) {
2071 $full .= $head[$i];
2072 }
2073 $i++;
2074 }
2075 if($forceTocHere) {
2076 $mw =& MagicWord::get( MAG_TOC );
2077 return $mw->replace( $toc, $full );
2078 } else {
2079 return $full;
2080 }
2081 }
2082
2083 # Return an HTML link for the "ISBN 123456" text
2084 /* private */ function magicISBN( $text ) {
2085 global $wgLang;
2086 $fname = 'Parser::magicISBN';
2087 wfProfileIn( $fname );
2088
2089 $a = split( 'ISBN ', ' '.$text );
2090 if ( count ( $a ) < 2 ) {
2091 wfProfileOut( $fname );
2092 return $text;
2093 }
2094 $text = substr( array_shift( $a ), 1);
2095 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2096
2097 foreach ( $a as $x ) {
2098 $isbn = $blank = '' ;
2099 while ( ' ' == $x{0} ) {
2100 $blank .= ' ';
2101 $x = substr( $x, 1 );
2102 }
2103 if ( $x == '' ) { # blank isbn
2104 $text .= "ISBN $blank";
2105 continue;
2106 }
2107 while ( strstr( $valid, $x{0} ) != false ) {
2108 $isbn .= $x{0};
2109 $x = substr( $x, 1 );
2110 }
2111 $num = str_replace( '-', '', $isbn );
2112 $num = str_replace( ' ', '', $num );
2113
2114 if ( '' == $num ) {
2115 $text .= "ISBN $blank$x";
2116 } else {
2117 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2118 $text .= '<a href="' .
2119 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2120 "\" class=\"internal\">ISBN $isbn</a>";
2121 $text .= $x;
2122 }
2123 }
2124 wfProfileOut( $fname );
2125 return $text;
2126 }
2127
2128 # Return an HTML link for the "GEO ..." text
2129 /* private */ function magicGEO( $text ) {
2130 global $wgLang, $wgUseGeoMode;
2131 $fname = 'Parser::magicGEO';
2132 wfProfileIn( $fname );
2133
2134 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2135 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2136 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2137 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2138 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2139 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2140
2141 $a = split( 'GEO ', ' '.$text );
2142 if ( count ( $a ) < 2 ) {
2143 wfProfileOut( $fname );
2144 return $text;
2145 }
2146 $text = substr( array_shift( $a ), 1);
2147 $valid = '0123456789.+-:';
2148
2149 foreach ( $a as $x ) {
2150 $geo = $blank = '' ;
2151 while ( ' ' == $x{0} ) {
2152 $blank .= ' ';
2153 $x = substr( $x, 1 );
2154 }
2155 while ( strstr( $valid, $x{0} ) != false ) {
2156 $geo .= $x{0};
2157 $x = substr( $x, 1 );
2158 }
2159 $num = str_replace( '+', '', $geo );
2160 $num = str_replace( ' ', '', $num );
2161
2162 if ( '' == $num || count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2163 $text .= "GEO $blank$x";
2164 } else {
2165 $titleObj = Title::makeTitle( NS_SPECIAL, 'Geo' );
2166 $text .= '<a href="' .
2167 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2168 "\" class=\"internal\">GEO $geo</a>";
2169 $text .= $x;
2170 }
2171 }
2172 wfProfileOut( $fname );
2173 return $text;
2174 }
2175
2176 # Return an HTML link for the "RFC 1234" text
2177 /* private */ function magicRFC( $text ) {
2178 global $wgLang;
2179
2180 $a = split( 'RFC ', ' '.$text );
2181 if ( count ( $a ) < 2 ) return $text;
2182 $text = substr( array_shift( $a ), 1);
2183 $valid = '0123456789';
2184
2185 foreach ( $a as $x ) {
2186 $rfc = $blank = '' ;
2187 while ( ' ' == $x{0} ) {
2188 $blank .= ' ';
2189 $x = substr( $x, 1 );
2190 }
2191 while ( strstr( $valid, $x{0} ) != false ) {
2192 $rfc .= $x{0};
2193 $x = substr( $x, 1 );
2194 }
2195
2196 if ( '' == $rfc ) {
2197 $text .= "RFC $blank$x";
2198 } else {
2199 $url = wfmsg( 'rfcurl' );
2200 $url = str_replace( '$1', $rfc, $url);
2201 $sk =& $this->mOptions->getSkin();
2202 $la = $sk->getExternalLinkAttributes( $url, 'RFC '.$rfc );
2203 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2204 }
2205 }
2206 return $text;
2207 }
2208
2209 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2210 $this->mOptions = $options;
2211 $this->mTitle =& $title;
2212 $this->mOutputType = OT_WIKI;
2213
2214 if ( $clearState ) {
2215 $this->clearState();
2216 }
2217
2218 $stripState = false;
2219 $pairs = array(
2220 "\r\n" => "\n",
2221 );
2222 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2223 // now with regexes
2224 /*
2225 $pairs = array(
2226 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2227 "/<br *?>/i" => "<br />",
2228 );
2229 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2230 */
2231 $text = $this->strip( $text, $stripState, false );
2232 $text = $this->pstPass2( $text, $user );
2233 $text = $this->unstrip( $text, $stripState );
2234 $text = $this->unstripNoWiki( $text, $stripState );
2235 return $text;
2236 }
2237
2238 /* private */ function pstPass2( $text, &$user ) {
2239 global $wgLang, $wgLocaltimezone, $wgCurParser;
2240
2241 # Variable replacement
2242 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2243 $text = $this->replaceVariables( $text );
2244
2245 # Signatures
2246 #
2247 $n = $user->getName();
2248 $k = $user->getOption( 'nickname' );
2249 if ( '' == $k ) { $k = $n; }
2250 if(isset($wgLocaltimezone)) {
2251 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2252 }
2253 /* Note: this is an ugly timezone hack for the European wikis */
2254 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2255 ' (' . date( 'T' ) . ')';
2256 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2257
2258 $text = preg_replace( '/~~~~~/', $d, $text );
2259 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText( NS_USER ) . ":$n|$k]] $d", $text );
2260 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText( NS_USER ) . ":$n|$k]]", $text );
2261
2262 # Context links: [[|name]] and [[name (context)|]]
2263 #
2264 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2265 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2266 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2267 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2268
2269 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2270 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2271 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2272 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2273 $context = '';
2274 $t = $this->mTitle->getText();
2275 if ( preg_match( $conpat, $t, $m ) ) {
2276 $context = $m[2];
2277 }
2278 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2279 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2280 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2281
2282 if ( '' == $context ) {
2283 $text = preg_replace( $p2, '[[\\1]]', $text );
2284 } else {
2285 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2286 }
2287
2288 /*
2289 $mw =& MagicWord::get( MAG_SUBST );
2290 $wgCurParser = $this->fork();
2291 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2292 $this->merge( $wgCurParser );
2293 */
2294
2295 # Trim trailing whitespace
2296 # MAG_END (__END__) tag allows for trailing
2297 # whitespace to be deliberately included
2298 $text = rtrim( $text );
2299 $mw =& MagicWord::get( MAG_END );
2300 $mw->matchAndRemove( $text );
2301
2302 return $text;
2303 }
2304
2305 # Set up some variables which are usually set up in parse()
2306 # so that an external function can call some class members with confidence
2307 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2308 $this->mTitle =& $title;
2309 $this->mOptions = $options;
2310 $this->mOutputType = $outputType;
2311 if ( $clearState ) {
2312 $this->clearState();
2313 }
2314 }
2315
2316 function transformMsg( $text, $options ) {
2317 global $wgTitle;
2318 static $executing = false;
2319
2320 # Guard against infinite recursion
2321 if ( $executing ) {
2322 return $text;
2323 }
2324 $executing = true;
2325
2326 $this->mTitle = $wgTitle;
2327 $this->mOptions = $options;
2328 $this->mOutputType = OT_MSG;
2329 $this->clearState();
2330 $text = $this->replaceVariables( $text );
2331
2332 $executing = false;
2333 return $text;
2334 }
2335
2336 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2337 # Callback will be called with the text within
2338 # Transform and return the text within
2339 function setHook( $tag, $callback ) {
2340 $oldVal = @$this->mTagHooks[$tag];
2341 $this->mTagHooks[$tag] = $callback;
2342 return $oldVal;
2343 }
2344 }
2345
2346 /**
2347 * @todo document
2348 * @package MediaWiki
2349 */
2350 class ParserOutput
2351 {
2352 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2353 var $mCacheTime; # Used in ParserCache
2354
2355 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2356 $containsOldMagic = false )
2357 {
2358 $this->mText = $text;
2359 $this->mLanguageLinks = $languageLinks;
2360 $this->mCategoryLinks = $categoryLinks;
2361 $this->mContainsOldMagic = $containsOldMagic;
2362 $this->mCacheTime = '';
2363 }
2364
2365 function getText() { return $this->mText; }
2366 function getLanguageLinks() { return $this->mLanguageLinks; }
2367 function getCategoryLinks() { return $this->mCategoryLinks; }
2368 function getCacheTime() { return $this->mCacheTime; }
2369 function containsOldMagic() { return $this->mContainsOldMagic; }
2370 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2371 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2372 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2373 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2374 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2375
2376 function merge( $other ) {
2377 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2378 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2379 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2380 }
2381
2382 }
2383
2384 /**
2385 * Set options of the Parser
2386 * @todo document
2387 * @package MediaWiki
2388 */
2389 class ParserOptions
2390 {
2391 # All variables are private
2392 var $mUseTeX; # Use texvc to expand <math> tags
2393 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2394 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2395 var $mAllowExternalImages; # Allow external images inline
2396 var $mSkin; # Reference to the preferred skin
2397 var $mDateFormat; # Date format index
2398 var $mEditSection; # Create "edit section" links
2399 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2400 var $mNumberHeadings; # Automatically number headings
2401 var $mShowToc; # Show table of contents
2402
2403 function getUseTeX() { return $this->mUseTeX; }
2404 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2405 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2406 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2407 function getSkin() { return $this->mSkin; }
2408 function getDateFormat() { return $this->mDateFormat; }
2409 function getEditSection() { return $this->mEditSection; }
2410 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
2411 function getNumberHeadings() { return $this->mNumberHeadings; }
2412 function getShowToc() { return $this->mShowToc; }
2413
2414 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
2415 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
2416 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
2417 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
2418 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
2419 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
2420 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
2421 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
2422 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
2423
2424 function setSkin( &$x ) { $this->mSkin =& $x; }
2425
2426 # Get parser options
2427 /* static */ function newFromUser( &$user ) {
2428 $popts = new ParserOptions;
2429 $popts->initialiseFromUser( $user );
2430 return $popts;
2431 }
2432
2433 # Get user options
2434 function initialiseFromUser( &$userInput ) {
2435 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2436
2437 $fname = 'ParserOptions::initialiseFromUser';
2438 wfProfileIn( $fname );
2439 if ( !$userInput ) {
2440 $user = new User;
2441 $user->setLoaded( true );
2442 } else {
2443 $user =& $userInput;
2444 }
2445
2446 $this->mUseTeX = $wgUseTeX;
2447 $this->mUseDynamicDates = $wgUseDynamicDates;
2448 $this->mInterwikiMagic = $wgInterwikiMagic;
2449 $this->mAllowExternalImages = $wgAllowExternalImages;
2450 wfProfileIn( $fname.'-skin' );
2451 $this->mSkin =& $user->getSkin();
2452 wfProfileOut( $fname.'-skin' );
2453 $this->mDateFormat = $user->getOption( 'date' );
2454 $this->mEditSection = $user->getOption( 'editsection' );
2455 $this->mEditSectionOnRightClick = $user->getOption( 'editsectiononrightclick' );
2456 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
2457 $this->mShowToc = $user->getOption( 'showtoc' );
2458 wfProfileOut( $fname );
2459 }
2460
2461
2462 }
2463
2464 # Regex callbacks, used in Parser::replaceVariables
2465 function wfBraceSubstitution( $matches ) {
2466 global $wgCurParser;
2467 return $wgCurParser->braceSubstitution( $matches );
2468 }
2469
2470 function wfArgSubstitution( $matches ) {
2471 global $wgCurParser;
2472 return $wgCurParser->argSubstitution( $matches );
2473 }
2474
2475 function wfVariableSubstitution( $matches ) {
2476 global $wgCurParser;
2477 return $wgCurParser->variableSubstitution( $matches );
2478 }
2479
2480 /**
2481 * Return the total number of articles
2482 */
2483 function wfNumberOfArticles() {
2484 global $wgNumberOfArticles;
2485
2486 wfLoadSiteStats();
2487 return $wgNumberOfArticles;
2488 }
2489
2490 /**
2491 * Get various statistics from the database
2492 * @private
2493 */
2494 function wfLoadSiteStats() {
2495 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
2496 $fname = 'wfLoadSiteStats';
2497
2498 if ( -1 != $wgNumberOfArticles ) return;
2499 $dbr =& wfGetDB( DB_SLAVE );
2500 $s = $dbr->getArray( 'site_stats',
2501 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
2502 array( 'ss_row_id' => 1 ), $fname
2503 );
2504
2505 if ( $s === false ) {
2506 return;
2507 } else {
2508 $wgTotalViews = $s->ss_total_views;
2509 $wgTotalEdits = $s->ss_total_edits;
2510 $wgNumberOfArticles = $s->ss_good_articles;
2511 }
2512 }
2513
2514 function wfEscapeHTMLTagsOnly( $in ) {
2515 return str_replace(
2516 array( '"', '>', '<' ),
2517 array( '&quot;', '&gt;', '&lt;' ),
2518 $in );
2519 }
2520
2521
2522 ?>