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