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