Loop invariant optimization: skip further checks for subpages on namespaces where...
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2
3 /**
4 * File for Parser and related classes
5 *
6 * @package MediaWiki
7 * @version $Id$
8 */
9
10 /**
11 * Update this version number when the ParserOutput format
12 * changes in an incompatible way, so the parser cache
13 * can automatically discard old data.
14 */
15 define( 'MW_PARSER_VERSION', '1.4.0' );
16
17 /**
18 * Variable substitution O(N^2) attack
19 *
20 * Without countermeasures, it would be possible to attack the parser by saving
21 * a page filled with a large number of inclusions of large pages. The size of
22 * the generated page would be proportional to the square of the input size.
23 * Hence, we limit the number of inclusions of any given page, thus bringing any
24 * attack back to O(N).
25 */
26
27 define( 'MAX_INCLUDE_REPEAT', 100 );
28 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
29
30 define( 'RLH_FOR_UPDATE', 1 );
31
32 # Allowed values for $mOutputType
33 define( 'OT_HTML', 1 );
34 define( 'OT_WIKI', 2 );
35 define( 'OT_MSG' , 3 );
36
37 # string parameter for extractTags which will cause it
38 # to strip HTML comments in addition to regular
39 # <XML>-style tags. This should not be anything we
40 # may want to use in wikisyntax
41 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
42
43 # prefix for escaping, used in two functions at least
44 define( 'UNIQ_PREFIX', 'NaodW29');
45
46 # Constants needed for external link processing
47 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
48 define( 'HTTP_PROTOCOLS', 'http|https' );
49 # Everything except bracket, space, or control characters
50 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
51 # Including space
52 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
53 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
54 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
55 define( 'EXT_LINK_BRACKETED', '/\[(('.URL_PROTOCOLS.'):'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
56 define( 'EXT_IMAGE_REGEX',
57 '/^('.HTTP_PROTOCOLS.':)'. # Protocol
58 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
59 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
60 );
61
62 /**
63 * PHP Parser
64 *
65 * Processes wiki markup
66 *
67 * <pre>
68 * There are three main entry points into the Parser class:
69 * parse()
70 * produces HTML output
71 * preSaveTransform().
72 * produces altered wiki markup.
73 * transformMsg()
74 * performs brace substitution on MediaWiki messages
75 *
76 * Globals used:
77 * objects: $wgLang, $wgDateFormatter, $wgLinkCache
78 *
79 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
80 *
81 * settings:
82 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
83 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
84 * $wgLocaltimezone
85 *
86 * * only within ParserOptions
87 * </pre>
88 *
89 * @package MediaWiki
90 */
91 class Parser
92 {
93 /**#@+
94 * @access private
95 */
96 # Persistent:
97 var $mTagHooks;
98
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
101 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102
103 # Temporary:
104 var $mOptions, $mTitle, $mOutputType,
105 $mTemplates, // cache of already loaded templates, avoids
106 // multiple SQL queries for the same string
107 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
108 // in this path. Used for loop detection.
109
110 /**#@-*/
111
112 /**
113 * Constructor
114 *
115 * @access public
116 */
117 function Parser() {
118 $this->mTemplates = array();
119 $this->mTemplatePath = array();
120 $this->mTagHooks = array();
121 $this->clearState();
122 }
123
124 /**
125 * Clear Parser state
126 *
127 * @access private
128 */
129 function clearState() {
130 $this->mOutput = new ParserOutput;
131 $this->mAutonumber = 0;
132 $this->mLastSection = "";
133 $this->mDTopen = false;
134 $this->mVariables = false;
135 $this->mIncludeCount = array();
136 $this->mStripState = array();
137 $this->mArgStack = array();
138 $this->mInPre = false;
139 }
140
141 /**
142 * First pass--just handle <nowiki> sections, pass the rest off
143 * to internalParse() which does all the real work.
144 *
145 * @access private
146 * @return ParserOutput a ParserOutput
147 */
148 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
149 global $wgUseTidy, $wgContLang;
150 $fname = 'Parser::parse';
151 wfProfileIn( $fname );
152
153 if ( $clearState ) {
154 $this->clearState();
155 }
156
157 $this->mOptions = $options;
158 $this->mTitle =& $title;
159 $this->mOutputType = OT_HTML;
160
161 $stripState = NULL;
162 $text = $this->strip( $text, $this->mStripState );
163
164 $text = $this->internalParse( $text, $linestart );
165 $text = $this->unstrip( $text, $this->mStripState );
166 # Clean up special characters, only run once, next-to-last before doBlockLevels
167 if(!$wgUseTidy) {
168 $fixtags = array(
169 # french spaces, last one Guillemet-left
170 # only if there is something before the space
171 '/(.) (?=\\?|:|;|!|\\302\\273)/i' => '\\1&nbsp;\\2',
172 # french spaces, Guillemet-right
173 "/(\\302\\253) /i"=>"\\1&nbsp;",
174 '/<hr *>/i' => '<hr />',
175 '/<br *>/i' => '<br />',
176 '/<center *>/i' => '<div class="center">',
177 '/<\\/center *>/i' => '</div>',
178 # Clean up spare ampersands; note that we probably ought to be
179 # more careful about named entities.
180 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&amp;'
181 );
182 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
183 } else {
184 $fixtags = array(
185 # french spaces, last one Guillemet-left
186 '/ (\\?|:|;|!|\\302\\273)/i' => '&nbsp;\\1',
187 # french spaces, Guillemet-right
188 '/(\\302\\253) /i' => '\\1&nbsp;',
189 '/<center *>/i' => '<div class="center">',
190 '/<\\/center *>/i' => '</div>'
191 );
192 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
193 }
194 # only once and last
195 $text = $this->doBlockLevels( $text, $linestart );
196
197 $this->replaceLinkHolders( $text );
198 $text = $wgContLang->convert($text);
199
200 $text = $this->unstripNoWiki( $text, $this->mStripState );
201 global $wgUseTidy;
202 if ($wgUseTidy) {
203 $text = Parser::tidy($text);
204 }
205
206 $this->mOutput->setText( $text );
207 wfProfileOut( $fname );
208 return $this->mOutput;
209 }
210
211 /**
212 * Get a random string
213 *
214 * @access private
215 * @static
216 */
217 function getRandomString() {
218 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
219 }
220
221 /**
222 * Replaces all occurrences of <$tag>content</$tag> in the text
223 * with a random marker and returns the new text. the output parameter
224 * $content will be an associative array filled with data on the form
225 * $unique_marker => content.
226 *
227 * If $content is already set, the additional entries will be appended
228 * If $tag is set to STRIP_COMMENTS, the function will extract
229 * <!-- HTML comments -->
230 *
231 * @access private
232 * @static
233 */
234 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
235 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
236 if ( !$content ) {
237 $content = array( );
238 }
239 $n = 1;
240 $stripped = '';
241
242 while ( '' != $text ) {
243 if($tag==STRIP_COMMENTS) {
244 $p = preg_split( '/<!--/i', $text, 2 );
245 } else {
246 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
247 }
248 $stripped .= $p[0];
249 if ( ( count( $p ) < 2 ) || ( '' == $p[1] ) ) {
250 $text = '';
251 } else {
252 if($tag==STRIP_COMMENTS) {
253 $q = preg_split( '/-->/i', $p[1], 2 );
254 } else {
255 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
256 }
257 $marker = $rnd . sprintf('%08X', $n++);
258 $content[$marker] = $q[0];
259 $stripped .= $marker;
260 $text = $q[1];
261 }
262 }
263 return $stripped;
264 }
265
266 /**
267 * Strips and renders nowiki, pre, math, hiero
268 * If $render is set, performs necessary rendering operations on plugins
269 * Returns the text, and fills an array with data needed in unstrip()
270 * If the $state is already a valid strip state, it adds to the state
271 *
272 * @param bool $stripcomments when set, HTML comments <!-- like this -->
273 * will be stripped in addition to other tags. This is important
274 * for section editing, where these comments cause confusion when
275 * counting the sections in the wikisource
276 *
277 * @access private
278 */
279 function strip( $text, &$state, $stripcomments = false ) {
280 $render = ($this->mOutputType == OT_HTML);
281 $html_content = array();
282 $nowiki_content = array();
283 $math_content = array();
284 $pre_content = array();
285 $comment_content = array();
286 $ext_content = array();
287 $gallery_content = array();
288
289 # Replace any instances of the placeholders
290 $uniq_prefix = UNIQ_PREFIX;
291 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
292
293 # html
294 global $wgRawHtml, $wgWhitelistEdit;
295 if( $wgRawHtml && $wgWhitelistEdit ) {
296 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
297 foreach( $html_content as $marker => $content ) {
298 if ($render ) {
299 # Raw and unchecked for validity.
300 $html_content[$marker] = $content;
301 } else {
302 $html_content[$marker] = '<html>'.$content.'</html>';
303 }
304 }
305 }
306
307 # nowiki
308 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
309 foreach( $nowiki_content as $marker => $content ) {
310 if( $render ){
311 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
312 } else {
313 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
314 }
315 }
316
317 # math
318 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
319 foreach( $math_content as $marker => $content ){
320 if( $render ) {
321 if( $this->mOptions->getUseTeX() ) {
322 $math_content[$marker] = renderMath( $content );
323 } else {
324 $math_content[$marker] = '&lt;math&gt;'.$content.'&lt;math&gt;';
325 }
326 } else {
327 $math_content[$marker] = '<math>'.$content.'</math>';
328 }
329 }
330
331 # pre
332 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
333 foreach( $pre_content as $marker => $content ){
334 if( $render ){
335 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
336 } else {
337 $pre_content[$marker] = '<pre>'.$content.'</pre>';
338 }
339 }
340
341 # gallery
342 $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
343 foreach( $gallery_content as $marker => $content ) {
344 require_once( 'ImageGallery.php' );
345 if ( $render ) {
346 $gallery_content[$marker] = Parser::renderImageGallery( $content );
347 } else {
348 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
349 }
350 }
351
352 # Comments
353 if($stripcomments) {
354 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
355 foreach( $comment_content as $marker => $content ){
356 $comment_content[$marker] = '<!--'.$content.'-->';
357 }
358 }
359
360 # Extensions
361 foreach ( $this->mTagHooks as $tag => $callback ) {
362 $ext_contents[$tag] = array();
363 $text = Parser::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
364 foreach( $ext_content[$tag] as $marker => $content ) {
365 if ( $render ) {
366 $ext_content[$tag][$marker] = $callback( $content );
367 } else {
368 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
369 }
370 }
371 }
372
373 # Merge state with the pre-existing state, if there is one
374 if ( $state ) {
375 $state['html'] = $state['html'] + $html_content;
376 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
377 $state['math'] = $state['math'] + $math_content;
378 $state['pre'] = $state['pre'] + $pre_content;
379 $state['comment'] = $state['comment'] + $comment_content;
380 $state['gallery'] = $state['gallery'] + $gallery_content;
381
382 foreach( $ext_content as $tag => $array ) {
383 if ( array_key_exists( $tag, $state ) ) {
384 $state[$tag] = $state[$tag] + $array;
385 }
386 }
387 } else {
388 $state = array(
389 'html' => $html_content,
390 'nowiki' => $nowiki_content,
391 'math' => $math_content,
392 'pre' => $pre_content,
393 'comment' => $comment_content,
394 'gallery' => $gallery_content,
395 ) + $ext_content;
396 }
397 return $text;
398 }
399
400 /**
401 * restores pre, math, and hiero removed by strip()
402 *
403 * always call unstripNoWiki() after this one
404 * @access private
405 */
406 function unstrip( $text, &$state ) {
407 # Must expand in reverse order, otherwise nested tags will be corrupted
408 $contentDict = end( $state );
409 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
410 if( key($state) != 'nowiki' && key($state) != 'html') {
411 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
412 $text = str_replace( key( $contentDict ), $content, $text );
413 }
414 }
415 }
416
417 return $text;
418 }
419
420 /**
421 * always call this after unstrip() to preserve the order
422 *
423 * @access private
424 */
425 function unstripNoWiki( $text, &$state ) {
426 # Must expand in reverse order, otherwise nested tags will be corrupted
427 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
428 $text = str_replace( key( $state['nowiki'] ), $content, $text );
429 }
430
431 global $wgRawHtml;
432 if ($wgRawHtml) {
433 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
434 $text = str_replace( key( $state['html'] ), $content, $text );
435 }
436 }
437
438 return $text;
439 }
440
441 /**
442 * Add an item to the strip state
443 * Returns the unique tag which must be inserted into the stripped text
444 * The tag will be replaced with the original text in unstrip()
445 *
446 * @access private
447 */
448 function insertStripItem( $text, &$state ) {
449 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
450 if ( !$state ) {
451 $state = array(
452 'html' => array(),
453 'nowiki' => array(),
454 'math' => array(),
455 'pre' => array()
456 );
457 }
458 $state['item'][$rnd] = $text;
459 return $rnd;
460 }
461
462 /**
463 * Return allowed HTML attributes
464 *
465 * @access private
466 */
467 function getHTMLattrs () {
468 $htmlattrs = array( # Allowed attributes--no scripting, etc.
469 'title', 'align', 'lang', 'dir', 'width', 'height',
470 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
471 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
472 /* FONT */ 'type', 'start', 'value', 'compact',
473 /* For various lists, mostly deprecated but safe */
474 'summary', 'width', 'border', 'frame', 'rules',
475 'cellspacing', 'cellpadding', 'valign', 'char',
476 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
477 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
478 'id', 'class', 'name', 'style' /* For CSS */
479 );
480 return $htmlattrs ;
481 }
482
483 /**
484 * Remove non approved attributes and javascript in css
485 *
486 * @access private
487 */
488 function fixTagAttributes ( $t ) {
489 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
490 $htmlattrs = $this->getHTMLattrs() ;
491
492 # Strip non-approved attributes from the tag
493 $t = preg_replace(
494 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
495 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
496 $t);
497
498 $t = str_replace ( '<></>' , '' , $t ) ; # This should fix bug 980557
499
500 # Strip javascript "expression" from stylesheets. Brute force approach:
501 # If anythin offensive is found, all attributes of the HTML tag are dropped
502
503 if( preg_match(
504 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
505 wfMungeToUtf8( $t ) ) )
506 {
507 $t='';
508 }
509
510 return trim ( $t ) ;
511 }
512
513 /**
514 * interface with html tidy, used if $wgUseTidy = true
515 *
516 * @access public
517 * @static
518 */
519 function tidy ( $text ) {
520 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
521 global $wgInputEncoding, $wgOutputEncoding;
522 $fname = 'Parser::tidy';
523 wfProfileIn( $fname );
524
525 $cleansource = '';
526 $opts = '';
527 switch(strtoupper($wgOutputEncoding)) {
528 case 'ISO-8859-1':
529 $opts .= ($wgInputEncoding == $wgOutputEncoding)? ' -latin1':' -raw';
530 break;
531 case 'UTF-8':
532 $opts .= ($wgInputEncoding == $wgOutputEncoding)? ' -utf8':' -raw';
533 break;
534 default:
535 $opts .= ' -raw';
536 }
537
538 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
539 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
540 '<head><title>test</title></head><body>'.$text.'</body></html>';
541 $descriptorspec = array(
542 0 => array('pipe', 'r'),
543 1 => array('pipe', 'w'),
544 2 => array('file', '/dev/null', 'a')
545 );
546 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
547 if (is_resource($process)) {
548 fwrite($pipes[0], $wrappedtext);
549 fclose($pipes[0]);
550 while (!feof($pipes[1])) {
551 $cleansource .= fgets($pipes[1], 1024);
552 }
553 fclose($pipes[1]);
554 $return_value = proc_close($process);
555 }
556
557 wfProfileOut( $fname );
558
559 if( $cleansource == '' && $text != '') {
560 wfDebug( "Tidy error detected!\n" );
561 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
562 } else {
563 return $cleansource;
564 }
565 }
566
567 /**
568 * parse the wiki syntax used to render tables
569 *
570 * @access private
571 */
572 function doTableStuff ( $t ) {
573 $fname = 'Parser::doTableStuff';
574 wfProfileIn( $fname );
575
576 $t = explode ( "\n" , $t ) ;
577 $td = array () ; # Is currently a td tag open?
578 $ltd = array () ; # Was it TD or TH?
579 $tr = array () ; # Is currently a tr tag open?
580 $ltr = array () ; # tr attributes
581 $indent_level = 0; # indent level of the table
582 foreach ( $t AS $k => $x )
583 {
584 $x = trim ( $x ) ;
585 $fc = substr ( $x , 0 , 1 ) ;
586 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
587 $indent_level = strlen( $matches[1] );
588 $t[$k] = "\n" .
589 str_repeat( '<dl><dd>', $indent_level ) .
590 '<table ' . $this->fixTagAttributes ( $matches[2] ) . '>' ;
591 array_push ( $td , false ) ;
592 array_push ( $ltd , '' ) ;
593 array_push ( $tr , false ) ;
594 array_push ( $ltr , '' ) ;
595 }
596 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
597 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
598 $z = "</table>\n" ;
599 $l = array_pop ( $ltd ) ;
600 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
601 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
602 array_pop ( $ltr ) ;
603 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
604 }
605 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
606 $x = substr ( $x , 1 ) ;
607 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
608 $z = '' ;
609 $l = array_pop ( $ltd ) ;
610 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
611 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
612 array_pop ( $ltr ) ;
613 $t[$k] = $z ;
614 array_push ( $tr , false ) ;
615 array_push ( $td , false ) ;
616 array_push ( $ltd , '' ) ;
617 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
618 }
619 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
620 # $x is a table row
621 if ( '|+' == substr ( $x , 0 , 2 ) ) {
622 $fc = '+' ;
623 $x = substr ( $x , 1 ) ;
624 }
625 $after = substr ( $x , 1 ) ;
626 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
627 $after = explode ( '||' , $after ) ;
628 $t[$k] = '' ;
629
630 # Loop through each table cell
631 foreach ( $after AS $theline )
632 {
633 $z = '' ;
634 if ( $fc != '+' )
635 {
636 $tra = array_pop ( $ltr ) ;
637 if ( !array_pop ( $tr ) ) $z = '<tr '.$tra.">\n" ;
638 array_push ( $tr , true ) ;
639 array_push ( $ltr , '' ) ;
640 }
641
642 $l = array_pop ( $ltd ) ;
643 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
644 if ( $fc == '|' ) $l = 'td' ;
645 else if ( $fc == '!' ) $l = 'th' ;
646 else if ( $fc == '+' ) $l = 'caption' ;
647 else $l = '' ;
648 array_push ( $ltd , $l ) ;
649
650 # Cell parameters
651 $y = explode ( '|' , $theline , 2 ) ;
652 # Note that a '|' inside an invalid link should not
653 # be mistaken as delimiting cell parameters
654 if ( strpos( $y[0], '[[' ) !== false ) {
655 $y = array ($theline);
656 }
657 if ( count ( $y ) == 1 )
658 $y = "{$z}<{$l}>{$y[0]}" ;
659 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
660 $t[$k] .= $y ;
661 array_push ( $td , true ) ;
662 }
663 }
664 }
665
666 # Closing open td, tr && table
667 while ( count ( $td ) > 0 )
668 {
669 if ( array_pop ( $td ) ) $t[] = '</td>' ;
670 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
671 $t[] = '</table>' ;
672 }
673
674 $t = implode ( "\n" , $t ) ;
675 # $t = $this->removeHTMLtags( $t );
676 wfProfileOut( $fname );
677 return $t ;
678 }
679
680 /**
681 * Helper function for parse() that transforms wiki markup into
682 * HTML. Only called for $mOutputType == OT_HTML.
683 *
684 * @access private
685 */
686 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
687 global $wgContLang;
688
689 $fname = 'Parser::internalParse';
690 wfProfileIn( $fname );
691
692 $text = $this->removeHTMLtags( $text );
693 $text = $this->replaceVariables( $text, $args );
694
695 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
696
697 $text = $this->doHeadings( $text );
698 if($this->mOptions->getUseDynamicDates()) {
699 global $wgDateFormatter;
700 $text = $wgDateFormatter->reformat( $this->mOptions->getDateFormat(), $text );
701 }
702 $text = $this->doAllQuotes( $text );
703 $text = $this->replaceInternalLinks( $text );
704 $text = $this->replaceExternalLinks( $text );
705
706 # replaceInternalLinks may sometimes leave behind
707 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
708 $text = str_replace("http-noparse://","http://",$text);
709
710 $text = $this->doMagicLinks( $text );
711 $text = $this->doTableStuff( $text );
712 $text = $this->formatHeadings( $text, $isMain );
713 $sk =& $this->mOptions->getSkin();
714 $text = $sk->transformContent( $text );
715
716 wfProfileOut( $fname );
717 return $text;
718 }
719
720 /**
721 * Replace special strings like "ISBN xxx" and "RFC xxx" with
722 * magic external links.
723 *
724 * @access private
725 */
726 function &doMagicLinks( &$text ) {
727 global $wgUseGeoMode;
728 $text = $this->magicISBN( $text );
729 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
730 $text = $this->magicGEO( $text );
731 }
732 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
733 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
734 return $text;
735 }
736
737 /**
738 * Parse ^^ tokens and return html
739 *
740 * @access private
741 */
742 function doExponent( $text ) {
743 $fname = 'Parser::doExponent';
744 wfProfileIn( $fname );
745 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
746 wfProfileOut( $fname );
747 return $text;
748 }
749
750 /**
751 * Parse headers and return html
752 *
753 * @access private
754 */
755 function doHeadings( $text ) {
756 $fname = 'Parser::doHeadings';
757 wfProfileIn( $fname );
758 for ( $i = 6; $i >= 1; --$i ) {
759 $h = substr( '======', 0, $i );
760 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
761 "<h{$i}>\\1</h{$i}>\\2", $text );
762 }
763 wfProfileOut( $fname );
764 return $text;
765 }
766
767 /**
768 * Replace single quotes with HTML markup
769 * @access private
770 * @return string the altered text
771 */
772 function doAllQuotes( $text ) {
773 $fname = 'Parser::doAllQuotes';
774 wfProfileIn( $fname );
775 $outtext = '';
776 $lines = explode( "\n", $text );
777 foreach ( $lines as $line ) {
778 $outtext .= $this->doQuotes ( $line ) . "\n";
779 }
780 $outtext = substr($outtext, 0,-1);
781 wfProfileOut( $fname );
782 return $outtext;
783 }
784
785 /**
786 * Helper function for doAllQuotes()
787 * @access private
788 */
789 function doQuotes( $text ) {
790 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
791 if ( count( $arr ) == 1 )
792 return $text;
793 else
794 {
795 # First, do some preliminary work. This may shift some apostrophes from
796 # being mark-up to being text. It also counts the number of occurrences
797 # of bold and italics mark-ups.
798 $i = 0;
799 $numbold = 0;
800 $numitalics = 0;
801 foreach ( $arr as $r )
802 {
803 if ( ( $i % 2 ) == 1 )
804 {
805 # If there are ever four apostrophes, assume the first is supposed to
806 # be text, and the remaining three constitute mark-up for bold text.
807 if ( strlen( $arr[$i] ) == 4 )
808 {
809 $arr[$i-1] .= "'";
810 $arr[$i] = "'''";
811 }
812 # If there are more than 5 apostrophes in a row, assume they're all
813 # text except for the last 5.
814 else if ( strlen( $arr[$i] ) > 5 )
815 {
816 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
817 $arr[$i] = "'''''";
818 }
819 # Count the number of occurrences of bold and italics mark-ups.
820 # We are not counting sequences of five apostrophes.
821 if ( strlen( $arr[$i] ) == 2 ) $numitalics++; else
822 if ( strlen( $arr[$i] ) == 3 ) $numbold++; else
823 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
824 }
825 $i++;
826 }
827
828 # If there is an odd number of both bold and italics, it is likely
829 # that one of the bold ones was meant to be an apostrophe followed
830 # by italics. Which one we cannot know for certain, but it is more
831 # likely to be one that has a single-letter word before it.
832 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
833 {
834 $i = 0;
835 $firstsingleletterword = -1;
836 $firstmultiletterword = -1;
837 $firstspace = -1;
838 foreach ( $arr as $r )
839 {
840 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
841 {
842 $x1 = substr ($arr[$i-1], -1);
843 $x2 = substr ($arr[$i-1], -2, 1);
844 if ($x1 == ' ') {
845 if ($firstspace == -1) $firstspace = $i;
846 } else if ($x2 == ' ') {
847 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
848 } else {
849 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
850 }
851 }
852 $i++;
853 }
854
855 # If there is a single-letter word, use it!
856 if ($firstsingleletterword > -1)
857 {
858 $arr [ $firstsingleletterword ] = "''";
859 $arr [ $firstsingleletterword-1 ] .= "'";
860 }
861 # If not, but there's a multi-letter word, use that one.
862 else if ($firstmultiletterword > -1)
863 {
864 $arr [ $firstmultiletterword ] = "''";
865 $arr [ $firstmultiletterword-1 ] .= "'";
866 }
867 # ... otherwise use the first one that has neither.
868 # (notice that it is possible for all three to be -1 if, for example,
869 # there is only one pentuple-apostrophe in the line)
870 else if ($firstspace > -1)
871 {
872 $arr [ $firstspace ] = "''";
873 $arr [ $firstspace-1 ] .= "'";
874 }
875 }
876
877 # Now let's actually convert our apostrophic mush to HTML!
878 $output = '';
879 $buffer = '';
880 $state = '';
881 $i = 0;
882 foreach ($arr as $r)
883 {
884 if (($i % 2) == 0)
885 {
886 if ($state == 'both')
887 $buffer .= $r;
888 else
889 $output .= $r;
890 }
891 else
892 {
893 if (strlen ($r) == 2)
894 {
895 if ($state == 'i')
896 { $output .= '</i>'; $state = ''; }
897 else if ($state == 'bi')
898 { $output .= '</i>'; $state = 'b'; }
899 else if ($state == 'ib')
900 { $output .= '</b></i><b>'; $state = 'b'; }
901 else if ($state == 'both')
902 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
903 else # $state can be 'b' or ''
904 { $output .= '<i>'; $state .= 'i'; }
905 }
906 else if (strlen ($r) == 3)
907 {
908 if ($state == 'b')
909 { $output .= '</b>'; $state = ''; }
910 else if ($state == 'bi')
911 { $output .= '</i></b><i>'; $state = 'i'; }
912 else if ($state == 'ib')
913 { $output .= '</b>'; $state = 'i'; }
914 else if ($state == 'both')
915 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
916 else # $state can be 'i' or ''
917 { $output .= '<b>'; $state .= 'b'; }
918 }
919 else if (strlen ($r) == 5)
920 {
921 if ($state == 'b')
922 { $output .= '</b><i>'; $state = 'i'; }
923 else if ($state == 'i')
924 { $output .= '</i><b>'; $state = 'b'; }
925 else if ($state == 'bi')
926 { $output .= '</i></b>'; $state = ''; }
927 else if ($state == 'ib')
928 { $output .= '</b></i>'; $state = ''; }
929 else if ($state == 'both')
930 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
931 else # ($state == '')
932 { $buffer = ''; $state = 'both'; }
933 }
934 }
935 $i++;
936 }
937 # Now close all remaining tags. Notice that the order is important.
938 if ($state == 'b' || $state == 'ib')
939 $output .= '</b>';
940 if ($state == 'i' || $state == 'bi' || $state == 'ib')
941 $output .= '</i>';
942 if ($state == 'bi')
943 $output .= '</b>';
944 if ($state == 'both')
945 $output .= '<b><i>'.$buffer.'</i></b>';
946 return $output;
947 }
948 }
949
950 /**
951 * Replace external links
952 *
953 * Note: this is all very hackish and the order of execution matters a lot.
954 * Make sure to run maintenance/parserTests.php if you change this code.
955 *
956 * @access private
957 */
958 function replaceExternalLinks( $text ) {
959 $fname = 'Parser::replaceExternalLinks';
960 wfProfileIn( $fname );
961
962 $sk =& $this->mOptions->getSkin();
963 $linktrail = wfMsgForContent('linktrail');
964 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
965
966 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
967
968 $i = 0;
969 while ( $i<count( $bits ) ) {
970 $url = $bits[$i++];
971 $protocol = $bits[$i++];
972 $text = $bits[$i++];
973 $trail = $bits[$i++];
974
975 # The characters '<' and '>' (which were escaped by
976 # removeHTMLtags()) should not be included in
977 # URLs, per RFC 2396.
978 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
979 $text = substr($url, $m2[0][1]) . ' ' . $text;
980 $url = substr($url, 0, $m2[0][1]);
981 }
982
983 # If the link text is an image URL, replace it with an <img> tag
984 # This happened by accident in the original parser, but some people used it extensively
985 $img = $this->maybeMakeImageLink( $text );
986 if ( $img !== false ) {
987 $text = $img;
988 }
989
990 $dtrail = '';
991
992 # No link text, e.g. [http://domain.tld/some.link]
993 if ( $text == '' ) {
994 # Autonumber if allowed
995 if ( strpos( HTTP_PROTOCOLS, $protocol ) !== false ) {
996 $text = '[' . ++$this->mAutonumber . ']';
997 } else {
998 # Otherwise just use the URL
999 $text = htmlspecialchars( $url );
1000 }
1001 } else {
1002 # Have link text, e.g. [http://domain.tld/some.link text]s
1003 # Check for trail
1004 if ( preg_match( $linktrail, $trail, $m2 ) ) {
1005 $dtrail = $m2[1];
1006 $trail = $m2[2];
1007 }
1008 }
1009
1010 $encUrl = htmlspecialchars( $url );
1011 # Bit in parentheses showing the URL for the printable version
1012 if( $url == $text || preg_match( "!$protocol://" . preg_quote( $text, '/' ) . "/?$!", $url ) ) {
1013 $paren = '';
1014 } else {
1015 # Expand the URL for printable version
1016 if ( ! $sk->suppressUrlExpansion() ) {
1017 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
1018 } else {
1019 $paren = '';
1020 }
1021 }
1022
1023 # Process the trail (i.e. everything after this link up until start of the next link),
1024 # replacing any non-bracketed links
1025 $trail = $this->replaceFreeExternalLinks( $trail );
1026
1027 # Use the encoded URL
1028 # This means that users can paste URLs directly into the text
1029 # Funny characters like &ouml; aren't valid in URLs anyway
1030 # This was changed in August 2004
1031 $s .= $sk->makeExternalLink( $url, $text, false ) . $dtrail. $paren . $trail;
1032 }
1033
1034 wfProfileOut( $fname );
1035 return $s;
1036 }
1037
1038 /**
1039 * Replace anything that looks like a URL with a link
1040 * @access private
1041 */
1042 function replaceFreeExternalLinks( $text ) {
1043 $fname = 'Parser::replaceFreeExternalLinks';
1044 wfProfileIn( $fname );
1045
1046 $bits = preg_split( '/((?:'.URL_PROTOCOLS.'):)/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1047 $s = array_shift( $bits );
1048 $i = 0;
1049
1050 $sk =& $this->mOptions->getSkin();
1051
1052 while ( $i < count( $bits ) ){
1053 $protocol = $bits[$i++];
1054 $remainder = $bits[$i++];
1055
1056 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1057 # Found some characters after the protocol that look promising
1058 $url = $protocol . $m[1];
1059 $trail = $m[2];
1060
1061 # The characters '<' and '>' (which were escaped by
1062 # removeHTMLtags()) should not be included in
1063 # URLs, per RFC 2396.
1064 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1065 $trail = substr($url, $m2[0][1]) . $trail;
1066 $url = substr($url, 0, $m2[0][1]);
1067 }
1068
1069 # Move trailing punctuation to $trail
1070 $sep = ',;\.:!?';
1071 # If there is no left bracket, then consider right brackets fair game too
1072 if ( strpos( $url, '(' ) === false ) {
1073 $sep .= ')';
1074 }
1075
1076 $numSepChars = strspn( strrev( $url ), $sep );
1077 if ( $numSepChars ) {
1078 $trail = substr( $url, -$numSepChars ) . $trail;
1079 $url = substr( $url, 0, -$numSepChars );
1080 }
1081
1082 # Replace &amp; from obsolete syntax with &.
1083 # All HTML entities will be escaped by makeExternalLink()
1084 # or maybeMakeImageLink()
1085 $url = str_replace( '&amp;', '&', $url );
1086
1087 # Is this an external image?
1088 $text = $this->maybeMakeImageLink( $url );
1089 if ( $text === false ) {
1090 # Not an image, make a link
1091 $text = $sk->makeExternalLink( $url, $url );
1092 }
1093 $s .= $text . $trail;
1094 } else {
1095 $s .= $protocol . $remainder;
1096 }
1097 }
1098 wfProfileOut();
1099 return $s;
1100 }
1101
1102 /**
1103 * make an image if it's allowed
1104 * @access private
1105 */
1106 function maybeMakeImageLink( $url ) {
1107 $sk =& $this->mOptions->getSkin();
1108 $text = false;
1109 if ( $this->mOptions->getAllowExternalImages() ) {
1110 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1111 # Image found
1112 $text = $sk->makeImage( htmlspecialchars( $url ) );
1113 }
1114 }
1115 return $text;
1116 }
1117
1118 /**
1119 * Process [[ ]] wikilinks
1120 *
1121 * @access private
1122 */
1123
1124 function replaceInternalLinks( $s ) {
1125 global $wgLang, $wgContLang, $wgLinkCache;
1126 global $wgDisableLangConversion;
1127 static $fname = 'Parser::replaceInternalLinks' ;
1128
1129 wfProfileIn( $fname );
1130
1131 wfProfileIn( $fname.'-setup' );
1132 static $tc = FALSE;
1133 # the % is needed to support urlencoded titles as well
1134 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1135
1136 $sk =& $this->mOptions->getSkin();
1137 global $wgUseOldExistenceCheck;
1138 # "Post-parse link colour check" works only on wiki text since it's now
1139 # in Parser. Enable it, then disable it when we're done.
1140 $saveParseColour = $sk->postParseLinkColour( !$wgUseOldExistenceCheck );
1141
1142 $redirect = MagicWord::get ( MAG_REDIRECT ) ;
1143
1144 #split the entire text string on occurences of [[
1145 $a = explode( '[[', ' ' . $s );
1146 #get the first element (all text up to first [[), and remove the space we added
1147 $s = array_shift( $a );
1148 $s = substr( $s, 1 );
1149
1150 # Match a link having the form [[namespace:link|alternate]]trail
1151 static $e1 = FALSE;
1152 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1153 # Match cases where there is no "]]", which might still be images
1154 static $e1_img = FALSE;
1155 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1156 # Match the end of a line for a word that's not followed by whitespace,
1157 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1158 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1159
1160 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1161
1162 $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
1163
1164 if ( $useLinkPrefixExtension ) {
1165 if ( preg_match( $e2, $s, $m ) ) {
1166 $first_prefix = $m[2];
1167 $s = $m[1];
1168 } else {
1169 $first_prefix = false;
1170 }
1171 } else {
1172 $prefix = '';
1173 }
1174
1175 $selflink = $this->mTitle->getPrefixedText();
1176 wfProfileOut( $fname.'-setup' );
1177
1178 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1179 $useSubpages = $this->areSubpagesAllowed();
1180
1181 # Loop for each link
1182 for ($k = 0; isset( $a[$k] ); $k++) {
1183 $line = $a[$k];
1184 if ( $useLinkPrefixExtension ) {
1185 wfProfileIn( $fname.'-prefixhandling' );
1186 if ( preg_match( $e2, $s, $m ) ) {
1187 $prefix = $m[2];
1188 $s = $m[1];
1189 } else {
1190 $prefix='';
1191 }
1192 # first link
1193 if($first_prefix) {
1194 $prefix = $first_prefix;
1195 $first_prefix = false;
1196 }
1197 wfProfileOut( $fname.'-prefixhandling' );
1198 }
1199
1200 $might_be_img = false;
1201
1202 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1203 $text = $m[2];
1204 # fix up urlencoded title texts
1205 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1206 $trail = $m[3];
1207 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1208 $might_be_img = true;
1209 $text = $m[2];
1210 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1211 $trail = "";
1212 } else { # Invalid form; output directly
1213 $s .= $prefix . '[[' . $line ;
1214 continue;
1215 }
1216
1217 # Don't allow internal links to pages containing
1218 # PROTO: where PROTO is a valid URL protocol; these
1219 # should be external links.
1220 if (preg_match('/^((?:'.URL_PROTOCOLS.'):)/', $m[1])) {
1221 $s .= $prefix . '[[' . $line ;
1222 continue;
1223 }
1224
1225 # Make subpage if necessary
1226 if( $useSubpages ) {
1227 $link = $this->maybeDoSubpageLink( $m[1], $text );
1228 } else {
1229 $link = $m[1];
1230 }
1231
1232 $noforce = (substr($m[1], 0, 1) != ':');
1233 if (!$noforce) {
1234 # Strip off leading ':'
1235 $link = substr($link, 1);
1236 }
1237
1238 $nt =& Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1239 if( !$nt ) {
1240 $s .= $prefix . '[[' . $line;
1241 continue;
1242 }
1243
1244 #check other language variants of the link
1245 #if the article does not exist
1246 if( $checkVariantLink
1247 && $nt->getArticleID() == 0 ) {
1248 $wgContLang->findVariantLink($link, $nt);
1249 }
1250
1251 $ns = $nt->getNamespace();
1252 $iw = $nt->getInterWiki();
1253
1254 if ($might_be_img) { # if this is actually an invalid link
1255 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1256 $found = false;
1257 while (isset ($a[$k+1]) ) {
1258 #look at the next 'line' to see if we can close it there
1259 $next_line = array_shift(array_splice( $a, $k + 1, 1) );
1260 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1261 # the first ]] closes the inner link, the second the image
1262 $found = true;
1263 $text .= '[[' . $m[1];
1264 $trail = $m[2];
1265 break;
1266 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1267 #if there's exactly one ]] that's fine, we'll keep looking
1268 $text .= '[[' . $m[0];
1269 } else {
1270 #if $next_line is invalid too, we need look no further
1271 $text .= '[[' . $next_line;
1272 break;
1273 }
1274 }
1275 if ( !$found ) {
1276 # we couldn't find the end of this imageLink, so output it raw
1277 #but don't ignore what might be perfectly normal links in the text we've examined
1278 $text = $this->replaceInternalLinks($text);
1279 $s .= $prefix . '[[' . $link . '|' . $text;
1280 # note: no $trail, because without an end, there *is* no trail
1281 continue;
1282 }
1283 } else { #it's not an image, so output it raw
1284 $s .= $prefix . '[[' . $link . '|' . $text;
1285 # note: no $trail, because without an end, there *is* no trail
1286 continue;
1287 }
1288 }
1289
1290 $wasblank = ( '' == $text );
1291 if( $wasblank ) $text = $link;
1292
1293
1294 # Link not escaped by : , create the various objects
1295 if( $noforce ) {
1296
1297 # Interwikis
1298 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1299 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1300 $tmp = $prefix . $trail ;
1301 $s .= (trim($tmp) == '')? '': $tmp;
1302 continue;
1303 }
1304
1305 if ( $ns == NS_IMAGE ) {
1306 wfProfileIn( "$fname-image" );
1307
1308 # recursively parse links inside the image caption
1309 # actually, this will parse them in any other parameters, too,
1310 # but it might be hard to fix that, and it doesn't matter ATM
1311 $text = $this->replaceExternalLinks($text);
1312 $text = $this->replaceInternalLinks($text);
1313
1314 # replace the image with a link-holder so that replaceExternalLinks() can't mess with it
1315 $s .= $prefix . $this->insertStripItem( $sk->makeImageLinkObj( $nt, $text ), $this->mStripState ) . $trail;
1316 $wgLinkCache->addImageLinkObj( $nt );
1317
1318 wfProfileOut( "$fname-image" );
1319 continue;
1320 }
1321
1322 if ( $ns == NS_CATEGORY ) {
1323 wfProfileIn( "$fname-category" );
1324 $t = $nt->getText();
1325
1326 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1327 $pPLC=$sk->postParseLinkColour();
1328 $sk->postParseLinkColour( false );
1329 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1330 $sk->postParseLinkColour( $pPLC );
1331 $wgLinkCache->resume();
1332
1333 if ( $wasblank ) {
1334 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1335 $sortkey = $this->mTitle->getText();
1336 } else {
1337 $sortkey = $this->mTitle->getPrefixedText();
1338 }
1339 } else {
1340 $sortkey = $text;
1341 }
1342 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1343 $this->mOutput->addCategoryLink( $t );
1344 $s .= $prefix . $trail ;
1345
1346 wfProfileOut( "$fname-category" );
1347 continue;
1348 }
1349 }
1350
1351 if( ( $nt->getPrefixedText() === $selflink ) &&
1352 ( $nt->getFragment() === '' ) ) {
1353 # Self-links are handled specially; generally de-link and change to bold.
1354 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1355 continue;
1356 }
1357
1358 # Special and Media are pseudo-namespaces; no pages actually exist in them
1359 if( $ns == NS_MEDIA ) {
1360 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1361 $wgLinkCache->addImageLinkObj( $nt );
1362 continue;
1363 } elseif( $ns == NS_SPECIAL ) {
1364 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1365 continue;
1366 }
1367 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1368 }
1369 $sk->postParseLinkColour( $saveParseColour );
1370 wfProfileOut( $fname );
1371 return $s;
1372 }
1373
1374 /**
1375 * Return true if subpage links should be expanded on this page.
1376 * @return bool
1377 */
1378 function areSubpagesAllowed() {
1379 # Some namespaces don't allow subpages
1380 global $wgNamespacesWithSubpages;
1381 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1382 }
1383
1384 /**
1385 * Handle link to subpage if necessary
1386 * @param string $target the source of the link
1387 * @param string &$text the link text, modified as necessary
1388 * @return string the full name of the link
1389 * @access private
1390 */
1391 function maybeDoSubpageLink($target, &$text) {
1392 # Valid link forms:
1393 # Foobar -- normal
1394 # :Foobar -- override special treatment of prefix (images, language links)
1395 # /Foobar -- convert to CurrentPage/Foobar
1396 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1397
1398 $fname = 'Parser::maybeDoSubpageLink';
1399 wfProfileIn( $fname );
1400 # Look at the first character
1401 if( $target != '' && $target{0} == '/' ) {
1402 # / at end means we don't want the slash to be shown
1403 if(substr($target,-1,1)=='/') {
1404 $target=substr($target,1,-1);
1405 $noslash=$target;
1406 } else {
1407 $noslash=substr($target,1);
1408 }
1409
1410 # Some namespaces don't allow subpages
1411 if( $this->areSubpagesAllowed() ) {
1412 # subpages allowed here
1413 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1414 if( '' === $text ) {
1415 $text = $target;
1416 } # this might be changed for ugliness reasons
1417 } else {
1418 # no subpage allowed, use standard link
1419 $ret = $target;
1420 }
1421 } else {
1422 # no subpage
1423 $ret = $target;
1424 }
1425
1426 wfProfileOut( $fname );
1427 return $ret;
1428 }
1429
1430 /**#@+
1431 * Used by doBlockLevels()
1432 * @access private
1433 */
1434 /* private */ function closeParagraph() {
1435 $result = '';
1436 if ( '' != $this->mLastSection ) {
1437 $result = '</' . $this->mLastSection . ">\n";
1438 }
1439 $this->mInPre = false;
1440 $this->mLastSection = '';
1441 return $result;
1442 }
1443 # getCommon() returns the length of the longest common substring
1444 # of both arguments, starting at the beginning of both.
1445 #
1446 /* private */ function getCommon( $st1, $st2 ) {
1447 $fl = strlen( $st1 );
1448 $shorter = strlen( $st2 );
1449 if ( $fl < $shorter ) { $shorter = $fl; }
1450
1451 for ( $i = 0; $i < $shorter; ++$i ) {
1452 if ( $st1{$i} != $st2{$i} ) { break; }
1453 }
1454 return $i;
1455 }
1456 # These next three functions open, continue, and close the list
1457 # element appropriate to the prefix character passed into them.
1458 #
1459 /* private */ function openList( $char ) {
1460 $result = $this->closeParagraph();
1461
1462 if ( '*' == $char ) { $result .= '<ul><li>'; }
1463 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1464 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1465 else if ( ';' == $char ) {
1466 $result .= '<dl><dt>';
1467 $this->mDTopen = true;
1468 }
1469 else { $result = '<!-- ERR 1 -->'; }
1470
1471 return $result;
1472 }
1473
1474 /* private */ function nextItem( $char ) {
1475 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1476 else if ( ':' == $char || ';' == $char ) {
1477 $close = '</dd>';
1478 if ( $this->mDTopen ) { $close = '</dt>'; }
1479 if ( ';' == $char ) {
1480 $this->mDTopen = true;
1481 return $close . '<dt>';
1482 } else {
1483 $this->mDTopen = false;
1484 return $close . '<dd>';
1485 }
1486 }
1487 return '<!-- ERR 2 -->';
1488 }
1489
1490 /* private */ function closeList( $char ) {
1491 if ( '*' == $char ) { $text = '</li></ul>'; }
1492 else if ( '#' == $char ) { $text = '</li></ol>'; }
1493 else if ( ':' == $char ) {
1494 if ( $this->mDTopen ) {
1495 $this->mDTopen = false;
1496 $text = '</dt></dl>';
1497 } else {
1498 $text = '</dd></dl>';
1499 }
1500 }
1501 else { return '<!-- ERR 3 -->'; }
1502 return $text."\n";
1503 }
1504 /**#@-*/
1505
1506 /**
1507 * Make lists from lines starting with ':', '*', '#', etc.
1508 *
1509 * @access private
1510 * @return string the lists rendered as HTML
1511 */
1512 function doBlockLevels( $text, $linestart ) {
1513 $fname = 'Parser::doBlockLevels';
1514 wfProfileIn( $fname );
1515
1516 # Parsing through the text line by line. The main thing
1517 # happening here is handling of block-level elements p, pre,
1518 # and making lists from lines starting with * # : etc.
1519 #
1520 $textLines = explode( "\n", $text );
1521
1522 $lastPrefix = $output = $lastLine = '';
1523 $this->mDTopen = $inBlockElem = false;
1524 $prefixLength = 0;
1525 $paragraphStack = false;
1526
1527 if ( !$linestart ) {
1528 $output .= array_shift( $textLines );
1529 }
1530 foreach ( $textLines as $oLine ) {
1531 $lastPrefixLength = strlen( $lastPrefix );
1532 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1533 $preOpenMatch = preg_match('/<pre/i', $oLine );
1534 if ( !$this->mInPre ) {
1535 # Multiple prefixes may abut each other for nested lists.
1536 $prefixLength = strspn( $oLine, '*#:;' );
1537 $pref = substr( $oLine, 0, $prefixLength );
1538
1539 # eh?
1540 $pref2 = str_replace( ';', ':', $pref );
1541 $t = substr( $oLine, $prefixLength );
1542 $this->mInPre = !empty($preOpenMatch);
1543 } else {
1544 # Don't interpret any other prefixes in preformatted text
1545 $prefixLength = 0;
1546 $pref = $pref2 = '';
1547 $t = $oLine;
1548 }
1549
1550 # List generation
1551 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1552 # Same as the last item, so no need to deal with nesting or opening stuff
1553 $output .= $this->nextItem( substr( $pref, -1 ) );
1554 $paragraphStack = false;
1555
1556 if ( substr( $pref, -1 ) == ';') {
1557 # The one nasty exception: definition lists work like this:
1558 # ; title : definition text
1559 # So we check for : in the remainder text to split up the
1560 # title and definition, without b0rking links.
1561 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1562 $t = $t2;
1563 $output .= $term . $this->nextItem( ':' );
1564 }
1565 }
1566 } elseif( $prefixLength || $lastPrefixLength ) {
1567 # Either open or close a level...
1568 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1569 $paragraphStack = false;
1570
1571 while( $commonPrefixLength < $lastPrefixLength ) {
1572 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1573 --$lastPrefixLength;
1574 }
1575 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1576 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1577 }
1578 while ( $prefixLength > $commonPrefixLength ) {
1579 $char = substr( $pref, $commonPrefixLength, 1 );
1580 $output .= $this->openList( $char );
1581
1582 if ( ';' == $char ) {
1583 # FIXME: This is dupe of code above
1584 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1585 $t = $t2;
1586 $output .= $term . $this->nextItem( ':' );
1587 }
1588 }
1589 ++$commonPrefixLength;
1590 }
1591 $lastPrefix = $pref2;
1592 }
1593 if( 0 == $prefixLength ) {
1594 wfProfileIn( "$fname-paragraph" );
1595 # No prefix (not in list)--go to paragraph mode
1596 $uniq_prefix = UNIQ_PREFIX;
1597 // XXX: use a stack for nestable elements like span, table and div
1598 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1599 $closematch = preg_match(
1600 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1601 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1602 if ( $openmatch or $closematch ) {
1603 $paragraphStack = false;
1604 $output .= $this->closeParagraph();
1605 if($preOpenMatch and !$preCloseMatch) {
1606 $this->mInPre = true;
1607 }
1608 if ( $closematch ) {
1609 $inBlockElem = false;
1610 } else {
1611 $inBlockElem = true;
1612 }
1613 } else if ( !$inBlockElem && !$this->mInPre ) {
1614 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1615 // pre
1616 if ($this->mLastSection != 'pre') {
1617 $paragraphStack = false;
1618 $output .= $this->closeParagraph().'<pre>';
1619 $this->mLastSection = 'pre';
1620 }
1621 $t = substr( $t, 1 );
1622 } else {
1623 // paragraph
1624 if ( '' == trim($t) ) {
1625 if ( $paragraphStack ) {
1626 $output .= $paragraphStack.'<br />';
1627 $paragraphStack = false;
1628 $this->mLastSection = 'p';
1629 } else {
1630 if ($this->mLastSection != 'p' ) {
1631 $output .= $this->closeParagraph();
1632 $this->mLastSection = '';
1633 $paragraphStack = '<p>';
1634 } else {
1635 $paragraphStack = '</p><p>';
1636 }
1637 }
1638 } else {
1639 if ( $paragraphStack ) {
1640 $output .= $paragraphStack;
1641 $paragraphStack = false;
1642 $this->mLastSection = 'p';
1643 } else if ($this->mLastSection != 'p') {
1644 $output .= $this->closeParagraph().'<p>';
1645 $this->mLastSection = 'p';
1646 }
1647 }
1648 }
1649 }
1650 wfProfileOut( "$fname-paragraph" );
1651 }
1652 if ($paragraphStack === false) {
1653 $output .= $t."\n";
1654 }
1655 }
1656 while ( $prefixLength ) {
1657 $output .= $this->closeList( $pref2{$prefixLength-1} );
1658 --$prefixLength;
1659 }
1660 if ( '' != $this->mLastSection ) {
1661 $output .= '</' . $this->mLastSection . '>';
1662 $this->mLastSection = '';
1663 }
1664
1665 wfProfileOut( $fname );
1666 return $output;
1667 }
1668
1669 /**
1670 * Split up a string on ':', ignoring any occurences inside
1671 * <a>..</a> or <span>...</span>
1672 * @param string $str the string to split
1673 * @param string &$before set to everything before the ':'
1674 * @param string &$after set to everything after the ':'
1675 * return string the position of the ':', or false if none found
1676 */
1677 function findColonNoLinks($str, &$before, &$after) {
1678 # I wonder if we should make this count all tags, not just <a>
1679 # and <span>. That would prevent us from matching a ':' that
1680 # comes in the middle of italics other such formatting....
1681 # -- Wil
1682 $fname = 'Parser::findColonNoLinks';
1683 wfProfileIn( $fname );
1684 $pos = 0;
1685 do {
1686 $colon = strpos($str, ':', $pos);
1687
1688 if ($colon !== false) {
1689 $before = substr($str, 0, $colon);
1690 $after = substr($str, $colon + 1);
1691
1692 # Skip any ':' within <a> or <span> pairs
1693 $a = substr_count($before, '<a');
1694 $s = substr_count($before, '<span');
1695 $ca = substr_count($before, '</a>');
1696 $cs = substr_count($before, '</span>');
1697
1698 if ($a <= $ca and $s <= $cs) {
1699 # Tags are balanced before ':'; ok
1700 break;
1701 }
1702 $pos = $colon + 1;
1703 }
1704 } while ($colon !== false);
1705 wfProfileOut( $fname );
1706 return $colon;
1707 }
1708
1709 /**
1710 * Return value of a magic variable (like PAGENAME)
1711 *
1712 * @access private
1713 */
1714 function getVariableValue( $index ) {
1715 global $wgContLang, $wgSitename, $wgServer;
1716
1717 /**
1718 * Some of these require message or data lookups and can be
1719 * expensive to check many times.
1720 */
1721 static $varCache = array();
1722 if( isset( $varCache[$index] ) ) return $varCache[$index];
1723
1724 switch ( $index ) {
1725 case MAG_CURRENTMONTH:
1726 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1727 case MAG_CURRENTMONTHNAME:
1728 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1729 case MAG_CURRENTMONTHNAMEGEN:
1730 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1731 case MAG_CURRENTDAY:
1732 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1733 case MAG_PAGENAME:
1734 return $this->mTitle->getText();
1735 case MAG_PAGENAMEE:
1736 return $this->mTitle->getPartialURL();
1737 case MAG_NAMESPACE:
1738 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1739 return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1740 case MAG_CURRENTDAYNAME:
1741 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1742 case MAG_CURRENTYEAR:
1743 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1744 case MAG_CURRENTTIME:
1745 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1746 case MAG_NUMBEROFARTICLES:
1747 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1748 case MAG_SITENAME:
1749 return $wgSitename;
1750 case MAG_SERVER:
1751 return $wgServer;
1752 default:
1753 return NULL;
1754 }
1755 }
1756
1757 /**
1758 * initialise the magic variables (like CURRENTMONTHNAME)
1759 *
1760 * @access private
1761 */
1762 function initialiseVariables() {
1763 $fname = 'Parser::initialiseVariables';
1764 wfProfileIn( $fname );
1765 global $wgVariableIDs;
1766 $this->mVariables = array();
1767 foreach ( $wgVariableIDs as $id ) {
1768 $mw =& MagicWord::get( $id );
1769 $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
1770 }
1771 wfProfileOut( $fname );
1772 }
1773
1774 /**
1775 * Replace magic variables, templates, and template arguments
1776 * with the appropriate text. Templates are substituted recursively,
1777 * taking care to avoid infinite loops.
1778 *
1779 * Note that the substitution depends on value of $mOutputType:
1780 * OT_WIKI: only {{subst:}} templates
1781 * OT_MSG: only magic variables
1782 * OT_HTML: all templates and magic variables
1783 *
1784 * @param string $tex The text to transform
1785 * @param array $args Key-value pairs representing template parameters to substitute
1786 * @access private
1787 */
1788 function replaceVariables( $text, $args = array() ) {
1789 global $wgLang, $wgScript, $wgArticlePath;
1790
1791 # Prevent too big inclusions
1792 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
1793 return $text;
1794 }
1795
1796 $fname = 'Parser::replaceVariables';
1797 wfProfileIn( $fname );
1798
1799 $titleChars = Title::legalChars();
1800
1801 # This function is called recursively. To keep track of arguments we need a stack:
1802 array_push( $this->mArgStack, $args );
1803
1804 # Variable substitution
1805 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1806
1807 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
1808 # Argument substitution
1809 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1810 }
1811 # Template substitution
1812 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1813 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1814
1815 array_pop( $this->mArgStack );
1816
1817 wfProfileOut( $fname );
1818 return $text;
1819 }
1820
1821 /**
1822 * Replace magic variables
1823 * @access private
1824 */
1825 function variableSubstitution( $matches ) {
1826 if ( !$this->mVariables ) {
1827 $this->initialiseVariables();
1828 }
1829 $skip = false;
1830 if ( $this->mOutputType == OT_WIKI ) {
1831 # Do only magic variables prefixed by SUBST
1832 $mwSubst =& MagicWord::get( MAG_SUBST );
1833 if (!$mwSubst->matchStartAndRemove( $matches[1] ))
1834 $skip = true;
1835 # Note that if we don't substitute the variable below,
1836 # we don't remove the {{subst:}} magic word, in case
1837 # it is a template rather than a magic variable.
1838 }
1839 if ( !$skip && array_key_exists( $matches[1], $this->mVariables ) ) {
1840 $text = $this->mVariables[$matches[1]];
1841 $this->mOutput->mContainsOldMagic = true;
1842 } else {
1843 $text = $matches[0];
1844 }
1845 return $text;
1846 }
1847
1848 # Split template arguments
1849 function getTemplateArgs( $argsString ) {
1850 if ( $argsString === '' ) {
1851 return array();
1852 }
1853
1854 $args = explode( '|', substr( $argsString, 1 ) );
1855
1856 # If any of the arguments contains a '[[' but no ']]', it needs to be
1857 # merged with the next arg because the '|' character between belongs
1858 # to the link syntax and not the template parameter syntax.
1859 $argc = count($args);
1860 $i = 0;
1861 for ( $i = 0; $i < $argc-1; $i++ ) {
1862 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1863 $args[$i] .= '|'.$args[$i+1];
1864 array_splice($args, $i+1, 1);
1865 $i--;
1866 $argc--;
1867 }
1868 }
1869
1870 return $args;
1871 }
1872
1873 /**
1874 * Return the text of a template, after recursively
1875 * replacing any variables or templates within the template.
1876 *
1877 * @param array $matches The parts of the template
1878 * $matches[1]: the title, i.e. the part before the |
1879 * $matches[2]: the parameters (including a leading |), if any
1880 * @return string the text of the template
1881 * @access private
1882 */
1883 function braceSubstitution( $matches ) {
1884 global $wgLinkCache, $wgContLang;
1885 $fname = 'Parser::braceSubstitution';
1886 $found = false;
1887 $nowiki = false;
1888 $noparse = false;
1889
1890 $title = NULL;
1891
1892 # Need to know if the template comes at the start of a line,
1893 # to treat the beginning of the template like the beginning
1894 # of a line for tables and block-level elements.
1895 $linestart = $matches[1];
1896
1897 # $part1 is the bit before the first |, and must contain only title characters
1898 # $args is a list of arguments, starting from index 0, not including $part1
1899
1900 $part1 = $matches[2];
1901 # If the third subpattern matched anything, it will start with |
1902
1903 $args = $this->getTemplateArgs($matches[3]);
1904 $argc = count( $args );
1905
1906 # Don't parse {{{}}} because that's only for template arguments
1907 if ( $linestart === '{' ) {
1908 $text = $matches[0];
1909 $found = true;
1910 $noparse = true;
1911 }
1912
1913 # SUBST
1914 if ( !$found ) {
1915 $mwSubst =& MagicWord::get( MAG_SUBST );
1916 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
1917 # One of two possibilities is true:
1918 # 1) Found SUBST but not in the PST phase
1919 # 2) Didn't find SUBST and in the PST phase
1920 # In either case, return without further processing
1921 $text = $matches[0];
1922 $found = true;
1923 $noparse = true;
1924 }
1925 }
1926
1927 # MSG, MSGNW and INT
1928 if ( !$found ) {
1929 # Check for MSGNW:
1930 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1931 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1932 $nowiki = true;
1933 } else {
1934 # Remove obsolete MSG:
1935 $mwMsg =& MagicWord::get( MAG_MSG );
1936 $mwMsg->matchStartAndRemove( $part1 );
1937 }
1938
1939 # Check if it is an internal message
1940 $mwInt =& MagicWord::get( MAG_INT );
1941 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1942 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1943 $text = $linestart . wfMsgReal( $part1, $args, true );
1944 $found = true;
1945 }
1946 }
1947 }
1948
1949 # NS
1950 if ( !$found ) {
1951 # Check for NS: (namespace expansion)
1952 $mwNs = MagicWord::get( MAG_NS );
1953 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1954 if ( intval( $part1 ) ) {
1955 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1956 $found = true;
1957 } else {
1958 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1959 if ( !is_null( $index ) ) {
1960 $text = $linestart . $wgContLang->getNsText( $index );
1961 $found = true;
1962 }
1963 }
1964 }
1965 }
1966
1967 # LOCALURL and LOCALURLE
1968 if ( !$found ) {
1969 $mwLocal = MagicWord::get( MAG_LOCALURL );
1970 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1971
1972 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1973 $func = 'getLocalURL';
1974 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1975 $func = 'escapeLocalURL';
1976 } else {
1977 $func = '';
1978 }
1979
1980 if ( $func !== '' ) {
1981 $title = Title::newFromText( $part1 );
1982 if ( !is_null( $title ) ) {
1983 if ( $argc > 0 ) {
1984 $text = $linestart . $title->$func( $args[0] );
1985 } else {
1986 $text = $linestart . $title->$func();
1987 }
1988 $found = true;
1989 }
1990 }
1991 }
1992
1993 # GRAMMAR
1994 if ( !$found && $argc == 1 ) {
1995 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
1996 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1997 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
1998 $found = true;
1999 }
2000 }
2001
2002 # Template table test
2003
2004 # Did we encounter this template already? If yes, it is in the cache
2005 # and we need to check for loops.
2006 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
2007 # set $text to cached message.
2008 $text = $linestart . $this->mTemplates[$part1];
2009 $found = true;
2010
2011 # Infinite loop test
2012 if ( isset( $this->mTemplatePath[$part1] ) ) {
2013 $noparse = true;
2014 $found = true;
2015 $text .= '<!-- WARNING: template loop detected -->';
2016 }
2017 }
2018
2019 # Load from database
2020 $itcamefromthedatabase = false;
2021 if ( !$found ) {
2022 $ns = NS_TEMPLATE;
2023 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2024 if ($subpage !== '') {
2025 $ns = $this->mTitle->getNamespace();
2026 }
2027 $title = Title::newFromText( $part1, $ns );
2028 if ( !is_null( $title ) && !$title->isExternal() ) {
2029 # Check for excessive inclusion
2030 $dbk = $title->getPrefixedDBkey();
2031 if ( $this->incrementIncludeCount( $dbk ) ) {
2032 # This should never be reached.
2033 $article = new Article( $title );
2034 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2035 if ( $articleContent !== false ) {
2036 $found = true;
2037 $text = $linestart . $articleContent;
2038 $itcamefromthedatabase = true;
2039 }
2040 }
2041
2042 # If the title is valid but undisplayable, make a link to it
2043 if ( $this->mOutputType == OT_HTML && !$found ) {
2044 $text = $linestart . '[['.$title->getPrefixedText().']]';
2045 $found = true;
2046 }
2047
2048 # Template cache array insertion
2049 $this->mTemplates[$part1] = $text;
2050 }
2051 }
2052
2053 # Recursive parsing, escaping and link table handling
2054 # Only for HTML output
2055 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2056 $text = wfEscapeWikiText( $text );
2057 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2058 # Clean up argument array
2059 $assocArgs = array();
2060 $index = 1;
2061 foreach( $args as $arg ) {
2062 $eqpos = strpos( $arg, '=' );
2063 if ( $eqpos === false ) {
2064 $assocArgs[$index++] = $arg;
2065 } else {
2066 $name = trim( substr( $arg, 0, $eqpos ) );
2067 $value = trim( substr( $arg, $eqpos+1 ) );
2068 if ( $value === false ) {
2069 $value = '';
2070 }
2071 if ( $name !== false ) {
2072 $assocArgs[$name] = $value;
2073 }
2074 }
2075 }
2076
2077 # Add a new element to the templace recursion path
2078 $this->mTemplatePath[$part1] = 1;
2079
2080 $text = $this->strip( $text, $this->mStripState );
2081 $text = $this->removeHTMLtags( $text );
2082 $text = $this->replaceVariables( $text, $assocArgs );
2083
2084 # Resume the link cache and register the inclusion as a link
2085 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2086 $wgLinkCache->addLinkObj( $title );
2087 }
2088
2089 # If the template begins with a table or block-level
2090 # element, it should be treated as beginning a new line.
2091 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2092 $text = "\n" . $text;
2093 }
2094 }
2095
2096 # Empties the template path
2097 $this->mTemplatePath = array();
2098 if ( !$found ) {
2099 return $matches[0];
2100 } else {
2101 # replace ==section headers==
2102 # XXX this needs to go away once we have a better parser.
2103 if ( $this->mOutputType != OT_WIKI && $itcamefromthedatabase ) {
2104 if( !is_null( $title ) )
2105 $encodedname = base64_encode($title->getPrefixedDBkey());
2106 else
2107 $encodedname = base64_encode("");
2108 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2109 PREG_SPLIT_DELIM_CAPTURE);
2110 $text = '';
2111 $nsec = 0;
2112 for( $i = 0; $i < count($m); $i += 2 ) {
2113 $text .= $m[$i];
2114 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2115 $hl = $m[$i + 1];
2116 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2117 $text .= $hl;
2118 continue;
2119 }
2120 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2121 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2122 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2123
2124 $nsec++;
2125 }
2126 }
2127 }
2128
2129 # Empties the template path
2130 $this->mTemplatePath = array();
2131
2132 if ( !$found ) {
2133 return $matches[0];
2134 } else {
2135 return $text;
2136 }
2137 }
2138
2139 /**
2140 * Triple brace replacement -- used for template arguments
2141 * @access private
2142 */
2143 function argSubstitution( $matches ) {
2144 $arg = trim( $matches[1] );
2145 $text = $matches[0];
2146 $inputArgs = end( $this->mArgStack );
2147
2148 if ( array_key_exists( $arg, $inputArgs ) ) {
2149 $text = $inputArgs[$arg];
2150 }
2151
2152 return $text;
2153 }
2154
2155 /**
2156 * Returns true if the function is allowed to include this entity
2157 * @access private
2158 */
2159 function incrementIncludeCount( $dbk ) {
2160 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2161 $this->mIncludeCount[$dbk] = 0;
2162 }
2163 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2164 return true;
2165 } else {
2166 return false;
2167 }
2168 }
2169
2170
2171 /**
2172 * Cleans up HTML, removes dangerous tags and attributes, and
2173 * removes HTML comments
2174 * @access private
2175 */
2176 function removeHTMLtags( $text ) {
2177 global $wgUseTidy, $wgUserHtml;
2178 $fname = 'Parser::removeHTMLtags';
2179 wfProfileIn( $fname );
2180
2181 if( $wgUserHtml ) {
2182 $htmlpairs = array( # Tags that must be closed
2183 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
2184 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
2185 'strike', 'strong', 'tt', 'var', 'div', 'center',
2186 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
2187 'ruby', 'rt' , 'rb' , 'rp', 'p'
2188 );
2189 $htmlsingle = array(
2190 'br', 'hr', 'li', 'dt', 'dd'
2191 );
2192 $htmlnest = array( # Tags that can be nested--??
2193 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
2194 'dl', 'font', 'big', 'small', 'sub', 'sup'
2195 );
2196 $tabletags = array( # Can only appear inside table
2197 'td', 'th', 'tr'
2198 );
2199 } else {
2200 $htmlpairs = array();
2201 $htmlsingle = array();
2202 $htmlnest = array();
2203 $tabletags = array();
2204 }
2205
2206 $htmlsingle = array_merge( $tabletags, $htmlsingle );
2207 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
2208
2209 $htmlattrs = $this->getHTMLattrs () ;
2210
2211 # Remove HTML comments
2212 $text = $this->removeHTMLcomments( $text );
2213
2214 $bits = explode( '<', $text );
2215 $text = array_shift( $bits );
2216 if(!$wgUseTidy) {
2217 $tagstack = array(); $tablestack = array();
2218 foreach ( $bits as $x ) {
2219 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
2220 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2221 $x, $regs );
2222 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2223 error_reporting( $prev );
2224
2225 $badtag = 0 ;
2226 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2227 # Check our stack
2228 if ( $slash ) {
2229 # Closing a tag...
2230 if ( ! in_array( $t, $htmlsingle ) &&
2231 ( $ot = @array_pop( $tagstack ) ) != $t ) {
2232 @array_push( $tagstack, $ot );
2233 $badtag = 1;
2234 } else {
2235 if ( $t == 'table' ) {
2236 $tagstack = array_pop( $tablestack );
2237 }
2238 $newparams = '';
2239 }
2240 } else {
2241 # Keep track for later
2242 if ( in_array( $t, $tabletags ) &&
2243 ! in_array( 'table', $tagstack ) ) {
2244 $badtag = 1;
2245 } else if ( in_array( $t, $tagstack ) &&
2246 ! in_array ( $t , $htmlnest ) ) {
2247 $badtag = 1 ;
2248 } else if ( ! in_array( $t, $htmlsingle ) ) {
2249 if ( $t == 'table' ) {
2250 array_push( $tablestack, $tagstack );
2251 $tagstack = array();
2252 }
2253 array_push( $tagstack, $t );
2254 }
2255 # Strip non-approved attributes from the tag
2256 $newparams = $this->fixTagAttributes($params);
2257
2258 }
2259 if ( ! $badtag ) {
2260 $rest = str_replace( '>', '&gt;', $rest );
2261 $text .= "<$slash$t $newparams$brace$rest";
2262 continue;
2263 }
2264 }
2265 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
2266 }
2267 # Close off any remaining tags
2268 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2269 $text .= "</$t>\n";
2270 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2271 }
2272 } else {
2273 # this might be possible using tidy itself
2274 foreach ( $bits as $x ) {
2275 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2276 $x, $regs );
2277 @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2278 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2279 $newparams = $this->fixTagAttributes($params);
2280 $rest = str_replace( '>', '&gt;', $rest );
2281 $text .= "<$slash$t $newparams$brace$rest";
2282 } else {
2283 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
2284 }
2285 }
2286 }
2287 wfProfileOut( $fname );
2288 return $text;
2289 }
2290
2291 /**
2292 * Remove '<!--', '-->', and everything between.
2293 * To avoid leaving blank lines, when a comment is both preceded
2294 * and followed by a newline (ignoring spaces), trim leading and
2295 * trailing spaces and one of the newlines.
2296 *
2297 * @access private
2298 */
2299 function removeHTMLcomments( $text ) {
2300 $fname='Parser::removeHTMLcomments';
2301 wfProfileIn( $fname );
2302 while (($start = strpos($text, '<!--')) !== false) {
2303 $end = strpos($text, '-->', $start + 4);
2304 if ($end === false) {
2305 # Unterminated comment; bail out
2306 break;
2307 }
2308
2309 $end += 3;
2310
2311 # Trim space and newline if the comment is both
2312 # preceded and followed by a newline
2313 $spaceStart = max($start - 1, 0);
2314 $spaceLen = $end - $spaceStart;
2315 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
2316 $spaceStart--;
2317 $spaceLen++;
2318 }
2319 while (substr($text, $spaceStart + $spaceLen, 1) === ' ')
2320 $spaceLen++;
2321 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart + $spaceLen, 1) === "\n") {
2322 # Remove the comment, leading and trailing
2323 # spaces, and leave only one newline.
2324 $text = substr_replace($text, "\n", $spaceStart, $spaceLen + 1);
2325 }
2326 else {
2327 # Remove just the comment.
2328 $text = substr_replace($text, '', $start, $end - $start);
2329 }
2330 }
2331 wfProfileOut( $fname );
2332 return $text;
2333 }
2334
2335 /**
2336 * This function accomplishes several tasks:
2337 * 1) Auto-number headings if that option is enabled
2338 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2339 * 3) Add a Table of contents on the top for users who have enabled the option
2340 * 4) Auto-anchor headings
2341 *
2342 * It loops through all headlines, collects the necessary data, then splits up the
2343 * string and re-inserts the newly formatted headlines.
2344 * @access private
2345 */
2346 /* private */ function formatHeadings( $text, $isMain=true ) {
2347 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders;
2348
2349 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2350 $doShowToc = $this->mOptions->getShowToc();
2351 $forceTocHere = false;
2352 if( !$this->mTitle->userCanEdit() ) {
2353 $showEditLink = 0;
2354 $rightClickHack = 0;
2355 } else {
2356 $showEditLink = $this->mOptions->getEditSection();
2357 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
2358 }
2359
2360 # Inhibit editsection links if requested in the page
2361 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2362 if( $esw->matchAndRemove( $text ) ) {
2363 $showEditLink = 0;
2364 }
2365 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2366 # do not add TOC
2367 $mw =& MagicWord::get( MAG_NOTOC );
2368 if( $mw->matchAndRemove( $text ) ) {
2369 $doShowToc = 0;
2370 }
2371
2372 # never add the TOC to the Main Page. This is an entry page that should not
2373 # be more than 1-2 screens large anyway
2374 if( $this->mTitle->getPrefixedText() == wfMsg('mainpage') ) {
2375 $doShowToc = 0;
2376 }
2377
2378 # Get all headlines for numbering them and adding funky stuff like [edit]
2379 # links - this is for later, but we need the number of headlines right now
2380 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
2381
2382 # if there are fewer than 4 headlines in the article, do not show TOC
2383 if( $numMatches < 4 ) {
2384 $doShowToc = 0;
2385 }
2386
2387 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2388 # override above conditions and always show TOC at that place
2389 $mw =& MagicWord::get( MAG_TOC );
2390 if ($mw->match( $text ) ) {
2391 $doShowToc = 1;
2392 $forceTocHere = true;
2393 } else {
2394 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2395 # override above conditions and always show TOC above first header
2396 $mw =& MagicWord::get( MAG_FORCETOC );
2397 if ($mw->matchAndRemove( $text ) ) {
2398 $doShowToc = 1;
2399 }
2400 }
2401
2402
2403
2404 # We need this to perform operations on the HTML
2405 $sk =& $this->mOptions->getSkin();
2406
2407 # headline counter
2408 $headlineCount = 0;
2409 $sectionCount = 0; # headlineCount excluding template sections
2410
2411 # Ugh .. the TOC should have neat indentation levels which can be
2412 # passed to the skin functions. These are determined here
2413 $toclevel = 0;
2414 $toc = '';
2415 $full = '';
2416 $head = array();
2417 $sublevelCount = array();
2418 $level = 0;
2419 $prevlevel = 0;
2420 foreach( $matches[3] as $headline ) {
2421 $istemplate = 0;
2422 $templatetitle = "";
2423 $templatesection = 0;
2424
2425 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2426 $istemplate = 1;
2427 $templatetitle = base64_decode($mat[1]);
2428 $templatesection = 1 + (int)base64_decode($mat[2]);
2429 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2430 }
2431
2432 $numbering = '';
2433 if( $level ) {
2434 $prevlevel = $level;
2435 }
2436 $level = $matches[1][$headlineCount];
2437 if( ( $doNumberHeadings || $doShowToc ) && $prevlevel && $level > $prevlevel ) {
2438 # reset when we enter a new level
2439 $sublevelCount[$level] = 0;
2440 $toc .= $sk->tocIndent( $level - $prevlevel );
2441 $toclevel += $level - $prevlevel;
2442 }
2443 if( ( $doNumberHeadings || $doShowToc ) && $level < $prevlevel ) {
2444 # reset when we step back a level
2445 $sublevelCount[$level+1]=0;
2446 $toc .= $sk->tocUnindent( $prevlevel - $level );
2447 $toclevel -= $prevlevel - $level;
2448 }
2449 # count number of headlines for each level
2450 @$sublevelCount[$level]++;
2451 if( $doNumberHeadings || $doShowToc ) {
2452 $dot = 0;
2453 for( $i = 1; $i <= $level; $i++ ) {
2454 if( !empty( $sublevelCount[$i] ) ) {
2455 if( $dot ) {
2456 $numbering .= '.';
2457 }
2458 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2459 $dot = 1;
2460 }
2461 }
2462 }
2463
2464 # The canonized header is a version of the header text safe to use for links
2465 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2466 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2467 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState );
2468
2469 # Remove link placeholders by the link text.
2470 # <!--LINK number-->
2471 # turns into
2472 # link text with suffix
2473 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2474 "\$wgLinkHolders['texts'][\$1]",
2475 $canonized_headline );
2476
2477 # strip out HTML
2478 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2479 $tocline = trim( $canonized_headline );
2480 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
2481 $replacearray = array(
2482 '%3A' => ':',
2483 '%' => '.'
2484 );
2485 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2486 $refer[$headlineCount] = $canonized_headline;
2487
2488 # count how many in assoc. array so we can track dupes in anchors
2489 @$refers[$canonized_headline]++;
2490 $refcount[$headlineCount]=$refers[$canonized_headline];
2491
2492 # Prepend the number to the heading text
2493
2494 if( $doNumberHeadings || $doShowToc ) {
2495 $tocline = $numbering . ' ' . $tocline;
2496
2497 # Don't number the heading if it is the only one (looks silly)
2498 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2499 # the two are different if the line contains a link
2500 $headline=$numbering . ' ' . $headline;
2501 }
2502 }
2503
2504 # Create the anchor for linking from the TOC to the section
2505 $anchor = $canonized_headline;
2506 if($refcount[$headlineCount] > 1 ) {
2507 $anchor .= '_' . $refcount[$headlineCount];
2508 }
2509 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2510 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2511 }
2512 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2513 if ( empty( $head[$headlineCount] ) ) {
2514 $head[$headlineCount] = '';
2515 }
2516 if( $istemplate )
2517 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2518 else
2519 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2520 }
2521
2522 # Add the edit section span
2523 if( $rightClickHack ) {
2524 if( $istemplate )
2525 $headline = $sk->editSectionScriptForOther($templatetitle, $templatesection, $headline);
2526 else
2527 $headline = $sk->editSectionScript($this->mTitle, $sectionCount+1,$headline);
2528 }
2529
2530 # give headline the correct <h#> tag
2531 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2532
2533 $headlineCount++;
2534 if( !$istemplate )
2535 $sectionCount++;
2536 }
2537
2538 if( $doShowToc ) {
2539 $toclines = $headlineCount;
2540 $toc .= $sk->tocUnindent( $toclevel );
2541 $toc = $sk->tocTable( $toc );
2542 }
2543
2544 # split up and insert constructed headlines
2545
2546 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2547 $i = 0;
2548
2549 foreach( $blocks as $block ) {
2550 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2551 # This is the [edit] link that appears for the top block of text when
2552 # section editing is enabled
2553
2554 # Disabled because it broke block formatting
2555 # For example, a bullet point in the top line
2556 # $full .= $sk->editSectionLink(0);
2557 }
2558 $full .= $block;
2559 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2560 # Top anchor now in skin
2561 $full = $full.$toc;
2562 }
2563
2564 if( !empty( $head[$i] ) ) {
2565 $full .= $head[$i];
2566 }
2567 $i++;
2568 }
2569 if($forceTocHere) {
2570 $mw =& MagicWord::get( MAG_TOC );
2571 return $mw->replace( $toc, $full );
2572 } else {
2573 return $full;
2574 }
2575 }
2576
2577 /**
2578 * Return an HTML link for the "ISBN 123456" text
2579 * @access private
2580 */
2581 function magicISBN( $text ) {
2582 global $wgLang;
2583 $fname = 'Parser::magicISBN';
2584 wfProfileIn( $fname );
2585
2586 $a = split( 'ISBN ', ' '.$text );
2587 if ( count ( $a ) < 2 ) {
2588 wfProfileOut( $fname );
2589 return $text;
2590 }
2591 $text = substr( array_shift( $a ), 1);
2592 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2593
2594 foreach ( $a as $x ) {
2595 $isbn = $blank = '' ;
2596 while ( ' ' == $x{0} ) {
2597 $blank .= ' ';
2598 $x = substr( $x, 1 );
2599 }
2600 if ( $x == '' ) { # blank isbn
2601 $text .= "ISBN $blank";
2602 continue;
2603 }
2604 while ( strstr( $valid, $x{0} ) != false ) {
2605 $isbn .= $x{0};
2606 $x = substr( $x, 1 );
2607 }
2608 $num = str_replace( '-', '', $isbn );
2609 $num = str_replace( ' ', '', $num );
2610
2611 if ( '' == $num ) {
2612 $text .= "ISBN $blank$x";
2613 } else {
2614 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2615 $text .= '<a href="' .
2616 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2617 "\" class=\"internal\">ISBN $isbn</a>";
2618 $text .= $x;
2619 }
2620 }
2621 wfProfileOut( $fname );
2622 return $text;
2623 }
2624
2625 /**
2626 * Return an HTML link for the "GEO ..." text
2627 * @access private
2628 */
2629 function magicGEO( $text ) {
2630 global $wgLang, $wgUseGeoMode;
2631 $fname = 'Parser::magicGEO';
2632 wfProfileIn( $fname );
2633
2634 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2635 $directions = array ( 'N' => 'North' , 'S' => 'South' , 'E' => 'East' , 'W' => 'West' ) ;
2636 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2637 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2638 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2639 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2640
2641 $a = split( 'GEO ', ' '.$text );
2642 if ( count ( $a ) < 2 ) {
2643 wfProfileOut( $fname );
2644 return $text;
2645 }
2646 $text = substr( array_shift( $a ), 1);
2647 $valid = '0123456789.+-:';
2648
2649 foreach ( $a as $x ) {
2650 $geo = $blank = '' ;
2651 while ( ' ' == $x{0} ) {
2652 $blank .= ' ';
2653 $x = substr( $x, 1 );
2654 }
2655 while ( strstr( $valid, $x{0} ) != false ) {
2656 $geo .= $x{0};
2657 $x = substr( $x, 1 );
2658 }
2659 $num = str_replace( '+', '', $geo );
2660 $num = str_replace( ' ', '', $num );
2661
2662 if ( '' == $num || count ( explode ( ':' , $num , 3 ) ) < 2 ) {
2663 $text .= "GEO $blank$x";
2664 } else {
2665 $titleObj = Title::makeTitle( NS_SPECIAL, 'Geo' );
2666 $text .= '<a href="' .
2667 $titleObj->escapeLocalUrl( 'coordinates='.$num ) .
2668 "\" class=\"internal\">GEO $geo</a>";
2669 $text .= $x;
2670 }
2671 }
2672 wfProfileOut( $fname );
2673 return $text;
2674 }
2675
2676 /**
2677 * Return an HTML link for the "RFC 1234" text
2678 * @access private
2679 * @param string $text text to be processed
2680 */
2681 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2682 global $wgLang;
2683
2684 $valid = '0123456789';
2685 $internal = false;
2686
2687 $a = split( $keyword, ' '.$text );
2688 if ( count ( $a ) < 2 ) {
2689 return $text;
2690 }
2691 $text = substr( array_shift( $a ), 1);
2692
2693 /* Check if keyword is preceed by [[.
2694 * This test is made here cause of the array_shift above
2695 * that prevent the test to be done in the foreach.
2696 */
2697 if ( substr( $text, -2 ) == '[[' ) {
2698 $internal = true;
2699 }
2700
2701 foreach ( $a as $x ) {
2702 /* token might be empty if we have RFC RFC 1234 */
2703 if ( $x=='' ) {
2704 $text.=$keyword;
2705 continue;
2706 }
2707
2708 $id = $blank = '' ;
2709
2710 /** remove and save whitespaces in $blank */
2711 while ( $x{0} == ' ' ) {
2712 $blank .= ' ';
2713 $x = substr( $x, 1 );
2714 }
2715
2716 /** remove and save the rfc number in $id */
2717 while ( strstr( $valid, $x{0} ) != false ) {
2718 $id .= $x{0};
2719 $x = substr( $x, 1 );
2720 }
2721
2722 if ( $id == '' ) {
2723 /* call back stripped spaces*/
2724 $text .= $keyword.$blank.$x;
2725 } elseif( $internal ) {
2726 /* normal link */
2727 $text .= $keyword.$id.$x;
2728 } else {
2729 /* build the external link*/
2730 $url = wfmsg( $urlmsg );
2731 $url = str_replace( '$1', $id, $url);
2732 $sk =& $this->mOptions->getSkin();
2733 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2734 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2735 }
2736
2737 /* Check if the next RFC keyword is preceed by [[ */
2738 $internal = ( substr($x,-2) == '[[' );
2739 }
2740 return $text;
2741 }
2742
2743 /**
2744 * Transform wiki markup when saving a page by doing \r\n -> \n
2745 * conversion, substitting signatures, {{subst:}} templates, etc.
2746 *
2747 * @param string $text the text to transform
2748 * @param Title &$title the Title object for the current article
2749 * @param User &$user the User object describing the current user
2750 * @param ParserOptions $options parsing options
2751 * @param bool $clearState whether to clear the parser state first
2752 * @return string the altered wiki markup
2753 * @access public
2754 */
2755 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2756 $this->mOptions = $options;
2757 $this->mTitle =& $title;
2758 $this->mOutputType = OT_WIKI;
2759
2760 if ( $clearState ) {
2761 $this->clearState();
2762 }
2763
2764 $stripState = false;
2765 $pairs = array(
2766 "\r\n" => "\n",
2767 );
2768 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2769 $text = $this->strip( $text, $stripState, false );
2770 $text = $this->pstPass2( $text, $user );
2771 $text = $this->unstrip( $text, $stripState );
2772 $text = $this->unstripNoWiki( $text, $stripState );
2773 return $text;
2774 }
2775
2776 /**
2777 * Pre-save transform helper function
2778 * @access private
2779 */
2780 function pstPass2( $text, &$user ) {
2781 global $wgLang, $wgContLang, $wgLocaltimezone;
2782
2783 # Variable replacement
2784 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2785 $text = $this->replaceVariables( $text );
2786
2787 # Signatures
2788 #
2789 $n = $user->getName();
2790 $k = $user->getOption( 'nickname' );
2791 if ( '' == $k ) { $k = $n; }
2792 if ( isset( $wgLocaltimezone ) ) {
2793 $oldtz = getenv( 'TZ' );
2794 putenv( 'TZ='.$wgLocaltimezone );
2795 }
2796 /* Note: this is an ugly timezone hack for the European wikis */
2797 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2798 ' (' . date( 'T' ) . ')';
2799 if ( isset( $wgLocaltimezone ) ) {
2800 putenv( 'TZ='.$oldtzs );
2801 }
2802
2803 $text = preg_replace( '/~~~~~~/', $d, $text );
2804 $text = preg_replace( '/~~~~/', '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]] $d", $text );
2805 $text = preg_replace( '/~~~/', '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]", $text );
2806
2807 # Context links: [[|name]] and [[name (context)|]]
2808 #
2809 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2810 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2811 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2812 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2813
2814 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2815 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2816 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2817 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2818 $context = '';
2819 $t = $this->mTitle->getText();
2820 if ( preg_match( $conpat, $t, $m ) ) {
2821 $context = $m[2];
2822 }
2823 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2824 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2825 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2826
2827 if ( '' == $context ) {
2828 $text = preg_replace( $p2, '[[\\1]]', $text );
2829 } else {
2830 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2831 }
2832
2833 # Trim trailing whitespace
2834 # MAG_END (__END__) tag allows for trailing
2835 # whitespace to be deliberately included
2836 $text = rtrim( $text );
2837 $mw =& MagicWord::get( MAG_END );
2838 $mw->matchAndRemove( $text );
2839
2840 return $text;
2841 }
2842
2843 /**
2844 * Set up some variables which are usually set up in parse()
2845 * so that an external function can call some class members with confidence
2846 * @access public
2847 */
2848 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2849 $this->mTitle =& $title;
2850 $this->mOptions = $options;
2851 $this->mOutputType = $outputType;
2852 if ( $clearState ) {
2853 $this->clearState();
2854 }
2855 }
2856
2857 /**
2858 * Transform a MediaWiki message by replacing magic variables.
2859 *
2860 * @param string $text the text to transform
2861 * @param ParserOptions $options options
2862 * @return string the text with variables substituted
2863 * @access public
2864 */
2865 function transformMsg( $text, $options ) {
2866 global $wgTitle;
2867 static $executing = false;
2868
2869 # Guard against infinite recursion
2870 if ( $executing ) {
2871 return $text;
2872 }
2873 $executing = true;
2874
2875 $this->mTitle = $wgTitle;
2876 $this->mOptions = $options;
2877 $this->mOutputType = OT_MSG;
2878 $this->clearState();
2879 $text = $this->replaceVariables( $text );
2880
2881 $executing = false;
2882 return $text;
2883 }
2884
2885 /**
2886 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2887 * Callback will be called with the text within
2888 * Transform and return the text within
2889 * @access public
2890 */
2891 function setHook( $tag, $callback ) {
2892 $oldVal = @$this->mTagHooks[$tag];
2893 $this->mTagHooks[$tag] = $callback;
2894 return $oldVal;
2895 }
2896
2897 /**
2898 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2899 * Placeholders created in Skin::makeLinkObj()
2900 * Returns an array of links found, indexed by PDBK:
2901 * 0 - broken
2902 * 1 - normal link
2903 * 2 - stub
2904 * $options is a bit field, RLH_FOR_UPDATE to select for update
2905 */
2906 function replaceLinkHolders( &$text, $options = 0 ) {
2907 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2908 global $wgInterwikiLinkHolders;
2909 global $outputReplace;
2910
2911 if ( $wgUseOldExistenceCheck ) {
2912 return array();
2913 }
2914
2915 $fname = 'Parser::replaceLinkHolders';
2916 wfProfileIn( $fname );
2917
2918 $pdbks = array();
2919 $colours = array();
2920
2921 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2922 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2923 wfProfileIn( $fname.'-check' );
2924 $dbr =& wfGetDB( DB_SLAVE );
2925 $cur = $dbr->tableName( 'cur' );
2926 $sk = $wgUser->getSkin();
2927 $threshold = $wgUser->getOption('stubthreshold');
2928
2929 # Sort by namespace
2930 asort( $wgLinkHolders['namespaces'] );
2931
2932 # Generate query
2933 $query = false;
2934 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2935 # Make title object
2936 $title = $wgLinkHolders['titles'][$key];
2937
2938 # Skip invalid entries.
2939 # Result will be ugly, but prevents crash.
2940 if ( is_null( $title ) ) {
2941 continue;
2942 }
2943 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2944
2945 # Check if it's in the link cache already
2946 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2947 $colours[$pdbk] = 1;
2948 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2949 $colours[$pdbk] = 0;
2950 } else {
2951 # Not in the link cache, add it to the query
2952 if ( !isset( $current ) ) {
2953 $current = $val;
2954 $query = "SELECT cur_id, cur_namespace, cur_title";
2955 if ( $threshold > 0 ) {
2956 $query .= ", LENGTH(cur_text) AS cur_len, cur_is_redirect";
2957 }
2958 $query .= " FROM $cur WHERE (cur_namespace=$val AND cur_title IN(";
2959 } elseif ( $current != $val ) {
2960 $current = $val;
2961 $query .= ")) OR (cur_namespace=$val AND cur_title IN(";
2962 } else {
2963 $query .= ', ';
2964 }
2965
2966 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2967 }
2968 }
2969 if ( $query ) {
2970 $query .= '))';
2971 if ( $options & RLH_FOR_UPDATE ) {
2972 $query .= ' FOR UPDATE';
2973 }
2974
2975 $res = $dbr->query( $query, $fname );
2976
2977 # Fetch data and form into an associative array
2978 # non-existent = broken
2979 # 1 = known
2980 # 2 = stub
2981 while ( $s = $dbr->fetchObject($res) ) {
2982 $title = Title::makeTitle( $s->cur_namespace, $s->cur_title );
2983 $pdbk = $title->getPrefixedDBkey();
2984 $wgLinkCache->addGoodLink( $s->cur_id, $pdbk );
2985
2986 if ( $threshold > 0 ) {
2987 $size = $s->cur_len;
2988 if ( $s->cur_is_redirect || $s->cur_namespace != 0 || $length < $threshold ) {
2989 $colours[$pdbk] = 1;
2990 } else {
2991 $colours[$pdbk] = 2;
2992 }
2993 } else {
2994 $colours[$pdbk] = 1;
2995 }
2996 }
2997 }
2998 wfProfileOut( $fname.'-check' );
2999
3000 # Construct search and replace arrays
3001 wfProfileIn( $fname.'-construct' );
3002 $outputReplace = array();
3003 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
3004 $pdbk = $pdbks[$key];
3005 $searchkey = '<!--LINK '.$key.'-->';
3006 $title = $wgLinkHolders['titles'][$key];
3007 if ( empty( $colours[$pdbk] ) ) {
3008 $wgLinkCache->addBadLink( $pdbk );
3009 $colours[$pdbk] = 0;
3010 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3011 $wgLinkHolders['texts'][$key],
3012 $wgLinkHolders['queries'][$key] );
3013 } elseif ( $colours[$pdbk] == 1 ) {
3014 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3015 $wgLinkHolders['texts'][$key],
3016 $wgLinkHolders['queries'][$key] );
3017 } elseif ( $colours[$pdbk] == 2 ) {
3018 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3019 $wgLinkHolders['texts'][$key],
3020 $wgLinkHolders['queries'][$key] );
3021 }
3022 }
3023 wfProfileOut( $fname.'-construct' );
3024
3025 # Do the thing
3026 wfProfileIn( $fname.'-replace' );
3027
3028 $text = preg_replace_callback(
3029 '/(<!--LINK .*?-->)/',
3030 "outputReplaceMatches",
3031 $text);
3032 wfProfileOut( $fname.'-replace' );
3033 }
3034
3035 if ( !empty( $wgInterwikiLinkHolders ) ) {
3036 wfProfileIn( $fname.'-interwiki' );
3037 $outputReplace = $wgInterwikiLinkHolders;
3038 $text = preg_replace_callback(
3039 '/<!--IWLINK (.*?)-->/',
3040 "outputReplaceMatches",
3041 $text );
3042 wfProfileOut( $fname.'-interwiki' );
3043 }
3044
3045 wfProfileOut( $fname );
3046 return $colours;
3047 }
3048
3049 /**
3050 * Renders an image gallery from a text with one line per image.
3051 * text labels may be given by using |-style alternative text. E.g.
3052 * Image:one.jpg|The number "1"
3053 * Image:tree.jpg|A tree
3054 * given as text will return the HTML of a gallery with two images,
3055 * labeled 'The number "1"' and
3056 * 'A tree'.
3057 */
3058 function renderImageGallery( $text ) {
3059 global $wgLinkCache;
3060 $ig = new ImageGallery();
3061 $ig->setShowBytes( false );
3062 $ig->setShowFilename( false );
3063 $lines = explode( "\n", $text );
3064
3065 foreach ( $lines as $line ) {
3066 # match lines like these:
3067 # Image:someimage.jpg|This is some image
3068 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3069 # Skip empty lines
3070 if ( count( $matches ) == 0 ) {
3071 continue;
3072 }
3073 $nt = Title::newFromURL( $matches[1] );
3074 if ( isset( $matches[3] ) ) {
3075 $label = $matches[3];
3076 } else {
3077 $label = '';
3078 }
3079 $ig->add( Image::newFromTitle( $nt ), $label );
3080 $wgLinkCache->addImageLinkObj( $nt );
3081 }
3082 return $ig->toHTML();
3083 }
3084 }
3085
3086 /**
3087 * @todo document
3088 * @package MediaWiki
3089 */
3090 class ParserOutput
3091 {
3092 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3093 var $mCacheTime; # Used in ParserCache
3094 var $mVersion; # Compatibility check
3095
3096 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3097 $containsOldMagic = false )
3098 {
3099 $this->mText = $text;
3100 $this->mLanguageLinks = $languageLinks;
3101 $this->mCategoryLinks = $categoryLinks;
3102 $this->mContainsOldMagic = $containsOldMagic;
3103 $this->mCacheTime = '';
3104 $this->mVersion = MW_PARSER_VERSION;
3105 }
3106
3107 function getText() { return $this->mText; }
3108 function getLanguageLinks() { return $this->mLanguageLinks; }
3109 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
3110 function getCacheTime() { return $this->mCacheTime; }
3111 function containsOldMagic() { return $this->mContainsOldMagic; }
3112 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3113 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3114 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
3115 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3116 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3117 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
3118
3119 function merge( $other ) {
3120 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3121 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3122 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3123 }
3124
3125 /**
3126 * Return true if this cached output object predates the global or
3127 * per-article cache invalidation timestamps, or if it comes from
3128 * an incompatible older version.
3129 *
3130 * @param string $touched the affected article's last touched timestamp
3131 * @return bool
3132 * @access public
3133 */
3134 function expired( $touched ) {
3135 global $wgCacheEpoch;
3136 return $this->getCacheTime() <= $touched ||
3137 $this->getCacheTime() <= $wgCacheEpoch ||
3138 !isset( $this->mVersion ) ||
3139 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3140 }
3141 }
3142
3143 /**
3144 * Set options of the Parser
3145 * @todo document
3146 * @package MediaWiki
3147 */
3148 class ParserOptions
3149 {
3150 # All variables are private
3151 var $mUseTeX; # Use texvc to expand <math> tags
3152 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
3153 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3154 var $mAllowExternalImages; # Allow external images inline
3155 var $mSkin; # Reference to the preferred skin
3156 var $mDateFormat; # Date format index
3157 var $mEditSection; # Create "edit section" links
3158 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
3159 var $mNumberHeadings; # Automatically number headings
3160 var $mShowToc; # Show table of contents
3161
3162 function getUseTeX() { return $this->mUseTeX; }
3163 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3164 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3165 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3166 function getSkin() { return $this->mSkin; }
3167 function getDateFormat() { return $this->mDateFormat; }
3168 function getEditSection() { return $this->mEditSection; }
3169 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
3170 function getNumberHeadings() { return $this->mNumberHeadings; }
3171 function getShowToc() { return $this->mShowToc; }
3172
3173 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3174 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3175 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3176 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3177 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3178 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3179 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
3180 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3181 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
3182
3183 function setSkin( &$x ) { $this->mSkin =& $x; }
3184
3185 # Get parser options
3186 /* static */ function newFromUser( &$user ) {
3187 $popts = new ParserOptions;
3188 $popts->initialiseFromUser( $user );
3189 return $popts;
3190 }
3191
3192 # Get user options
3193 function initialiseFromUser( &$userInput ) {
3194 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3195 $fname = 'ParserOptions::initialiseFromUser';
3196 wfProfileIn( $fname );
3197 if ( !$userInput ) {
3198 $user = new User;
3199 $user->setLoaded( true );
3200 } else {
3201 $user =& $userInput;
3202 }
3203
3204 $this->mUseTeX = $wgUseTeX;
3205 $this->mUseDynamicDates = $wgUseDynamicDates;
3206 $this->mInterwikiMagic = $wgInterwikiMagic;
3207 $this->mAllowExternalImages = $wgAllowExternalImages;
3208 wfProfileIn( $fname.'-skin' );
3209 $this->mSkin =& $user->getSkin();
3210 wfProfileOut( $fname.'-skin' );
3211 $this->mDateFormat = $user->getOption( 'date' );
3212 $this->mEditSection = $user->getOption( 'editsection' );
3213 $this->mEditSectionOnRightClick = $user->getOption( 'editsectiononrightclick' );
3214 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3215 $this->mShowToc = $user->getOption( 'showtoc' );
3216 wfProfileOut( $fname );
3217 }
3218
3219
3220 }
3221
3222 /**
3223 * Callback function used by Parser::replaceLinkHolders()
3224 * to substitute link placeholders.
3225 */
3226 function &outputReplaceMatches( $matches ) {
3227 global $outputReplace;
3228 return $outputReplace[$matches[1]];
3229 }
3230
3231 /**
3232 * Return the total number of articles
3233 */
3234 function wfNumberOfArticles() {
3235 global $wgNumberOfArticles;
3236
3237 wfLoadSiteStats();
3238 return $wgNumberOfArticles;
3239 }
3240
3241 /**
3242 * Get various statistics from the database
3243 * @private
3244 */
3245 function wfLoadSiteStats() {
3246 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3247 $fname = 'wfLoadSiteStats';
3248
3249 if ( -1 != $wgNumberOfArticles ) return;
3250 $dbr =& wfGetDB( DB_SLAVE );
3251 $s = $dbr->selectRow( 'site_stats',
3252 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3253 array( 'ss_row_id' => 1 ), $fname
3254 );
3255
3256 if ( $s === false ) {
3257 return;
3258 } else {
3259 $wgTotalViews = $s->ss_total_views;
3260 $wgTotalEdits = $s->ss_total_edits;
3261 $wgNumberOfArticles = $s->ss_good_articles;
3262 }
3263 }
3264
3265 function wfEscapeHTMLTagsOnly( $in ) {
3266 return str_replace(
3267 array( '"', '>', '<' ),
3268 array( '&quot;', '&gt;', '&lt;' ),
3269 $in );
3270 }
3271
3272 ?>