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