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