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