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