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