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