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