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