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