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