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