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