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