* Rewrote the url protocol thing to not suck
[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(' . wfUrlProtocols() . ')'.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 $wgContLang;
1125 $fname = 'Parser::replaceFreeExternalLinks';
1126 wfProfileIn( $fname );
1127
1128 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1129 $s = array_shift( $bits );
1130 $i = 0;
1131
1132 $sk =& $this->mOptions->getSkin();
1133
1134 while ( $i < count( $bits ) ){
1135 $protocol = $bits[$i++];
1136 $remainder = $bits[$i++];
1137
1138 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1139 # Found some characters after the protocol that look promising
1140 $url = $protocol . $m[1];
1141 $trail = $m[2];
1142
1143 # The characters '<' and '>' (which were escaped by
1144 # removeHTMLtags()) should not be included in
1145 # URLs, per RFC 2396.
1146 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1147 $trail = substr($url, $m2[0][1]) . $trail;
1148 $url = substr($url, 0, $m2[0][1]);
1149 }
1150
1151 # Move trailing punctuation to $trail
1152 $sep = ',;\.:!?';
1153 # If there is no left bracket, then consider right brackets fair game too
1154 if ( strpos( $url, '(' ) === false ) {
1155 $sep .= ')';
1156 }
1157
1158 $numSepChars = strspn( strrev( $url ), $sep );
1159 if ( $numSepChars ) {
1160 $trail = substr( $url, -$numSepChars ) . $trail;
1161 $url = substr( $url, 0, -$numSepChars );
1162 }
1163
1164 # Replace &amp; from obsolete syntax with &.
1165 # All HTML entities will be escaped by makeExternalLink()
1166 # or maybeMakeExternalImage()
1167 $url = str_replace( '&amp;', '&', $url );
1168
1169 # Is this an external image?
1170 $text = $this->maybeMakeExternalImage( $url );
1171 if ( $text === false ) {
1172 # Not an image, make a link
1173 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1174 }
1175 $s .= $text . $trail;
1176 } else {
1177 $s .= $protocol . $remainder;
1178 }
1179 }
1180 wfProfileOut( $fname );
1181 return $s;
1182 }
1183
1184 /**
1185 * make an image if it's allowed, either through the global
1186 * option or through the exception
1187 * @access private
1188 */
1189 function maybeMakeExternalImage( $url ) {
1190 $sk =& $this->mOptions->getSkin();
1191 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1192 $imagesexception = !empty($imagesfrom);
1193 $text = false;
1194 if ( $this->mOptions->getAllowExternalImages()
1195 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1196 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1197 # Image found
1198 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1199 }
1200 }
1201 return $text;
1202 }
1203
1204 /**
1205 * Process [[ ]] wikilinks
1206 *
1207 * @access private
1208 */
1209 function replaceInternalLinks( $s ) {
1210 global $wgContLang, $wgLinkCache;
1211 static $fname = 'Parser::replaceInternalLinks' ;
1212
1213 wfProfileIn( $fname );
1214
1215 wfProfileIn( $fname.'-setup' );
1216 static $tc = FALSE;
1217 # the % is needed to support urlencoded titles as well
1218 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1219
1220 $sk =& $this->mOptions->getSkin();
1221
1222 #split the entire text string on occurences of [[
1223 $a = explode( '[[', ' ' . $s );
1224 #get the first element (all text up to first [[), and remove the space we added
1225 $s = array_shift( $a );
1226 $s = substr( $s, 1 );
1227
1228 # Match a link having the form [[namespace:link|alternate]]trail
1229 static $e1 = FALSE;
1230 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1231 # Match cases where there is no "]]", which might still be images
1232 static $e1_img = FALSE;
1233 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1234 # Match the end of a line for a word that's not followed by whitespace,
1235 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1236 $e2 = wfMsgForContent( 'linkprefix' );
1237
1238 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1239
1240 if( is_null( $this->mTitle ) ) {
1241 wfDebugDieBacktrace( 'nooo' );
1242 }
1243 $nottalk = !$this->mTitle->isTalkPage();
1244
1245 if ( $useLinkPrefixExtension ) {
1246 if ( preg_match( $e2, $s, $m ) ) {
1247 $first_prefix = $m[2];
1248 } else {
1249 $first_prefix = false;
1250 }
1251 } else {
1252 $prefix = '';
1253 }
1254
1255 $selflink = $this->mTitle->getPrefixedText();
1256 wfProfileOut( $fname.'-setup' );
1257
1258 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1259 $useSubpages = $this->areSubpagesAllowed();
1260
1261 # Loop for each link
1262 for ($k = 0; isset( $a[$k] ); $k++) {
1263 $line = $a[$k];
1264 if ( $useLinkPrefixExtension ) {
1265 wfProfileIn( $fname.'-prefixhandling' );
1266 if ( preg_match( $e2, $s, $m ) ) {
1267 $prefix = $m[2];
1268 $s = $m[1];
1269 } else {
1270 $prefix='';
1271 }
1272 # first link
1273 if($first_prefix) {
1274 $prefix = $first_prefix;
1275 $first_prefix = false;
1276 }
1277 wfProfileOut( $fname.'-prefixhandling' );
1278 }
1279
1280 $might_be_img = false;
1281
1282 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1283 $text = $m[2];
1284 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1285 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1286 # the real problem is with the $e1 regex
1287 # See bug 1300.
1288 #
1289 # Still some problems for cases where the ] is meant to be outside punctuation,
1290 # and no image is in sight. See bug 2095.
1291 #
1292 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1293 $text .= ']'; # so that replaceExternalLinks($text) works later
1294 $m[3] = $n[1];
1295 }
1296 # fix up urlencoded title texts
1297 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1298 $trail = $m[3];
1299 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1300 $might_be_img = true;
1301 $text = $m[2];
1302 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1303 $trail = "";
1304 } else { # Invalid form; output directly
1305 $s .= $prefix . '[[' . $line ;
1306 continue;
1307 }
1308
1309 # Don't allow internal links to pages containing
1310 # PROTO: where PROTO is a valid URL protocol; these
1311 # should be external links.
1312 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1313 $s .= $prefix . '[[' . $line ;
1314 continue;
1315 }
1316
1317 # Make subpage if necessary
1318 if( $useSubpages ) {
1319 $link = $this->maybeDoSubpageLink( $m[1], $text );
1320 } else {
1321 $link = $m[1];
1322 }
1323
1324 $noforce = (substr($m[1], 0, 1) != ':');
1325 if (!$noforce) {
1326 # Strip off leading ':'
1327 $link = substr($link, 1);
1328 }
1329
1330 $nt = Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1331 if( !$nt ) {
1332 $s .= $prefix . '[[' . $line;
1333 continue;
1334 }
1335
1336 #check other language variants of the link
1337 #if the article does not exist
1338 if( $checkVariantLink
1339 && $nt->getArticleID() == 0 ) {
1340 $wgContLang->findVariantLink($link, $nt);
1341 }
1342
1343 $ns = $nt->getNamespace();
1344 $iw = $nt->getInterWiki();
1345
1346 if ($might_be_img) { # if this is actually an invalid link
1347 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1348 $found = false;
1349 while (isset ($a[$k+1]) ) {
1350 #look at the next 'line' to see if we can close it there
1351 $spliced = array_splice( $a, $k + 1, 1 );
1352 $next_line = array_shift( $spliced );
1353 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1354 # the first ]] closes the inner link, the second the image
1355 $found = true;
1356 $text .= '[[' . $m[1];
1357 $trail = $m[2];
1358 break;
1359 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1360 #if there's exactly one ]] that's fine, we'll keep looking
1361 $text .= '[[' . $m[0];
1362 } else {
1363 #if $next_line is invalid too, we need look no further
1364 $text .= '[[' . $next_line;
1365 break;
1366 }
1367 }
1368 if ( !$found ) {
1369 # we couldn't find the end of this imageLink, so output it raw
1370 #but don't ignore what might be perfectly normal links in the text we've examined
1371 $text = $this->replaceInternalLinks($text);
1372 $s .= $prefix . '[[' . $link . '|' . $text;
1373 # note: no $trail, because without an end, there *is* no trail
1374 continue;
1375 }
1376 } else { #it's not an image, so output it raw
1377 $s .= $prefix . '[[' . $link . '|' . $text;
1378 # note: no $trail, because without an end, there *is* no trail
1379 continue;
1380 }
1381 }
1382
1383 $wasblank = ( '' == $text );
1384 if( $wasblank ) $text = $link;
1385
1386
1387 # Link not escaped by : , create the various objects
1388 if( $noforce ) {
1389
1390 # Interwikis
1391 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1392 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1393 $s = rtrim($s . "\n");
1394 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1395 continue;
1396 }
1397
1398 if ( $ns == NS_IMAGE ) {
1399 wfProfileIn( "$fname-image" );
1400 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1401 # recursively parse links inside the image caption
1402 # actually, this will parse them in any other parameters, too,
1403 # but it might be hard to fix that, and it doesn't matter ATM
1404 $text = $this->replaceExternalLinks($text);
1405 $text = $this->replaceInternalLinks($text);
1406
1407 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1408 $s .= $prefix . preg_replace( "/\b(" . wfUrlProtocols() . ')/', UNIQ_PREFIX."NOPARSE$1", $this->makeImage( $nt, $text) ) . $trail;
1409 $wgLinkCache->addImageLinkObj( $nt );
1410
1411 wfProfileOut( "$fname-image" );
1412 continue;
1413 }
1414 wfProfileOut( "$fname-image" );
1415
1416 }
1417
1418 if ( $ns == NS_CATEGORY ) {
1419 wfProfileIn( "$fname-category" );
1420 $t = $wgContLang->convertHtml( $nt->getText() );
1421 $s = rtrim($s . "\n"); # bug 87
1422
1423 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1424 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1425 $wgLinkCache->resume();
1426
1427 if ( $wasblank ) {
1428 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1429 $sortkey = $this->mTitle->getText();
1430 } else {
1431 $sortkey = $this->mTitle->getPrefixedText();
1432 }
1433 } else {
1434 $sortkey = $text;
1435 }
1436 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1437 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1438 $this->mOutput->addCategoryLink( $t );
1439
1440 /**
1441 * Strip the whitespace Category links produce, see bug 87
1442 * @todo We might want to use trim($tmp, "\n") here.
1443 */
1444 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1445
1446 wfProfileOut( "$fname-category" );
1447 continue;
1448 }
1449 }
1450
1451 if( ( $nt->getPrefixedText() === $selflink ) &&
1452 ( $nt->getFragment() === '' ) ) {
1453 # Self-links are handled specially; generally de-link and change to bold.
1454 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1455 continue;
1456 }
1457
1458 # Special and Media are pseudo-namespaces; no pages actually exist in them
1459 if( $ns == NS_MEDIA ) {
1460 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1461 $wgLinkCache->addImageLinkObj( $nt );
1462 continue;
1463 } elseif( $ns == NS_SPECIAL ) {
1464 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1465 continue;
1466 }
1467 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1468 }
1469 wfProfileOut( $fname );
1470 return $s;
1471 }
1472
1473 /**
1474 * Make a link placeholder. The text returned can be later resolved to a real link with
1475 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1476 * parsing of interwiki links, and secondly to allow all extistence checks and
1477 * article length checks (for stub links) to be bundled into a single query.
1478 *
1479 */
1480 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1481 if ( ! is_object($nt) ) {
1482 # Fail gracefully
1483 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1484 } else {
1485 # Separate the link trail from the rest of the link
1486 list( $inside, $trail ) = Linker::splitTrail( $trail );
1487
1488 if ( $nt->isExternal() ) {
1489 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1490 $this->mInterwikiLinkHolders['titles'][] = $nt;
1491 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1492 } else {
1493 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1494 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1495 $this->mLinkHolders['queries'][] = $query;
1496 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1497 $this->mLinkHolders['titles'][] = $nt;
1498
1499 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1500 }
1501 }
1502 return $retVal;
1503 }
1504
1505 /**
1506 * Return true if subpage links should be expanded on this page.
1507 * @return bool
1508 */
1509 function areSubpagesAllowed() {
1510 # Some namespaces don't allow subpages
1511 global $wgNamespacesWithSubpages;
1512 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1513 }
1514
1515 /**
1516 * Handle link to subpage if necessary
1517 * @param string $target the source of the link
1518 * @param string &$text the link text, modified as necessary
1519 * @return string the full name of the link
1520 * @access private
1521 */
1522 function maybeDoSubpageLink($target, &$text) {
1523 # Valid link forms:
1524 # Foobar -- normal
1525 # :Foobar -- override special treatment of prefix (images, language links)
1526 # /Foobar -- convert to CurrentPage/Foobar
1527 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1528 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1529 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1530
1531 $fname = 'Parser::maybeDoSubpageLink';
1532 wfProfileIn( $fname );
1533 $ret = $target; # default return value is no change
1534
1535 # Some namespaces don't allow subpages,
1536 # so only perform processing if subpages are allowed
1537 if( $this->areSubpagesAllowed() ) {
1538 # Look at the first character
1539 if( $target != '' && $target{0} == '/' ) {
1540 # / at end means we don't want the slash to be shown
1541 if( substr( $target, -1, 1 ) == '/' ) {
1542 $target = substr( $target, 1, -1 );
1543 $noslash = $target;
1544 } else {
1545 $noslash = substr( $target, 1 );
1546 }
1547
1548 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1549 if( '' === $text ) {
1550 $text = $target;
1551 } # this might be changed for ugliness reasons
1552 } else {
1553 # check for .. subpage backlinks
1554 $dotdotcount = 0;
1555 $nodotdot = $target;
1556 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1557 ++$dotdotcount;
1558 $nodotdot = substr( $nodotdot, 3 );
1559 }
1560 if($dotdotcount > 0) {
1561 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1562 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1563 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1564 # / at the end means don't show full path
1565 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1566 $nodotdot = substr( $nodotdot, 0, -1 );
1567 if( '' === $text ) {
1568 $text = $nodotdot;
1569 }
1570 }
1571 $nodotdot = trim( $nodotdot );
1572 if( $nodotdot != '' ) {
1573 $ret .= '/' . $nodotdot;
1574 }
1575 }
1576 }
1577 }
1578 }
1579
1580 wfProfileOut( $fname );
1581 return $ret;
1582 }
1583
1584 /**#@+
1585 * Used by doBlockLevels()
1586 * @access private
1587 */
1588 /* private */ function closeParagraph() {
1589 $result = '';
1590 if ( '' != $this->mLastSection ) {
1591 $result = '</' . $this->mLastSection . ">\n";
1592 }
1593 $this->mInPre = false;
1594 $this->mLastSection = '';
1595 return $result;
1596 }
1597 # getCommon() returns the length of the longest common substring
1598 # of both arguments, starting at the beginning of both.
1599 #
1600 /* private */ function getCommon( $st1, $st2 ) {
1601 $fl = strlen( $st1 );
1602 $shorter = strlen( $st2 );
1603 if ( $fl < $shorter ) { $shorter = $fl; }
1604
1605 for ( $i = 0; $i < $shorter; ++$i ) {
1606 if ( $st1{$i} != $st2{$i} ) { break; }
1607 }
1608 return $i;
1609 }
1610 # These next three functions open, continue, and close the list
1611 # element appropriate to the prefix character passed into them.
1612 #
1613 /* private */ function openList( $char ) {
1614 $result = $this->closeParagraph();
1615
1616 if ( '*' == $char ) { $result .= '<ul><li>'; }
1617 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1618 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1619 else if ( ';' == $char ) {
1620 $result .= '<dl><dt>';
1621 $this->mDTopen = true;
1622 }
1623 else { $result = '<!-- ERR 1 -->'; }
1624
1625 return $result;
1626 }
1627
1628 /* private */ function nextItem( $char ) {
1629 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1630 else if ( ':' == $char || ';' == $char ) {
1631 $close = '</dd>';
1632 if ( $this->mDTopen ) { $close = '</dt>'; }
1633 if ( ';' == $char ) {
1634 $this->mDTopen = true;
1635 return $close . '<dt>';
1636 } else {
1637 $this->mDTopen = false;
1638 return $close . '<dd>';
1639 }
1640 }
1641 return '<!-- ERR 2 -->';
1642 }
1643
1644 /* private */ function closeList( $char ) {
1645 if ( '*' == $char ) { $text = '</li></ul>'; }
1646 else if ( '#' == $char ) { $text = '</li></ol>'; }
1647 else if ( ':' == $char ) {
1648 if ( $this->mDTopen ) {
1649 $this->mDTopen = false;
1650 $text = '</dt></dl>';
1651 } else {
1652 $text = '</dd></dl>';
1653 }
1654 }
1655 else { return '<!-- ERR 3 -->'; }
1656 return $text."\n";
1657 }
1658 /**#@-*/
1659
1660 /**
1661 * Make lists from lines starting with ':', '*', '#', etc.
1662 *
1663 * @access private
1664 * @return string the lists rendered as HTML
1665 */
1666 function doBlockLevels( $text, $linestart ) {
1667 $fname = 'Parser::doBlockLevels';
1668 wfProfileIn( $fname );
1669
1670 # Parsing through the text line by line. The main thing
1671 # happening here is handling of block-level elements p, pre,
1672 # and making lists from lines starting with * # : etc.
1673 #
1674 $textLines = explode( "\n", $text );
1675
1676 $lastPrefix = $output = '';
1677 $this->mDTopen = $inBlockElem = false;
1678 $prefixLength = 0;
1679 $paragraphStack = false;
1680
1681 if ( !$linestart ) {
1682 $output .= array_shift( $textLines );
1683 }
1684 foreach ( $textLines as $oLine ) {
1685 $lastPrefixLength = strlen( $lastPrefix );
1686 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1687 $preOpenMatch = preg_match('/<pre/i', $oLine );
1688 if ( !$this->mInPre ) {
1689 # Multiple prefixes may abut each other for nested lists.
1690 $prefixLength = strspn( $oLine, '*#:;' );
1691 $pref = substr( $oLine, 0, $prefixLength );
1692
1693 # eh?
1694 $pref2 = str_replace( ';', ':', $pref );
1695 $t = substr( $oLine, $prefixLength );
1696 $this->mInPre = !empty($preOpenMatch);
1697 } else {
1698 # Don't interpret any other prefixes in preformatted text
1699 $prefixLength = 0;
1700 $pref = $pref2 = '';
1701 $t = $oLine;
1702 }
1703
1704 # List generation
1705 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1706 # Same as the last item, so no need to deal with nesting or opening stuff
1707 $output .= $this->nextItem( substr( $pref, -1 ) );
1708 $paragraphStack = false;
1709
1710 if ( substr( $pref, -1 ) == ';') {
1711 # The one nasty exception: definition lists work like this:
1712 # ; title : definition text
1713 # So we check for : in the remainder text to split up the
1714 # title and definition, without b0rking links.
1715 $term = $t2 = '';
1716 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1717 $t = $t2;
1718 $output .= $term . $this->nextItem( ':' );
1719 }
1720 }
1721 } elseif( $prefixLength || $lastPrefixLength ) {
1722 # Either open or close a level...
1723 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1724 $paragraphStack = false;
1725
1726 while( $commonPrefixLength < $lastPrefixLength ) {
1727 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1728 --$lastPrefixLength;
1729 }
1730 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1731 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1732 }
1733 while ( $prefixLength > $commonPrefixLength ) {
1734 $char = substr( $pref, $commonPrefixLength, 1 );
1735 $output .= $this->openList( $char );
1736
1737 if ( ';' == $char ) {
1738 # FIXME: This is dupe of code above
1739 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1740 $t = $t2;
1741 $output .= $term . $this->nextItem( ':' );
1742 }
1743 }
1744 ++$commonPrefixLength;
1745 }
1746 $lastPrefix = $pref2;
1747 }
1748 if( 0 == $prefixLength ) {
1749 wfProfileIn( "$fname-paragraph" );
1750 # No prefix (not in list)--go to paragraph mode
1751 $uniq_prefix = UNIQ_PREFIX;
1752 // XXX: use a stack for nestable elements like span, table and div
1753 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1754 $closematch = preg_match(
1755 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1756 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1757 if ( $openmatch or $closematch ) {
1758 $paragraphStack = false;
1759 $output .= $this->closeParagraph();
1760 if ( $preOpenMatch and !$preCloseMatch ) {
1761 $this->mInPre = true;
1762 }
1763 if ( $closematch ) {
1764 $inBlockElem = false;
1765 } else {
1766 $inBlockElem = true;
1767 }
1768 } else if ( !$inBlockElem && !$this->mInPre ) {
1769 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1770 // pre
1771 if ($this->mLastSection != 'pre') {
1772 $paragraphStack = false;
1773 $output .= $this->closeParagraph().'<pre>';
1774 $this->mLastSection = 'pre';
1775 }
1776 $t = substr( $t, 1 );
1777 } else {
1778 // paragraph
1779 if ( '' == trim($t) ) {
1780 if ( $paragraphStack ) {
1781 $output .= $paragraphStack.'<br />';
1782 $paragraphStack = false;
1783 $this->mLastSection = 'p';
1784 } else {
1785 if ($this->mLastSection != 'p' ) {
1786 $output .= $this->closeParagraph();
1787 $this->mLastSection = '';
1788 $paragraphStack = '<p>';
1789 } else {
1790 $paragraphStack = '</p><p>';
1791 }
1792 }
1793 } else {
1794 if ( $paragraphStack ) {
1795 $output .= $paragraphStack;
1796 $paragraphStack = false;
1797 $this->mLastSection = 'p';
1798 } else if ($this->mLastSection != 'p') {
1799 $output .= $this->closeParagraph().'<p>';
1800 $this->mLastSection = 'p';
1801 }
1802 }
1803 }
1804 }
1805 wfProfileOut( "$fname-paragraph" );
1806 }
1807 // somewhere above we forget to get out of pre block (bug 785)
1808 if($preCloseMatch && $this->mInPre) {
1809 $this->mInPre = false;
1810 }
1811 if ($paragraphStack === false) {
1812 $output .= $t."\n";
1813 }
1814 }
1815 while ( $prefixLength ) {
1816 $output .= $this->closeList( $pref2{$prefixLength-1} );
1817 --$prefixLength;
1818 }
1819 if ( '' != $this->mLastSection ) {
1820 $output .= '</' . $this->mLastSection . '>';
1821 $this->mLastSection = '';
1822 }
1823
1824 wfProfileOut( $fname );
1825 return $output;
1826 }
1827
1828 /**
1829 * Split up a string on ':', ignoring any occurences inside
1830 * <a>..</a> or <span>...</span>
1831 * @param string $str the string to split
1832 * @param string &$before set to everything before the ':'
1833 * @param string &$after set to everything after the ':'
1834 * return string the position of the ':', or false if none found
1835 */
1836 function findColonNoLinks($str, &$before, &$after) {
1837 # I wonder if we should make this count all tags, not just <a>
1838 # and <span>. That would prevent us from matching a ':' that
1839 # comes in the middle of italics other such formatting....
1840 # -- Wil
1841 $fname = 'Parser::findColonNoLinks';
1842 wfProfileIn( $fname );
1843 $pos = 0;
1844 do {
1845 $colon = strpos($str, ':', $pos);
1846
1847 if ($colon !== false) {
1848 $before = substr($str, 0, $colon);
1849 $after = substr($str, $colon + 1);
1850
1851 # Skip any ':' within <a> or <span> pairs
1852 $a = substr_count($before, '<a');
1853 $s = substr_count($before, '<span');
1854 $ca = substr_count($before, '</a>');
1855 $cs = substr_count($before, '</span>');
1856
1857 if ($a <= $ca and $s <= $cs) {
1858 # Tags are balanced before ':'; ok
1859 break;
1860 }
1861 $pos = $colon + 1;
1862 }
1863 } while ($colon !== false);
1864 wfProfileOut( $fname );
1865 return $colon;
1866 }
1867
1868 /**
1869 * Return value of a magic variable (like PAGENAME)
1870 *
1871 * @access private
1872 */
1873 function getVariableValue( $index ) {
1874 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
1875
1876 /**
1877 * Some of these require message or data lookups and can be
1878 * expensive to check many times.
1879 */
1880 static $varCache = array();
1881 if( isset( $varCache[$index] ) ) return $varCache[$index];
1882
1883 switch ( $index ) {
1884 case MAG_CURRENTMONTH:
1885 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1886 case MAG_CURRENTMONTHNAME:
1887 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1888 case MAG_CURRENTMONTHNAMEGEN:
1889 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1890 case MAG_CURRENTMONTHABBREV:
1891 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1892 case MAG_CURRENTDAY:
1893 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1894 case MAG_PAGENAME:
1895 return $this->mTitle->getText();
1896 case MAG_PAGENAMEE:
1897 return $this->mTitle->getPartialURL();
1898 case MAG_REVISIONID:
1899 return $wgArticle->getRevIdFetched();
1900 case MAG_NAMESPACE:
1901 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1902 return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1903 case MAG_CURRENTDAYNAME:
1904 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1905 case MAG_CURRENTYEAR:
1906 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1907 case MAG_CURRENTTIME:
1908 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1909 case MAG_CURRENTWEEK:
1910 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1911 case MAG_CURRENTDOW:
1912 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1913 case MAG_NUMBEROFARTICLES:
1914 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1915 case MAG_NUMBEROFFILES:
1916 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1917 case MAG_SITENAME:
1918 return $wgSitename;
1919 case MAG_SERVER:
1920 return $wgServer;
1921 case MAG_SERVERNAME:
1922 return $wgServerName;
1923 case MAG_SCRIPTPATH:
1924 return $wgScriptPath;
1925 default:
1926 return NULL;
1927 }
1928 }
1929
1930 /**
1931 * initialise the magic variables (like CURRENTMONTHNAME)
1932 *
1933 * @access private
1934 */
1935 function initialiseVariables() {
1936 $fname = 'Parser::initialiseVariables';
1937 wfProfileIn( $fname );
1938 global $wgVariableIDs;
1939 $this->mVariables = array();
1940 foreach ( $wgVariableIDs as $id ) {
1941 $mw =& MagicWord::get( $id );
1942 $mw->addToArray( $this->mVariables, $id );
1943 }
1944 wfProfileOut( $fname );
1945 }
1946
1947 /**
1948 * parse any parentheses in format ((title|part|part))
1949 * and call callbacks to get a replacement text for any found piece
1950 *
1951 * @param string $text The text to parse
1952 * @param array $callbacks rules in form:
1953 * '{' => array( # opening parentheses
1954 * 'end' => '}', # closing parentheses
1955 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
1956 * 4 => callback # replacement callback to call if {{{{..}}}} is found
1957 * )
1958 * )
1959 * @access private
1960 */
1961 function replace_callback ($text, $callbacks) {
1962 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
1963 $lastOpeningBrace = -1; # last not closed parentheses
1964
1965 for ($i = 0; $i < strlen($text); $i++) {
1966 # check for any opening brace
1967 $rule = null;
1968 $nextPos = -1;
1969 foreach ($callbacks as $key => $value) {
1970 $pos = strpos ($text, $key, $i);
1971 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
1972 $rule = $value;
1973 $nextPos = $pos;
1974 }
1975 }
1976
1977 if ($lastOpeningBrace >= 0) {
1978 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
1979
1980 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
1981 $rule = null;
1982 $nextPos = $pos;
1983 }
1984
1985 $pos = strpos ($text, '|', $i);
1986
1987 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
1988 $rule = null;
1989 $nextPos = $pos;
1990 }
1991 }
1992
1993 if ($nextPos == -1)
1994 break;
1995
1996 $i = $nextPos;
1997
1998 # found openning brace, lets add it to parentheses stack
1999 if (null != $rule) {
2000 $piece = array('brace' => $text[$i],
2001 'braceEnd' => $rule['end'],
2002 'count' => 1,
2003 'title' => '',
2004 'parts' => null);
2005
2006 # count openning brace characters
2007 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2008 $piece['count']++;
2009 $i++;
2010 }
2011
2012 $piece['startAt'] = $i+1;
2013 $piece['partStart'] = $i+1;
2014
2015 # we need to add to stack only if openning brace count is enough for any given rule
2016 foreach ($rule['cb'] as $cnt => $fn) {
2017 if ($piece['count'] >= $cnt) {
2018 $lastOpeningBrace ++;
2019 $openingBraceStack[$lastOpeningBrace] = $piece;
2020 break;
2021 }
2022 }
2023
2024 continue;
2025 }
2026 else if ($lastOpeningBrace >= 0) {
2027 # first check if it is a closing brace
2028 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2029 # lets check if it is enough characters for closing brace
2030 $count = 1;
2031 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2032 $count++;
2033
2034 # if there are more closing parentheses than opening ones, we parse less
2035 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2036 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2037
2038 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2039 $matchingCount = 0;
2040 $matchingCallback = null;
2041 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2042 if ($count >= $cnt && $matchingCount < $cnt) {
2043 $matchingCount = $cnt;
2044 $matchingCallback = $fn;
2045 }
2046 }
2047
2048 if ($matchingCount == 0) {
2049 $i += $count - 1;
2050 continue;
2051 }
2052
2053 # lets set a title or last part (if '|' was found)
2054 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2055 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2056 else
2057 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2058
2059 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2060 $pieceEnd = $i + $matchingCount;
2061
2062 if( is_callable( $matchingCallback ) ) {
2063 $cbArgs = array (
2064 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2065 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2066 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2067 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2068 );
2069 # finally we can call a user callback and replace piece of text
2070 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2071 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2072 $i = $pieceStart + strlen($replaceWith) - 1;
2073 }
2074 else {
2075 # null value for callback means that parentheses should be parsed, but not replaced
2076 $i += $matchingCount - 1;
2077 }
2078
2079 # reset last openning parentheses, but keep it in case there are unused characters
2080 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2081 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2082 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2083 'title' => '',
2084 'parts' => null,
2085 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2086 $openingBraceStack[$lastOpeningBrace--] = null;
2087
2088 if ($matchingCount < $piece['count']) {
2089 $piece['count'] -= $matchingCount;
2090 $piece['startAt'] -= $matchingCount;
2091 $piece['partStart'] = $piece['startAt'];
2092 # do we still qualify for any callback with remaining count?
2093 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2094 if ($piece['count'] >= $cnt) {
2095 $lastOpeningBrace ++;
2096 $openingBraceStack[$lastOpeningBrace] = $piece;
2097 break;
2098 }
2099 }
2100 }
2101 continue;
2102 }
2103
2104 # lets set a title if it is a first separator, or next part otherwise
2105 if ($text[$i] == '|') {
2106 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2107 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2108 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2109 }
2110 else
2111 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2112
2113 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2114 }
2115 }
2116 }
2117
2118 return $text;
2119 }
2120
2121 /**
2122 * Replace magic variables, templates, and template arguments
2123 * with the appropriate text. Templates are substituted recursively,
2124 * taking care to avoid infinite loops.
2125 *
2126 * Note that the substitution depends on value of $mOutputType:
2127 * OT_WIKI: only {{subst:}} templates
2128 * OT_MSG: only magic variables
2129 * OT_HTML: all templates and magic variables
2130 *
2131 * @param string $tex The text to transform
2132 * @param array $args Key-value pairs representing template parameters to substitute
2133 * @access private
2134 */
2135 function replaceVariables( $text, $args = array() ) {
2136 # Prevent too big inclusions
2137 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2138 return $text;
2139 }
2140
2141 $fname = 'Parser::replaceVariables';
2142 wfProfileIn( $fname );
2143
2144 $titleChars = Title::legalChars();
2145
2146 # This function is called recursively. To keep track of arguments we need a stack:
2147 array_push( $this->mArgStack, $args );
2148
2149 $braceCallbacks = array();
2150 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2151 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2152 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2153 }
2154 $callbacks = array();
2155 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2156 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2157 $text = $this->replace_callback ($text, $callbacks);
2158
2159 array_pop( $this->mArgStack );
2160
2161 wfProfileOut( $fname );
2162 return $text;
2163 }
2164
2165 /**
2166 * Replace magic variables
2167 * @access private
2168 */
2169 function variableSubstitution( $matches ) {
2170 $fname = 'parser::variableSubstitution';
2171 $varname = $matches[1];
2172 wfProfileIn( $fname );
2173 if ( !$this->mVariables ) {
2174 $this->initialiseVariables();
2175 }
2176 $skip = false;
2177 if ( $this->mOutputType == OT_WIKI ) {
2178 # Do only magic variables prefixed by SUBST
2179 $mwSubst =& MagicWord::get( MAG_SUBST );
2180 if (!$mwSubst->matchStartAndRemove( $varname ))
2181 $skip = true;
2182 # Note that if we don't substitute the variable below,
2183 # we don't remove the {{subst:}} magic word, in case
2184 # it is a template rather than a magic variable.
2185 }
2186 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2187 $id = $this->mVariables[$varname];
2188 $text = $this->getVariableValue( $id );
2189 $this->mOutput->mContainsOldMagic = true;
2190 } else {
2191 $text = $matches[0];
2192 }
2193 wfProfileOut( $fname );
2194 return $text;
2195 }
2196
2197 # Split template arguments
2198 function getTemplateArgs( $argsString ) {
2199 if ( $argsString === '' ) {
2200 return array();
2201 }
2202
2203 $args = explode( '|', substr( $argsString, 1 ) );
2204
2205 # If any of the arguments contains a '[[' but no ']]', it needs to be
2206 # merged with the next arg because the '|' character between belongs
2207 # to the link syntax and not the template parameter syntax.
2208 $argc = count($args);
2209
2210 for ( $i = 0; $i < $argc-1; $i++ ) {
2211 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2212 $args[$i] .= '|'.$args[$i+1];
2213 array_splice($args, $i+1, 1);
2214 $i--;
2215 $argc--;
2216 }
2217 }
2218
2219 return $args;
2220 }
2221
2222 /**
2223 * Return the text of a template, after recursively
2224 * replacing any variables or templates within the template.
2225 *
2226 * @param array $piece The parts of the template
2227 * $piece['text']: matched text
2228 * $piece['title']: the title, i.e. the part before the |
2229 * $piece['parts']: the parameter array
2230 * @return string the text of the template
2231 * @access private
2232 */
2233 function braceSubstitution( $piece ) {
2234 global $wgLinkCache, $wgContLang;
2235 $fname = 'Parser::braceSubstitution';
2236 wfProfileIn( $fname );
2237
2238 $found = false;
2239 $nowiki = false;
2240 $noparse = false;
2241
2242 $title = NULL;
2243
2244 $linestart = '';
2245
2246 # $part1 is the bit before the first |, and must contain only title characters
2247 # $args is a list of arguments, starting from index 0, not including $part1
2248
2249 $part1 = $piece['title'];
2250 # If the third subpattern matched anything, it will start with |
2251
2252 if (null == $piece['parts']) {
2253 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2254 if ($replaceWith != $piece['text']) {
2255 $text = $replaceWith;
2256 $found = true;
2257 $noparse = true;
2258 }
2259 }
2260
2261 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2262 $argc = count( $args );
2263
2264 # SUBST
2265 if ( !$found ) {
2266 $mwSubst =& MagicWord::get( MAG_SUBST );
2267 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2268 # One of two possibilities is true:
2269 # 1) Found SUBST but not in the PST phase
2270 # 2) Didn't find SUBST and in the PST phase
2271 # In either case, return without further processing
2272 $text = $piece['text'];
2273 $found = true;
2274 $noparse = true;
2275 }
2276 }
2277
2278 # MSG, MSGNW and INT
2279 if ( !$found ) {
2280 # Check for MSGNW:
2281 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2282 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2283 $nowiki = true;
2284 } else {
2285 # Remove obsolete MSG:
2286 $mwMsg =& MagicWord::get( MAG_MSG );
2287 $mwMsg->matchStartAndRemove( $part1 );
2288 }
2289
2290 # Check if it is an internal message
2291 $mwInt =& MagicWord::get( MAG_INT );
2292 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2293 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2294 $text = $linestart . wfMsgReal( $part1, $args, true );
2295 $found = true;
2296 }
2297 }
2298 }
2299
2300 # NS
2301 if ( !$found ) {
2302 # Check for NS: (namespace expansion)
2303 $mwNs = MagicWord::get( MAG_NS );
2304 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2305 if ( intval( $part1 ) ) {
2306 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2307 $found = true;
2308 } else {
2309 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2310 if ( !is_null( $index ) ) {
2311 $text = $linestart . $wgContLang->getNsText( $index );
2312 $found = true;
2313 }
2314 }
2315 }
2316 }
2317
2318 # LCFIRST, UCFIRST, LC and UC
2319 if ( !$found ) {
2320 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2321 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2322 $lc =& MagicWord::get( MAG_LC );
2323 $uc =& MagicWord::get( MAG_UC );
2324 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2325 $text = $linestart . $wgContLang->lcfirst( $part1 );
2326 $found = true;
2327 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2328 $text = $linestart . $wgContLang->ucfirst( $part1 );
2329 $found = true;
2330 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2331 $text = $linestart . $wgContLang->lc( $part1 );
2332 $found = true;
2333 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2334 $text = $linestart . $wgContLang->uc( $part1 );
2335 $found = true;
2336 }
2337 }
2338
2339 # LOCALURL and FULLURL
2340 if ( !$found ) {
2341 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2342 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2343 $mwFull =& MagicWord::get( MAG_FULLURL );
2344 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2345
2346
2347 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2348 $func = 'getLocalURL';
2349 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2350 $func = 'escapeLocalURL';
2351 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2352 $func = 'getFullURL';
2353 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2354 $func = 'escapeFullURL';
2355 } else {
2356 $func = false;
2357 }
2358
2359 if ( $func !== false ) {
2360 $title = Title::newFromText( $part1 );
2361 if ( !is_null( $title ) ) {
2362 if ( $argc > 0 ) {
2363 $text = $linestart . $title->$func( $args[0] );
2364 } else {
2365 $text = $linestart . $title->$func();
2366 }
2367 $found = true;
2368 }
2369 }
2370 }
2371
2372 # GRAMMAR
2373 if ( !$found && $argc == 1 ) {
2374 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2375 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2376 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2377 $found = true;
2378 }
2379 }
2380
2381 # PLURAL
2382 if ( !$found && $argc >= 2 ) {
2383 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2384 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2385 if ($argc==2) {$args[2]=$args[1];}
2386 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2387 $found = true;
2388 }
2389 }
2390
2391 # Template table test
2392
2393 # Did we encounter this template already? If yes, it is in the cache
2394 # and we need to check for loops.
2395 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
2396 $found = true;
2397
2398 # Infinite loop test
2399 if ( isset( $this->mTemplatePath[$part1] ) ) {
2400 $noparse = true;
2401 $found = true;
2402 $text = $linestart .
2403 "\{\{$part1}}" .
2404 '<!-- WARNING: template loop detected -->';
2405 wfDebug( "$fname: template loop broken at '$part1'\n" );
2406 } else {
2407 # set $text to cached message.
2408 $text = $linestart . $this->mTemplates[$part1];
2409 }
2410 }
2411
2412 # Load from database
2413 $replaceHeadings = false;
2414 $isHTML = false;
2415 $lastPathLevel = $this->mTemplatePath;
2416 if ( !$found ) {
2417 $ns = NS_TEMPLATE;
2418 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2419 if ($subpage !== '') {
2420 $ns = $this->mTitle->getNamespace();
2421 }
2422 $title = Title::newFromText( $part1, $ns );
2423
2424 if ($title) {
2425 $interwiki = Title::getInterwikiLink($title->getInterwiki());
2426 if ($interwiki != '' && $title->isTrans()) {
2427 return $this->scarytransclude($title, $interwiki);
2428 }
2429 }
2430
2431 if ( !is_null( $title ) && !$title->isExternal() ) {
2432 # Check for excessive inclusion
2433 $dbk = $title->getPrefixedDBkey();
2434 if ( $this->incrementIncludeCount( $dbk ) ) {
2435 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2436 # Capture special page output
2437 $text = SpecialPage::capturePath( $title );
2438 if ( is_string( $text ) ) {
2439 $found = true;
2440 $noparse = true;
2441 $isHTML = true;
2442 $this->disableCache();
2443 }
2444 } else {
2445 $article = new Article( $title );
2446 $articleContent = $article->fetchContent(0, false);
2447 if ( $articleContent !== false ) {
2448 $found = true;
2449 $text = $articleContent;
2450 $replaceHeadings = true;
2451 }
2452 }
2453 }
2454
2455 # If the title is valid but undisplayable, make a link to it
2456 if ( $this->mOutputType == OT_HTML && !$found ) {
2457 $text = '[['.$title->getPrefixedText().']]';
2458 $found = true;
2459 }
2460
2461 # Template cache array insertion
2462 if( $found ) {
2463 $this->mTemplates[$part1] = $text;
2464 $text = $linestart . $text;
2465 }
2466 }
2467 }
2468
2469 # Recursive parsing, escaping and link table handling
2470 # Only for HTML output
2471 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2472 $text = wfEscapeWikiText( $text );
2473 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2474 # Clean up argument array
2475 $assocArgs = array();
2476 $index = 1;
2477 foreach( $args as $arg ) {
2478 $eqpos = strpos( $arg, '=' );
2479 if ( $eqpos === false ) {
2480 $assocArgs[$index++] = $arg;
2481 } else {
2482 $name = trim( substr( $arg, 0, $eqpos ) );
2483 $value = trim( substr( $arg, $eqpos+1 ) );
2484 if ( $value === false ) {
2485 $value = '';
2486 }
2487 if ( $name !== false ) {
2488 $assocArgs[$name] = $value;
2489 }
2490 }
2491 }
2492
2493 # Add a new element to the templace recursion path
2494 $this->mTemplatePath[$part1] = 1;
2495
2496 if( $this->mOutputType == OT_HTML ) {
2497 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2498 preg_match_all( '/<onlyinclude>(.*?)<\/onlyinclude>/s', $text, $m );
2499 $text = '';
2500 foreach ($m[1] as $piece)
2501 $text .= $piece;
2502 }
2503 # Remove <noinclude> sections and <includeonly> tags
2504 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2505 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2506 # Strip <nowiki>, <pre>, etc.
2507 $text = $this->strip( $text, $this->mStripState );
2508 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2509 }
2510 $text = $this->replaceVariables( $text, $assocArgs );
2511
2512 # Resume the link cache and register the inclusion as a link
2513 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2514 $wgLinkCache->addLinkObj( $title );
2515 }
2516
2517 # If the template begins with a table or block-level
2518 # element, it should be treated as beginning a new line.
2519 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2520 $text = "\n" . $text;
2521 }
2522 }
2523 # Prune lower levels off the recursion check path
2524 $this->mTemplatePath = $lastPathLevel;
2525
2526 if ( !$found ) {
2527 wfProfileOut( $fname );
2528 return $piece['text'];
2529 } else {
2530 if ( $isHTML ) {
2531 # Replace raw HTML by a placeholder
2532 # Add a blank line preceding, to prevent it from mucking up
2533 # immediately preceding headings
2534 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2535 } else {
2536 # replace ==section headers==
2537 # XXX this needs to go away once we have a better parser.
2538 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2539 if( !is_null( $title ) )
2540 $encodedname = base64_encode($title->getPrefixedDBkey());
2541 else
2542 $encodedname = base64_encode("");
2543 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2544 PREG_SPLIT_DELIM_CAPTURE);
2545 $text = '';
2546 $nsec = 0;
2547 for( $i = 0; $i < count($m); $i += 2 ) {
2548 $text .= $m[$i];
2549 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2550 $hl = $m[$i + 1];
2551 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2552 $text .= $hl;
2553 continue;
2554 }
2555 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2556 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2557 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2558
2559 $nsec++;
2560 }
2561 }
2562 }
2563 }
2564
2565 # Prune lower levels off the recursion check path
2566 $this->mTemplatePath = $lastPathLevel;
2567
2568 if ( !$found ) {
2569 wfProfileOut( $fname );
2570 return $piece['text'];
2571 } else {
2572 wfProfileOut( $fname );
2573 return $text;
2574 }
2575 }
2576
2577 /**
2578 * Translude an interwiki link.
2579 */
2580 function scarytransclude($title, $interwiki) {
2581 global $wgEnableScaryTranscluding;
2582
2583 if (!$wgEnableScaryTranscluding)
2584 return wfMsg('scarytranscludedisabled');
2585
2586 $articlename = "Template:" . $title->getDBkey();
2587 $url = str_replace('$1', urlencode($articlename), $interwiki);
2588 if (strlen($url) > 255)
2589 return wfMsg('scarytranscludetoolong');
2590 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2591 $this->mIWTransData[] = $text;
2592 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData) - 1)."-->";
2593 }
2594
2595 function fetchScaryTemplateMaybeFromCache($url) {
2596 $dbr =& wfGetDB(DB_SLAVE);
2597 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2598 array('tc_url' => $url));
2599 if ($obj) {
2600 $time = $obj->tc_time;
2601 $text = $obj->tc_contents;
2602 if ($time && $time < (time() + (60*60))) {
2603 return $text;
2604 }
2605 }
2606
2607 $text = wfGetHTTP($url . '?action=render');
2608 if (!$text)
2609 return wfMsg('scarytranscludefailed', $url);
2610
2611 $dbw =& wfGetDB(DB_MASTER);
2612 $dbw->replace('transcache', array(), array(
2613 'tc_url' => $url,
2614 'tc_time' => time(),
2615 'tc_contents' => $text));
2616 return $text;
2617 }
2618
2619
2620 /**
2621 * Triple brace replacement -- used for template arguments
2622 * @access private
2623 */
2624 function argSubstitution( $matches ) {
2625 $arg = trim( $matches['title'] );
2626 $text = $matches['text'];
2627 $inputArgs = end( $this->mArgStack );
2628
2629 if ( array_key_exists( $arg, $inputArgs ) ) {
2630 $text = $inputArgs[$arg];
2631 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
2632 $text = $matches['parts'][0];
2633 }
2634
2635 return $text;
2636 }
2637
2638 /**
2639 * Returns true if the function is allowed to include this entity
2640 * @access private
2641 */
2642 function incrementIncludeCount( $dbk ) {
2643 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2644 $this->mIncludeCount[$dbk] = 0;
2645 }
2646 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2647 return true;
2648 } else {
2649 return false;
2650 }
2651 }
2652
2653 /**
2654 * This function accomplishes several tasks:
2655 * 1) Auto-number headings if that option is enabled
2656 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2657 * 3) Add a Table of contents on the top for users who have enabled the option
2658 * 4) Auto-anchor headings
2659 *
2660 * It loops through all headlines, collects the necessary data, then splits up the
2661 * string and re-inserts the newly formatted headlines.
2662 *
2663 * @param string $text
2664 * @param boolean $isMain
2665 * @access private
2666 */
2667 function formatHeadings( $text, $isMain=true ) {
2668 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2669
2670 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2671 $doShowToc = true;
2672 $forceTocHere = false;
2673 if( !$this->mTitle->userCanEdit() ) {
2674 $showEditLink = 0;
2675 } else {
2676 $showEditLink = $this->mOptions->getEditSection();
2677 }
2678
2679 # Inhibit editsection links if requested in the page
2680 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2681 if( $esw->matchAndRemove( $text ) ) {
2682 $showEditLink = 0;
2683 }
2684 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2685 # do not add TOC
2686 $mw =& MagicWord::get( MAG_NOTOC );
2687 if( $mw->matchAndRemove( $text ) ) {
2688 $doShowToc = false;
2689 }
2690
2691 # Get all headlines for numbering them and adding funky stuff like [edit]
2692 # links - this is for later, but we need the number of headlines right now
2693 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2694
2695 # if there are fewer than 4 headlines in the article, do not show TOC
2696 if( $numMatches < 4 ) {
2697 $doShowToc = false;
2698 }
2699
2700 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2701 # override above conditions and always show TOC at that place
2702
2703 $mw =& MagicWord::get( MAG_TOC );
2704 if($mw->match( $text ) ) {
2705 $doShowToc = true;
2706 $forceTocHere = true;
2707 } else {
2708 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2709 # override above conditions and always show TOC above first header
2710 $mw =& MagicWord::get( MAG_FORCETOC );
2711 if ($mw->matchAndRemove( $text ) ) {
2712 $doShowToc = true;
2713 }
2714 }
2715
2716 # Never ever show TOC if no headers
2717 if( $numMatches < 1 ) {
2718 $doShowToc = false;
2719 }
2720
2721 # We need this to perform operations on the HTML
2722 $sk =& $this->mOptions->getSkin();
2723
2724 # headline counter
2725 $headlineCount = 0;
2726 $sectionCount = 0; # headlineCount excluding template sections
2727
2728 # Ugh .. the TOC should have neat indentation levels which can be
2729 # passed to the skin functions. These are determined here
2730 $toc = '';
2731 $full = '';
2732 $head = array();
2733 $sublevelCount = array();
2734 $levelCount = array();
2735 $toclevel = 0;
2736 $level = 0;
2737 $prevlevel = 0;
2738 $toclevel = 0;
2739 $prevtoclevel = 0;
2740
2741 foreach( $matches[3] as $headline ) {
2742 $istemplate = 0;
2743 $templatetitle = '';
2744 $templatesection = 0;
2745 $numbering = '';
2746
2747 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2748 $istemplate = 1;
2749 $templatetitle = base64_decode($mat[1]);
2750 $templatesection = 1 + (int)base64_decode($mat[2]);
2751 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2752 }
2753
2754 if( $toclevel ) {
2755 $prevlevel = $level;
2756 $prevtoclevel = $toclevel;
2757 }
2758 $level = $matches[1][$headlineCount];
2759
2760 if( $doNumberHeadings || $doShowToc ) {
2761
2762 if ( $level > $prevlevel ) {
2763 # Increase TOC level
2764 $toclevel++;
2765 $sublevelCount[$toclevel] = 0;
2766 $toc .= $sk->tocIndent();
2767 }
2768 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2769 # Decrease TOC level, find level to jump to
2770
2771 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2772 # Can only go down to level 1
2773 $toclevel = 1;
2774 } else {
2775 for ($i = $toclevel; $i > 0; $i--) {
2776 if ( $levelCount[$i] == $level ) {
2777 # Found last matching level
2778 $toclevel = $i;
2779 break;
2780 }
2781 elseif ( $levelCount[$i] < $level ) {
2782 # Found first matching level below current level
2783 $toclevel = $i + 1;
2784 break;
2785 }
2786 }
2787 }
2788
2789 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2790 }
2791 else {
2792 # No change in level, end TOC line
2793 $toc .= $sk->tocLineEnd();
2794 }
2795
2796 $levelCount[$toclevel] = $level;
2797
2798 # count number of headlines for each level
2799 @$sublevelCount[$toclevel]++;
2800 $dot = 0;
2801 for( $i = 1; $i <= $toclevel; $i++ ) {
2802 if( !empty( $sublevelCount[$i] ) ) {
2803 if( $dot ) {
2804 $numbering .= '.';
2805 }
2806 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2807 $dot = 1;
2808 }
2809 }
2810 }
2811
2812 # The canonized header is a version of the header text safe to use for links
2813 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2814 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2815 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2816
2817 # Remove link placeholders by the link text.
2818 # <!--LINK number-->
2819 # turns into
2820 # link text with suffix
2821 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2822 "\$this->mLinkHolders['texts'][\$1]",
2823 $canonized_headline );
2824 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2825 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2826 $canonized_headline );
2827
2828 # strip out HTML
2829 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2830 $tocline = trim( $canonized_headline );
2831 $canonized_headline = urlencode( Sanitizer::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2832 $replacearray = array(
2833 '%3A' => ':',
2834 '%' => '.'
2835 );
2836 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2837 $refers[$headlineCount] = $canonized_headline;
2838
2839 # count how many in assoc. array so we can track dupes in anchors
2840 @$refers[$canonized_headline]++;
2841 $refcount[$headlineCount]=$refers[$canonized_headline];
2842
2843 # Don't number the heading if it is the only one (looks silly)
2844 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2845 # the two are different if the line contains a link
2846 $headline=$numbering . ' ' . $headline;
2847 }
2848
2849 # Create the anchor for linking from the TOC to the section
2850 $anchor = $canonized_headline;
2851 if($refcount[$headlineCount] > 1 ) {
2852 $anchor .= '_' . $refcount[$headlineCount];
2853 }
2854 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2855 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2856 }
2857 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2858 if ( empty( $head[$headlineCount] ) ) {
2859 $head[$headlineCount] = '';
2860 }
2861 if( $istemplate )
2862 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2863 else
2864 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2865 }
2866
2867 # give headline the correct <h#> tag
2868 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2869
2870 $headlineCount++;
2871 if( !$istemplate )
2872 $sectionCount++;
2873 }
2874
2875 if( $doShowToc ) {
2876 $toc .= $sk->tocUnindent( $toclevel - 1 );
2877 $toc = $sk->tocList( $toc );
2878 }
2879
2880 # split up and insert constructed headlines
2881
2882 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2883 $i = 0;
2884
2885 foreach( $blocks as $block ) {
2886 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2887 # This is the [edit] link that appears for the top block of text when
2888 # section editing is enabled
2889
2890 # Disabled because it broke block formatting
2891 # For example, a bullet point in the top line
2892 # $full .= $sk->editSectionLink(0);
2893 }
2894 $full .= $block;
2895 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2896 # Top anchor now in skin
2897 $full = $full.$toc;
2898 }
2899
2900 if( !empty( $head[$i] ) ) {
2901 $full .= $head[$i];
2902 }
2903 $i++;
2904 }
2905 if($forceTocHere) {
2906 $mw =& MagicWord::get( MAG_TOC );
2907 return $mw->replace( $toc, $full );
2908 } else {
2909 return $full;
2910 }
2911 }
2912
2913 /**
2914 * Return an HTML link for the "ISBN 123456" text
2915 * @access private
2916 */
2917 function magicISBN( $text ) {
2918 $fname = 'Parser::magicISBN';
2919 wfProfileIn( $fname );
2920
2921 $a = split( 'ISBN ', ' '.$text );
2922 if ( count ( $a ) < 2 ) {
2923 wfProfileOut( $fname );
2924 return $text;
2925 }
2926 $text = substr( array_shift( $a ), 1);
2927 $valid = '0123456789-Xx';
2928
2929 foreach ( $a as $x ) {
2930 $isbn = $blank = '' ;
2931 while ( ' ' == $x{0} ) {
2932 $blank .= ' ';
2933 $x = substr( $x, 1 );
2934 }
2935 if ( $x == '' ) { # blank isbn
2936 $text .= "ISBN $blank";
2937 continue;
2938 }
2939 while ( strstr( $valid, $x{0} ) != false ) {
2940 $isbn .= $x{0};
2941 $x = substr( $x, 1 );
2942 }
2943 $num = str_replace( '-', '', $isbn );
2944 $num = str_replace( ' ', '', $num );
2945 $num = str_replace( 'x', 'X', $num );
2946
2947 if ( '' == $num ) {
2948 $text .= "ISBN $blank$x";
2949 } else {
2950 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2951 $text .= '<a href="' .
2952 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2953 "\" class=\"internal\">ISBN $isbn</a>";
2954 $text .= $x;
2955 }
2956 }
2957 wfProfileOut( $fname );
2958 return $text;
2959 }
2960
2961 /**
2962 * Return an HTML link for the "RFC 1234" text
2963 *
2964 * @access private
2965 * @param string $text Text to be processed
2966 * @param string $keyword Magic keyword to use (default RFC)
2967 * @param string $urlmsg Interface message to use (default rfcurl)
2968 * @return string
2969 */
2970 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2971
2972 $valid = '0123456789';
2973 $internal = false;
2974
2975 $a = split( $keyword, ' '.$text );
2976 if ( count ( $a ) < 2 ) {
2977 return $text;
2978 }
2979 $text = substr( array_shift( $a ), 1);
2980
2981 /* Check if keyword is preceed by [[.
2982 * This test is made here cause of the array_shift above
2983 * that prevent the test to be done in the foreach.
2984 */
2985 if ( substr( $text, -2 ) == '[[' ) {
2986 $internal = true;
2987 }
2988
2989 foreach ( $a as $x ) {
2990 /* token might be empty if we have RFC RFC 1234 */
2991 if ( $x=='' ) {
2992 $text.=$keyword;
2993 continue;
2994 }
2995
2996 $id = $blank = '' ;
2997
2998 /** remove and save whitespaces in $blank */
2999 while ( $x{0} == ' ' ) {
3000 $blank .= ' ';
3001 $x = substr( $x, 1 );
3002 }
3003
3004 /** remove and save the rfc number in $id */
3005 while ( strstr( $valid, $x{0} ) != false ) {
3006 $id .= $x{0};
3007 $x = substr( $x, 1 );
3008 }
3009
3010 if ( $id == '' ) {
3011 /* call back stripped spaces*/
3012 $text .= $keyword.$blank.$x;
3013 } elseif( $internal ) {
3014 /* normal link */
3015 $text .= $keyword.$id.$x;
3016 } else {
3017 /* build the external link*/
3018 $url = wfMsg( $urlmsg, $id);
3019 $sk =& $this->mOptions->getSkin();
3020 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3021 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3022 }
3023
3024 /* Check if the next RFC keyword is preceed by [[ */
3025 $internal = ( substr($x,-2) == '[[' );
3026 }
3027 return $text;
3028 }
3029
3030 /**
3031 * Transform wiki markup when saving a page by doing \r\n -> \n
3032 * conversion, substitting signatures, {{subst:}} templates, etc.
3033 *
3034 * @param string $text the text to transform
3035 * @param Title &$title the Title object for the current article
3036 * @param User &$user the User object describing the current user
3037 * @param ParserOptions $options parsing options
3038 * @param bool $clearState whether to clear the parser state first
3039 * @return string the altered wiki markup
3040 * @access public
3041 */
3042 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3043 $this->mOptions = $options;
3044 $this->mTitle =& $title;
3045 $this->mOutputType = OT_WIKI;
3046
3047 if ( $clearState ) {
3048 $this->clearState();
3049 }
3050
3051 $stripState = false;
3052 $pairs = array(
3053 "\r\n" => "\n",
3054 );
3055 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3056 $text = $this->strip( $text, $stripState, false );
3057 $text = $this->pstPass2( $text, $user );
3058 $text = $this->unstrip( $text, $stripState );
3059 $text = $this->unstripNoWiki( $text, $stripState );
3060 return $text;
3061 }
3062
3063 /**
3064 * Pre-save transform helper function
3065 * @access private
3066 */
3067 function pstPass2( $text, &$user ) {
3068 global $wgContLang, $wgLocaltimezone;
3069
3070 # Variable replacement
3071 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3072 $text = $this->replaceVariables( $text );
3073
3074 # Signatures
3075 #
3076 $n = $user->getName();
3077 $k = $user->getOption( 'nickname' );
3078 if ( '' == $k ) { $k = $n; }
3079 if ( isset( $wgLocaltimezone ) ) {
3080 $oldtz = getenv( 'TZ' );
3081 putenv( 'TZ='.$wgLocaltimezone );
3082 }
3083
3084 /* Note: This is the timestamp saved as hardcoded wikitext to
3085 * the database, we use $wgContLang here in order to give
3086 * everyone the same signiture and use the default one rather
3087 * than the one selected in each users preferences.
3088 */
3089 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3090 ' (' . date( 'T' ) . ')';
3091 if ( isset( $wgLocaltimezone ) ) {
3092 putenv( 'TZ='.$oldtz );
3093 }
3094
3095 if( $user->getOption( 'fancysig' ) ) {
3096 $sigText = $k;
3097 } else {
3098 $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
3099 }
3100 $text = preg_replace( '/~~~~~/', $d, $text );
3101 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3102 $text = preg_replace( '/~~~/', $sigText, $text );
3103
3104 # Context links: [[|name]] and [[name (context)|]]
3105 #
3106 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
3107 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
3108 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3109 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3110
3111 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3112 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3113 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3114 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3115 $context = '';
3116 $t = $this->mTitle->getText();
3117 if ( preg_match( $conpat, $t, $m ) ) {
3118 $context = $m[2];
3119 }
3120 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3121 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3122 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3123
3124 if ( '' == $context ) {
3125 $text = preg_replace( $p2, '[[\\1]]', $text );
3126 } else {
3127 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3128 }
3129
3130 # Trim trailing whitespace
3131 # MAG_END (__END__) tag allows for trailing
3132 # whitespace to be deliberately included
3133 $text = rtrim( $text );
3134 $mw =& MagicWord::get( MAG_END );
3135 $mw->matchAndRemove( $text );
3136
3137 return $text;
3138 }
3139
3140 /**
3141 * Set up some variables which are usually set up in parse()
3142 * so that an external function can call some class members with confidence
3143 * @access public
3144 */
3145 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3146 $this->mTitle =& $title;
3147 $this->mOptions = $options;
3148 $this->mOutputType = $outputType;
3149 if ( $clearState ) {
3150 $this->clearState();
3151 }
3152 }
3153
3154 /**
3155 * Transform a MediaWiki message by replacing magic variables.
3156 *
3157 * @param string $text the text to transform
3158 * @param ParserOptions $options options
3159 * @return string the text with variables substituted
3160 * @access public
3161 */
3162 function transformMsg( $text, $options ) {
3163 global $wgTitle;
3164 static $executing = false;
3165
3166 # Guard against infinite recursion
3167 if ( $executing ) {
3168 return $text;
3169 }
3170 $executing = true;
3171
3172 $this->mTitle = $wgTitle;
3173 $this->mOptions = $options;
3174 $this->mOutputType = OT_MSG;
3175 $this->clearState();
3176 $text = $this->replaceVariables( $text );
3177
3178 $executing = false;
3179 return $text;
3180 }
3181
3182 /**
3183 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3184 * Callback will be called with the text within
3185 * Transform and return the text within
3186 * @access public
3187 */
3188 function setHook( $tag, $callback ) {
3189 $oldVal = @$this->mTagHooks[$tag];
3190 $this->mTagHooks[$tag] = $callback;
3191 return $oldVal;
3192 }
3193
3194 /**
3195 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3196 * Placeholders created in Skin::makeLinkObj()
3197 * Returns an array of links found, indexed by PDBK:
3198 * 0 - broken
3199 * 1 - normal link
3200 * 2 - stub
3201 * $options is a bit field, RLH_FOR_UPDATE to select for update
3202 */
3203 function replaceLinkHolders( &$text, $options = 0 ) {
3204 global $wgUser, $wgLinkCache;
3205 global $wgOutputReplace;
3206
3207 $fname = 'Parser::replaceLinkHolders';
3208 wfProfileIn( $fname );
3209
3210 $pdbks = array();
3211 $colours = array();
3212 $sk = $this->mOptions->getSkin();
3213
3214 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3215 wfProfileIn( $fname.'-check' );
3216 $dbr =& wfGetDB( DB_SLAVE );
3217 $page = $dbr->tableName( 'page' );
3218 $threshold = $wgUser->getOption('stubthreshold');
3219
3220 # Sort by namespace
3221 asort( $this->mLinkHolders['namespaces'] );
3222
3223 # Generate query
3224 $query = false;
3225 foreach ( $this->mLinkHolders['namespaces'] as $key => $val ) {
3226 # Make title object
3227 $title = $this->mLinkHolders['titles'][$key];
3228
3229 # Skip invalid entries.
3230 # Result will be ugly, but prevents crash.
3231 if ( is_null( $title ) ) {
3232 continue;
3233 }
3234 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3235
3236 # Check if it's in the link cache already
3237 if ( $title->isAlwaysKnown() || $wgLinkCache->getGoodLinkID( $pdbk ) ) {
3238 $colours[$pdbk] = 1;
3239 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3240 $colours[$pdbk] = 0;
3241 } else {
3242 # Not in the link cache, add it to the query
3243 if ( !isset( $current ) ) {
3244 $current = $val;
3245 $query = "SELECT page_id, page_namespace, page_title";
3246 if ( $threshold > 0 ) {
3247 $query .= ', page_len, page_is_redirect';
3248 }
3249 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3250 } elseif ( $current != $val ) {
3251 $current = $val;
3252 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3253 } else {
3254 $query .= ', ';
3255 }
3256
3257 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3258 }
3259 }
3260 if ( $query ) {
3261 $query .= '))';
3262 if ( $options & RLH_FOR_UPDATE ) {
3263 $query .= ' FOR UPDATE';
3264 }
3265
3266 $res = $dbr->query( $query, $fname );
3267
3268 # Fetch data and form into an associative array
3269 # non-existent = broken
3270 # 1 = known
3271 # 2 = stub
3272 while ( $s = $dbr->fetchObject($res) ) {
3273 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3274 $pdbk = $title->getPrefixedDBkey();
3275 $wgLinkCache->addGoodLinkObj( $s->page_id, $title );
3276
3277 if ( $threshold > 0 ) {
3278 $size = $s->page_len;
3279 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3280 $colours[$pdbk] = 1;
3281 } else {
3282 $colours[$pdbk] = 2;
3283 }
3284 } else {
3285 $colours[$pdbk] = 1;
3286 }
3287 }
3288 }
3289 wfProfileOut( $fname.'-check' );
3290
3291 # Construct search and replace arrays
3292 wfProfileIn( $fname.'-construct' );
3293 $wgOutputReplace = array();
3294 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3295 $pdbk = $pdbks[$key];
3296 $searchkey = "<!--LINK $key-->";
3297 $title = $this->mLinkHolders['titles'][$key];
3298 if ( empty( $colours[$pdbk] ) ) {
3299 $wgLinkCache->addBadLinkObj( $title );
3300 $colours[$pdbk] = 0;
3301 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3302 $this->mLinkHolders['texts'][$key],
3303 $this->mLinkHolders['queries'][$key] );
3304 } elseif ( $colours[$pdbk] == 1 ) {
3305 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3306 $this->mLinkHolders['texts'][$key],
3307 $this->mLinkHolders['queries'][$key] );
3308 } elseif ( $colours[$pdbk] == 2 ) {
3309 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3310 $this->mLinkHolders['texts'][$key],
3311 $this->mLinkHolders['queries'][$key] );
3312 }
3313 }
3314 wfProfileOut( $fname.'-construct' );
3315
3316 # Do the thing
3317 wfProfileIn( $fname.'-replace' );
3318
3319 $text = preg_replace_callback(
3320 '/(<!--LINK .*?-->)/',
3321 "wfOutputReplaceMatches",
3322 $text);
3323
3324 wfProfileOut( $fname.'-replace' );
3325 }
3326
3327 # Now process interwiki link holders
3328 # This is quite a bit simpler than internal links
3329 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3330 wfProfileIn( $fname.'-interwiki' );
3331 # Make interwiki link HTML
3332 $wgOutputReplace = array();
3333 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3334 $title = $this->mInterwikiLinkHolders['titles'][$key];
3335 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3336 }
3337
3338 $text = preg_replace_callback(
3339 '/<!--IWLINK (.*?)-->/',
3340 "wfOutputReplaceMatches",
3341 $text );
3342 wfProfileOut( $fname.'-interwiki' );
3343 }
3344
3345 wfProfileOut( $fname );
3346 return $colours;
3347 }
3348
3349 /**
3350 * Replace <!--LINK--> link placeholders with plain text of links
3351 * (not HTML-formatted).
3352 * @param string $text
3353 * @return string
3354 */
3355 function replaceLinkHoldersText( $text ) {
3356 global $wgUser, $wgLinkCache;
3357 global $wgOutputReplace;
3358
3359 $fname = 'Parser::replaceLinkHoldersText';
3360 wfProfileIn( $fname );
3361
3362 $text = preg_replace_callback(
3363 '/<!--(LINK|IWLINK) (.*?)-->/',
3364 array( &$this, 'replaceLinkHoldersTextCallback' ),
3365 $text );
3366
3367 wfProfileOut( $fname );
3368 return $text;
3369 }
3370
3371 /**
3372 * @param array $matches
3373 * @return string
3374 * @access private
3375 */
3376 function replaceLinkHoldersTextCallback( $matches ) {
3377 $type = $matches[1];
3378 $key = $matches[2];
3379 if( $type == 'LINK' ) {
3380 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3381 return $this->mLinkHolders['texts'][$key];
3382 }
3383 } elseif( $type == 'IWLINK' ) {
3384 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3385 return $this->mInterwikiLinkHolders['texts'][$key];
3386 }
3387 }
3388 return $matches[0];
3389 }
3390
3391 /**
3392 * Renders an image gallery from a text with one line per image.
3393 * text labels may be given by using |-style alternative text. E.g.
3394 * Image:one.jpg|The number "1"
3395 * Image:tree.jpg|A tree
3396 * given as text will return the HTML of a gallery with two images,
3397 * labeled 'The number "1"' and
3398 * 'A tree'.
3399 *
3400 * @static
3401 */
3402 function renderImageGallery( $text ) {
3403 # Setup the parser
3404 global $wgUser, $wgTitle;
3405 $parserOptions = ParserOptions::newFromUser( $wgUser );
3406 $localParser = new Parser();
3407
3408 global $wgLinkCache;
3409 $ig = new ImageGallery();
3410 $ig->setShowBytes( false );
3411 $ig->setShowFilename( false );
3412 $lines = explode( "\n", $text );
3413
3414 foreach ( $lines as $line ) {
3415 # match lines like these:
3416 # Image:someimage.jpg|This is some image
3417 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3418 # Skip empty lines
3419 if ( count( $matches ) == 0 ) {
3420 continue;
3421 }
3422 $nt = Title::newFromURL( $matches[1] );
3423 if( is_null( $nt ) ) {
3424 # Bogus title. Ignore these so we don't bomb out later.
3425 continue;
3426 }
3427 if ( isset( $matches[3] ) ) {
3428 $label = $matches[3];
3429 } else {
3430 $label = '';
3431 }
3432
3433 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3434 $html = $html->mText;
3435
3436 $ig->add( new Image( $nt ), $html );
3437 $wgLinkCache->addImageLinkObj( $nt );
3438 }
3439 return $ig->toHTML();
3440 }
3441
3442 /**
3443 * Parse image options text and use it to make an image
3444 */
3445 function makeImage( &$nt, $options ) {
3446 global $wgContLang, $wgUseImageResize;
3447 global $wgUser, $wgThumbLimits;
3448
3449 $align = '';
3450
3451 # Check if the options text is of the form "options|alt text"
3452 # Options are:
3453 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3454 # * left no resizing, just left align. label is used for alt= only
3455 # * right same, but right aligned
3456 # * none same, but not aligned
3457 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3458 # * center center the image
3459 # * framed Keep original image size, no magnify-button.
3460
3461 $part = explode( '|', $options);
3462
3463 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3464 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
3465 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3466 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3467 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3468 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3469 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3470 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3471 $caption = '';
3472
3473 $width = $height = $framed = $thumb = false;
3474 $manual_thumb = '' ;
3475
3476 foreach( $part as $key => $val ) {
3477 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3478 $thumb=true;
3479 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3480 # use manually specified thumbnail
3481 $thumb=true;
3482 $manual_thumb = $match;
3483 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3484 # remember to set an alignment, don't render immediately
3485 $align = 'right';
3486 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3487 # remember to set an alignment, don't render immediately
3488 $align = 'left';
3489 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3490 # remember to set an alignment, don't render immediately
3491 $align = 'center';
3492 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3493 # remember to set an alignment, don't render immediately
3494 $align = 'none';
3495 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3496 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3497 # $match is the image width in pixels
3498 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3499 $width = intval( $m[1] );
3500 $height = intval( $m[2] );
3501 } else {
3502 $width = intval($match);
3503 }
3504 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3505 $framed=true;
3506 } else {
3507 $caption = $val;
3508 }
3509 }
3510 # Strip bad stuff out of the alt text
3511 $alt = $this->replaceLinkHoldersText( $caption );
3512 $alt = Sanitizer::stripAllTags( $alt );
3513
3514 # Linker does the rest
3515 $sk =& $this->mOptions->getSkin();
3516 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3517 }
3518
3519 /**
3520 * Set a flag in the output object indicating that the content is dynamic and
3521 * shouldn't be cached.
3522 */
3523 function disableCache() {
3524 $this->mOutput->mCacheTime = -1;
3525 }
3526
3527 /**
3528 * Callback from the Sanitizer for expanding items found in HTML attribute
3529 * values, so they can be safely tested and escaped.
3530 * @param string $text
3531 * @param array $args
3532 * @return string
3533 * @access private
3534 */
3535 function attributeStripCallback( &$text, $args ) {
3536 $text = $this->replaceVariables( $text, $args );
3537 $text = $this->unstripForHTML( $text );
3538 return $text;
3539 }
3540
3541 function unstripForHTML( $text ) {
3542 $text = $this->unstrip( $text, $this->mStripState );
3543 $text = $this->unstripNoWiki( $text, $this->mStripState );
3544 return $text;
3545 }
3546 }
3547
3548 /**
3549 * @todo document
3550 * @package MediaWiki
3551 */
3552 class ParserOutput
3553 {
3554 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3555 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3556 var $mVersion; # Compatibility check
3557 var $mTitleText; # title text of the chosen language variant
3558
3559 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3560 $containsOldMagic = false, $titletext = '' )
3561 {
3562 $this->mText = $text;
3563 $this->mLanguageLinks = $languageLinks;
3564 $this->mCategoryLinks = $categoryLinks;
3565 $this->mContainsOldMagic = $containsOldMagic;
3566 $this->mCacheTime = '';
3567 $this->mVersion = MW_PARSER_VERSION;
3568 $this->mTitleText = $titletext;
3569 }
3570
3571 function getText() { return $this->mText; }
3572 function getLanguageLinks() { return $this->mLanguageLinks; }
3573 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
3574 function getCacheTime() { return $this->mCacheTime; }
3575 function getTitleText() { return $this->mTitleText; }
3576 function containsOldMagic() { return $this->mContainsOldMagic; }
3577 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3578 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3579 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
3580 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3581 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3582 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3583
3584 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
3585
3586 function merge( $other ) {
3587 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3588 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3589 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3590 }
3591
3592 /**
3593 * Return true if this cached output object predates the global or
3594 * per-article cache invalidation timestamps, or if it comes from
3595 * an incompatible older version.
3596 *
3597 * @param string $touched the affected article's last touched timestamp
3598 * @return bool
3599 * @access public
3600 */
3601 function expired( $touched ) {
3602 global $wgCacheEpoch;
3603 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3604 $this->getCacheTime() <= $touched ||
3605 $this->getCacheTime() <= $wgCacheEpoch ||
3606 !isset( $this->mVersion ) ||
3607 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3608 }
3609 }
3610
3611 /**
3612 * Set options of the Parser
3613 * @todo document
3614 * @package MediaWiki
3615 */
3616 class ParserOptions
3617 {
3618 # All variables are private
3619 var $mUseTeX; # Use texvc to expand <math> tags
3620 var $mUseDynamicDates; # Use DateFormatter to format dates
3621 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3622 var $mAllowExternalImages; # Allow external images inline
3623 var $mAllowExternalImagesFrom; # If not, any exception?
3624 var $mSkin; # Reference to the preferred skin
3625 var $mDateFormat; # Date format index
3626 var $mEditSection; # Create "edit section" links
3627 var $mNumberHeadings; # Automatically number headings
3628 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3629
3630 function getUseTeX() { return $this->mUseTeX; }
3631 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3632 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3633 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3634 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
3635 function &getSkin() { return $this->mSkin; }
3636 function getDateFormat() { return $this->mDateFormat; }
3637 function getEditSection() { return $this->mEditSection; }
3638 function getNumberHeadings() { return $this->mNumberHeadings; }
3639 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3640
3641
3642 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3643 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3644 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3645 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3646 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
3647 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3648 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3649 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3650 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3651
3652 function setSkin( &$x ) { $this->mSkin =& $x; }
3653
3654 function ParserOptions() {
3655 global $wgUser;
3656 $this->initialiseFromUser( $wgUser );
3657 }
3658
3659 /**
3660 * Get parser options
3661 * @static
3662 */
3663 function newFromUser( &$user ) {
3664 $popts = new ParserOptions;
3665 $popts->initialiseFromUser( $user );
3666 return $popts;
3667 }
3668
3669 /** Get user options */
3670 function initialiseFromUser( &$userInput ) {
3671 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3672 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3673 $fname = 'ParserOptions::initialiseFromUser';
3674 wfProfileIn( $fname );
3675 if ( !$userInput ) {
3676 $user = new User;
3677 $user->setLoaded( true );
3678 } else {
3679 $user =& $userInput;
3680 }
3681
3682 $this->mUseTeX = $wgUseTeX;
3683 $this->mUseDynamicDates = $wgUseDynamicDates;
3684 $this->mInterwikiMagic = $wgInterwikiMagic;
3685 $this->mAllowExternalImages = $wgAllowExternalImages;
3686 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
3687 wfProfileIn( $fname.'-skin' );
3688 $this->mSkin =& $user->getSkin();
3689 wfProfileOut( $fname.'-skin' );
3690 $this->mDateFormat = $user->getOption( 'date' );
3691 $this->mEditSection = true;
3692 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3693 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
3694 wfProfileOut( $fname );
3695 }
3696 }
3697
3698 /**
3699 * Callback function used by Parser::replaceLinkHolders()
3700 * to substitute link placeholders.
3701 */
3702 function &wfOutputReplaceMatches( $matches ) {
3703 global $wgOutputReplace;
3704 return $wgOutputReplace[$matches[1]];
3705 }
3706
3707 /**
3708 * Return the total number of articles
3709 */
3710 function wfNumberOfArticles() {
3711 global $wgNumberOfArticles;
3712
3713 wfLoadSiteStats();
3714 return $wgNumberOfArticles;
3715 }
3716
3717 /**
3718 * Return the number of files
3719 */
3720 function wfNumberOfFiles() {
3721 $fname = 'Parser::wfNumberOfFiles';
3722
3723 wfProfileIn( $fname );
3724 $dbr =& wfGetDB( DB_SLAVE );
3725 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3726 wfProfileOut( $fname );
3727
3728 return $res;
3729 }
3730
3731 /**
3732 * Get various statistics from the database
3733 * @private
3734 */
3735 function wfLoadSiteStats() {
3736 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3737 $fname = 'wfLoadSiteStats';
3738
3739 if ( -1 != $wgNumberOfArticles ) return;
3740 $dbr =& wfGetDB( DB_SLAVE );
3741 $s = $dbr->selectRow( 'site_stats',
3742 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3743 array( 'ss_row_id' => 1 ), $fname
3744 );
3745
3746 if ( $s === false ) {
3747 return;
3748 } else {
3749 $wgTotalViews = $s->ss_total_views;
3750 $wgTotalEdits = $s->ss_total_edits;
3751 $wgNumberOfArticles = $s->ss_good_articles;
3752 }
3753 }
3754
3755 /**
3756 * Escape html tags
3757 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3758 *
3759 * @param string $in Text that might contain HTML tags
3760 * @return string Escaped string
3761 */
3762 function wfEscapeHTMLTagsOnly( $in ) {
3763 return str_replace(
3764 array( '"', '>', '<' ),
3765 array( '&quot;', '&gt;', '&lt;' ),
3766 $in );
3767 }
3768
3769 ?>