Always use reference assignment when taking the return value of wfGetDB(), or else...
[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 } else {
1242 $first_prefix = false;
1243 }
1244 } else {
1245 $prefix = '';
1246 }
1247
1248 $selflink = $this->mTitle->getPrefixedText();
1249 wfProfileOut( $fname.'-setup' );
1250
1251 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1252 $useSubpages = $this->areSubpagesAllowed();
1253
1254 # Loop for each link
1255 for ($k = 0; isset( $a[$k] ); $k++) {
1256 $line = $a[$k];
1257 if ( $useLinkPrefixExtension ) {
1258 wfProfileIn( $fname.'-prefixhandling' );
1259 if ( preg_match( $e2, $s, $m ) ) {
1260 $prefix = $m[2];
1261 $s = $m[1];
1262 } else {
1263 $prefix='';
1264 }
1265 # first link
1266 if($first_prefix) {
1267 $prefix = $first_prefix;
1268 $first_prefix = false;
1269 }
1270 wfProfileOut( $fname.'-prefixhandling' );
1271 }
1272
1273 $might_be_img = false;
1274
1275 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1276 $text = $m[2];
1277 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1278 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1279 # the real problem is with the $e1 regex
1280 # See bug 1300.
1281 #
1282 # Still some problems for cases where the ] is meant to be outside punctuation,
1283 # and no image is in sight. See bug 2095.
1284 #
1285 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1286 $text .= ']'; # so that replaceExternalLinks($text) works later
1287 $m[3] = $n[1];
1288 }
1289 # fix up urlencoded title texts
1290 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1291 $trail = $m[3];
1292 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1293 $might_be_img = true;
1294 $text = $m[2];
1295 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1296 $trail = "";
1297 } else { # Invalid form; output directly
1298 $s .= $prefix . '[[' . $line ;
1299 continue;
1300 }
1301
1302 # Don't allow internal links to pages containing
1303 # PROTO: where PROTO is a valid URL protocol; these
1304 # should be external links.
1305 if (preg_match('/^(\b(?:'.$wgUrlProtocols.'))/', $m[1])) {
1306 $s .= $prefix . '[[' . $line ;
1307 continue;
1308 }
1309
1310 # Make subpage if necessary
1311 if( $useSubpages ) {
1312 $link = $this->maybeDoSubpageLink( $m[1], $text );
1313 } else {
1314 $link = $m[1];
1315 }
1316
1317 $noforce = (substr($m[1], 0, 1) != ':');
1318 if (!$noforce) {
1319 # Strip off leading ':'
1320 $link = substr($link, 1);
1321 }
1322
1323 $nt = Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1324 if( !$nt ) {
1325 $s .= $prefix . '[[' . $line;
1326 continue;
1327 }
1328
1329 #check other language variants of the link
1330 #if the article does not exist
1331 if( $checkVariantLink
1332 && $nt->getArticleID() == 0 ) {
1333 $wgContLang->findVariantLink($link, $nt);
1334 }
1335
1336 $ns = $nt->getNamespace();
1337 $iw = $nt->getInterWiki();
1338
1339 if ($might_be_img) { # if this is actually an invalid link
1340 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1341 $found = false;
1342 while (isset ($a[$k+1]) ) {
1343 #look at the next 'line' to see if we can close it there
1344 $next_line = array_shift(array_splice( $a, $k + 1, 1) );
1345 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1346 # the first ]] closes the inner link, the second the image
1347 $found = true;
1348 $text .= '[[' . $m[1];
1349 $trail = $m[2];
1350 break;
1351 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1352 #if there's exactly one ]] that's fine, we'll keep looking
1353 $text .= '[[' . $m[0];
1354 } else {
1355 #if $next_line is invalid too, we need look no further
1356 $text .= '[[' . $next_line;
1357 break;
1358 }
1359 }
1360 if ( !$found ) {
1361 # we couldn't find the end of this imageLink, so output it raw
1362 #but don't ignore what might be perfectly normal links in the text we've examined
1363 $text = $this->replaceInternalLinks($text);
1364 $s .= $prefix . '[[' . $link . '|' . $text;
1365 # note: no $trail, because without an end, there *is* no trail
1366 continue;
1367 }
1368 } else { #it's not an image, so output it raw
1369 $s .= $prefix . '[[' . $link . '|' . $text;
1370 # note: no $trail, because without an end, there *is* no trail
1371 continue;
1372 }
1373 }
1374
1375 $wasblank = ( '' == $text );
1376 if( $wasblank ) $text = $link;
1377
1378
1379 # Link not escaped by : , create the various objects
1380 if( $noforce ) {
1381
1382 # Interwikis
1383 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1384 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1385 $s = rtrim($s . "\n");
1386 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1387 continue;
1388 }
1389
1390 if ( $ns == NS_IMAGE ) {
1391 wfProfileIn( "$fname-image" );
1392 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1393 # recursively parse links inside the image caption
1394 # actually, this will parse them in any other parameters, too,
1395 # but it might be hard to fix that, and it doesn't matter ATM
1396 $text = $this->replaceExternalLinks($text);
1397 $text = $this->replaceInternalLinks($text);
1398
1399 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1400 $s .= $prefix . str_replace('http://', 'http-noparse://', $this->makeImage( $nt, $text ) ) . $trail;
1401 $wgLinkCache->addImageLinkObj( $nt );
1402
1403 wfProfileOut( "$fname-image" );
1404 continue;
1405 }
1406 wfProfileOut( "$fname-image" );
1407
1408 }
1409
1410 if ( $ns == NS_CATEGORY ) {
1411 wfProfileIn( "$fname-category" );
1412 $t = $wgContLang->convertHtml( $nt->getText() );
1413 $s = rtrim($s . "\n"); # bug 87
1414
1415 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1416 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1417 $wgLinkCache->resume();
1418
1419 if ( $wasblank ) {
1420 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1421 $sortkey = $this->mTitle->getText();
1422 } else {
1423 $sortkey = $this->mTitle->getPrefixedText();
1424 }
1425 } else {
1426 $sortkey = $text;
1427 }
1428 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1429 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1430 $this->mOutput->addCategoryLink( $t );
1431
1432 /**
1433 * Strip the whitespace Category links produce, see bug 87
1434 * @todo We might want to use trim($tmp, "\n") here.
1435 */
1436 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1437
1438 wfProfileOut( "$fname-category" );
1439 continue;
1440 }
1441 }
1442
1443 if( ( $nt->getPrefixedText() === $selflink ) &&
1444 ( $nt->getFragment() === '' ) ) {
1445 # Self-links are handled specially; generally de-link and change to bold.
1446 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1447 continue;
1448 }
1449
1450 # Special and Media are pseudo-namespaces; no pages actually exist in them
1451 if( $ns == NS_MEDIA ) {
1452 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1453 $wgLinkCache->addImageLinkObj( $nt );
1454 continue;
1455 } elseif( $ns == NS_SPECIAL ) {
1456 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1457 continue;
1458 }
1459 if( !$nt->isExternal() && $nt->isAlwaysKnown() ) {
1460 /**
1461 * Skip lookups for special pages and self-links.
1462 * External interwiki links are not included here because
1463 * the HTTP urls would break output in the next parse step;
1464 * they will have placeholders kept.
1465 */
1466 $s .= $sk->makeKnownLinkObj( $nt, $text, '', $trail, $prefix );
1467 } else {
1468 /**
1469 * Add a link placeholder
1470 * Later, this will be replaced by a real link, after the existence or
1471 * non-existence of all the links is known
1472 */
1473 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1474 }
1475 }
1476 wfProfileOut( $fname );
1477 return $s;
1478 }
1479
1480 /**
1481 * Make a link placeholder. The text returned can be later resolved to a real link with
1482 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1483 * parsing of interwiki links, and secondly to allow all extistence checks and
1484 * article length checks (for stub links) to be bundled into a single query.
1485 *
1486 */
1487 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1488 if ( ! is_object($nt) ) {
1489 # Fail gracefully
1490 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1491 } else {
1492 # Separate the link trail from the rest of the link
1493 list( $inside, $trail ) = Linker::splitTrail( $trail );
1494
1495 if ( $nt->isExternal() ) {
1496 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1497 $this->mInterwikiLinkHolders['titles'][] = $nt;
1498 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1499 } else {
1500 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1501 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1502 $this->mLinkHolders['queries'][] = $query;
1503 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1504 $this->mLinkHolders['titles'][] = $nt;
1505
1506 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1507 }
1508 }
1509 return $retVal;
1510 }
1511
1512 /**
1513 * Return true if subpage links should be expanded on this page.
1514 * @return bool
1515 */
1516 function areSubpagesAllowed() {
1517 # Some namespaces don't allow subpages
1518 global $wgNamespacesWithSubpages;
1519 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1520 }
1521
1522 /**
1523 * Handle link to subpage if necessary
1524 * @param string $target the source of the link
1525 * @param string &$text the link text, modified as necessary
1526 * @return string the full name of the link
1527 * @access private
1528 */
1529 function maybeDoSubpageLink($target, &$text) {
1530 # Valid link forms:
1531 # Foobar -- normal
1532 # :Foobar -- override special treatment of prefix (images, language links)
1533 # /Foobar -- convert to CurrentPage/Foobar
1534 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1535 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1536 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1537
1538 $fname = 'Parser::maybeDoSubpageLink';
1539 wfProfileIn( $fname );
1540 $ret = $target; # default return value is no change
1541
1542 # Some namespaces don't allow subpages,
1543 # so only perform processing if subpages are allowed
1544 if( $this->areSubpagesAllowed() ) {
1545 # Look at the first character
1546 if( $target != '' && $target{0} == '/' ) {
1547 # / at end means we don't want the slash to be shown
1548 if( substr( $target, -1, 1 ) == '/' ) {
1549 $target = substr( $target, 1, -1 );
1550 $noslash = $target;
1551 } else {
1552 $noslash = substr( $target, 1 );
1553 }
1554
1555 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1556 if( '' === $text ) {
1557 $text = $target;
1558 } # this might be changed for ugliness reasons
1559 } else {
1560 # check for .. subpage backlinks
1561 $dotdotcount = 0;
1562 $nodotdot = $target;
1563 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1564 ++$dotdotcount;
1565 $nodotdot = substr( $nodotdot, 3 );
1566 }
1567 if($dotdotcount > 0) {
1568 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1569 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1570 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1571 # / at the end means don't show full path
1572 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1573 $nodotdot = substr( $nodotdot, 0, -1 );
1574 if( '' === $text ) {
1575 $text = $nodotdot;
1576 }
1577 }
1578 $nodotdot = trim( $nodotdot );
1579 if( $nodotdot != '' ) {
1580 $ret .= '/' . $nodotdot;
1581 }
1582 }
1583 }
1584 }
1585 }
1586
1587 wfProfileOut( $fname );
1588 return $ret;
1589 }
1590
1591 /**#@+
1592 * Used by doBlockLevels()
1593 * @access private
1594 */
1595 /* private */ function closeParagraph() {
1596 $result = '';
1597 if ( '' != $this->mLastSection ) {
1598 $result = '</' . $this->mLastSection . ">\n";
1599 }
1600 $this->mInPre = false;
1601 $this->mLastSection = '';
1602 return $result;
1603 }
1604 # getCommon() returns the length of the longest common substring
1605 # of both arguments, starting at the beginning of both.
1606 #
1607 /* private */ function getCommon( $st1, $st2 ) {
1608 $fl = strlen( $st1 );
1609 $shorter = strlen( $st2 );
1610 if ( $fl < $shorter ) { $shorter = $fl; }
1611
1612 for ( $i = 0; $i < $shorter; ++$i ) {
1613 if ( $st1{$i} != $st2{$i} ) { break; }
1614 }
1615 return $i;
1616 }
1617 # These next three functions open, continue, and close the list
1618 # element appropriate to the prefix character passed into them.
1619 #
1620 /* private */ function openList( $char ) {
1621 $result = $this->closeParagraph();
1622
1623 if ( '*' == $char ) { $result .= '<ul><li>'; }
1624 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1625 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1626 else if ( ';' == $char ) {
1627 $result .= '<dl><dt>';
1628 $this->mDTopen = true;
1629 }
1630 else { $result = '<!-- ERR 1 -->'; }
1631
1632 return $result;
1633 }
1634
1635 /* private */ function nextItem( $char ) {
1636 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1637 else if ( ':' == $char || ';' == $char ) {
1638 $close = '</dd>';
1639 if ( $this->mDTopen ) { $close = '</dt>'; }
1640 if ( ';' == $char ) {
1641 $this->mDTopen = true;
1642 return $close . '<dt>';
1643 } else {
1644 $this->mDTopen = false;
1645 return $close . '<dd>';
1646 }
1647 }
1648 return '<!-- ERR 2 -->';
1649 }
1650
1651 /* private */ function closeList( $char ) {
1652 if ( '*' == $char ) { $text = '</li></ul>'; }
1653 else if ( '#' == $char ) { $text = '</li></ol>'; }
1654 else if ( ':' == $char ) {
1655 if ( $this->mDTopen ) {
1656 $this->mDTopen = false;
1657 $text = '</dt></dl>';
1658 } else {
1659 $text = '</dd></dl>';
1660 }
1661 }
1662 else { return '<!-- ERR 3 -->'; }
1663 return $text."\n";
1664 }
1665 /**#@-*/
1666
1667 /**
1668 * Make lists from lines starting with ':', '*', '#', etc.
1669 *
1670 * @access private
1671 * @return string the lists rendered as HTML
1672 */
1673 function doBlockLevels( $text, $linestart ) {
1674 $fname = 'Parser::doBlockLevels';
1675 wfProfileIn( $fname );
1676
1677 # Parsing through the text line by line. The main thing
1678 # happening here is handling of block-level elements p, pre,
1679 # and making lists from lines starting with * # : etc.
1680 #
1681 $textLines = explode( "\n", $text );
1682
1683 $lastPrefix = $output = '';
1684 $this->mDTopen = $inBlockElem = false;
1685 $prefixLength = 0;
1686 $paragraphStack = false;
1687
1688 if ( !$linestart ) {
1689 $output .= array_shift( $textLines );
1690 }
1691 foreach ( $textLines as $oLine ) {
1692 $lastPrefixLength = strlen( $lastPrefix );
1693 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1694 $preOpenMatch = preg_match('/<pre/i', $oLine );
1695 if ( !$this->mInPre ) {
1696 # Multiple prefixes may abut each other for nested lists.
1697 $prefixLength = strspn( $oLine, '*#:;' );
1698 $pref = substr( $oLine, 0, $prefixLength );
1699
1700 # eh?
1701 $pref2 = str_replace( ';', ':', $pref );
1702 $t = substr( $oLine, $prefixLength );
1703 $this->mInPre = !empty($preOpenMatch);
1704 } else {
1705 # Don't interpret any other prefixes in preformatted text
1706 $prefixLength = 0;
1707 $pref = $pref2 = '';
1708 $t = $oLine;
1709 }
1710
1711 # List generation
1712 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1713 # Same as the last item, so no need to deal with nesting or opening stuff
1714 $output .= $this->nextItem( substr( $pref, -1 ) );
1715 $paragraphStack = false;
1716
1717 if ( substr( $pref, -1 ) == ';') {
1718 # The one nasty exception: definition lists work like this:
1719 # ; title : definition text
1720 # So we check for : in the remainder text to split up the
1721 # title and definition, without b0rking links.
1722 $term = $t2 = '';
1723 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1724 $t = $t2;
1725 $output .= $term . $this->nextItem( ':' );
1726 }
1727 }
1728 } elseif( $prefixLength || $lastPrefixLength ) {
1729 # Either open or close a level...
1730 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1731 $paragraphStack = false;
1732
1733 while( $commonPrefixLength < $lastPrefixLength ) {
1734 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1735 --$lastPrefixLength;
1736 }
1737 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1738 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1739 }
1740 while ( $prefixLength > $commonPrefixLength ) {
1741 $char = substr( $pref, $commonPrefixLength, 1 );
1742 $output .= $this->openList( $char );
1743
1744 if ( ';' == $char ) {
1745 # FIXME: This is dupe of code above
1746 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1747 $t = $t2;
1748 $output .= $term . $this->nextItem( ':' );
1749 }
1750 }
1751 ++$commonPrefixLength;
1752 }
1753 $lastPrefix = $pref2;
1754 }
1755 if( 0 == $prefixLength ) {
1756 wfProfileIn( "$fname-paragraph" );
1757 # No prefix (not in list)--go to paragraph mode
1758 $uniq_prefix = UNIQ_PREFIX;
1759 // XXX: use a stack for nestable elements like span, table and div
1760 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1761 $closematch = preg_match(
1762 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1763 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1764 if ( $openmatch or $closematch ) {
1765 $paragraphStack = false;
1766 $output .= $this->closeParagraph();
1767 if ( $preOpenMatch and !$preCloseMatch ) {
1768 $this->mInPre = true;
1769 }
1770 if ( $closematch ) {
1771 $inBlockElem = false;
1772 } else {
1773 $inBlockElem = true;
1774 }
1775 } else if ( !$inBlockElem && !$this->mInPre ) {
1776 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1777 // pre
1778 if ($this->mLastSection != 'pre') {
1779 $paragraphStack = false;
1780 $output .= $this->closeParagraph().'<pre>';
1781 $this->mLastSection = 'pre';
1782 }
1783 $t = substr( $t, 1 );
1784 } else {
1785 // paragraph
1786 if ( '' == trim($t) ) {
1787 if ( $paragraphStack ) {
1788 $output .= $paragraphStack.'<br />';
1789 $paragraphStack = false;
1790 $this->mLastSection = 'p';
1791 } else {
1792 if ($this->mLastSection != 'p' ) {
1793 $output .= $this->closeParagraph();
1794 $this->mLastSection = '';
1795 $paragraphStack = '<p>';
1796 } else {
1797 $paragraphStack = '</p><p>';
1798 }
1799 }
1800 } else {
1801 if ( $paragraphStack ) {
1802 $output .= $paragraphStack;
1803 $paragraphStack = false;
1804 $this->mLastSection = 'p';
1805 } else if ($this->mLastSection != 'p') {
1806 $output .= $this->closeParagraph().'<p>';
1807 $this->mLastSection = 'p';
1808 }
1809 }
1810 }
1811 }
1812 wfProfileOut( "$fname-paragraph" );
1813 }
1814 // somewhere above we forget to get out of pre block (bug 785)
1815 if($preCloseMatch && $this->mInPre) {
1816 $this->mInPre = false;
1817 }
1818 if ($paragraphStack === false) {
1819 $output .= $t."\n";
1820 }
1821 }
1822 while ( $prefixLength ) {
1823 $output .= $this->closeList( $pref2{$prefixLength-1} );
1824 --$prefixLength;
1825 }
1826 if ( '' != $this->mLastSection ) {
1827 $output .= '</' . $this->mLastSection . '>';
1828 $this->mLastSection = '';
1829 }
1830
1831 wfProfileOut( $fname );
1832 return $output;
1833 }
1834
1835 /**
1836 * Split up a string on ':', ignoring any occurences inside
1837 * <a>..</a> or <span>...</span>
1838 * @param string $str the string to split
1839 * @param string &$before set to everything before the ':'
1840 * @param string &$after set to everything after the ':'
1841 * return string the position of the ':', or false if none found
1842 */
1843 function findColonNoLinks($str, &$before, &$after) {
1844 # I wonder if we should make this count all tags, not just <a>
1845 # and <span>. That would prevent us from matching a ':' that
1846 # comes in the middle of italics other such formatting....
1847 # -- Wil
1848 $fname = 'Parser::findColonNoLinks';
1849 wfProfileIn( $fname );
1850 $pos = 0;
1851 do {
1852 $colon = strpos($str, ':', $pos);
1853
1854 if ($colon !== false) {
1855 $before = substr($str, 0, $colon);
1856 $after = substr($str, $colon + 1);
1857
1858 # Skip any ':' within <a> or <span> pairs
1859 $a = substr_count($before, '<a');
1860 $s = substr_count($before, '<span');
1861 $ca = substr_count($before, '</a>');
1862 $cs = substr_count($before, '</span>');
1863
1864 if ($a <= $ca and $s <= $cs) {
1865 # Tags are balanced before ':'; ok
1866 break;
1867 }
1868 $pos = $colon + 1;
1869 }
1870 } while ($colon !== false);
1871 wfProfileOut( $fname );
1872 return $colon;
1873 }
1874
1875 /**
1876 * Return value of a magic variable (like PAGENAME)
1877 *
1878 * @access private
1879 */
1880 function getVariableValue( $index ) {
1881 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgArticle, $wgScriptPath;
1882
1883 /**
1884 * Some of these require message or data lookups and can be
1885 * expensive to check many times.
1886 */
1887 static $varCache = array();
1888 if( isset( $varCache[$index] ) ) return $varCache[$index];
1889
1890 switch ( $index ) {
1891 case MAG_CURRENTMONTH:
1892 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1893 case MAG_CURRENTMONTHNAME:
1894 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1895 case MAG_CURRENTMONTHNAMEGEN:
1896 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1897 case MAG_CURRENTMONTHABBREV:
1898 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1899 case MAG_CURRENTDAY:
1900 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1901 case MAG_PAGENAME:
1902 return $this->mTitle->getText();
1903 case MAG_PAGENAMEE:
1904 return $this->mTitle->getPartialURL();
1905 case MAG_REVISIONID:
1906 return $wgArticle->getRevIdFetched();
1907 case MAG_NAMESPACE:
1908 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1909 return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1910 case MAG_CURRENTDAYNAME:
1911 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1912 case MAG_CURRENTYEAR:
1913 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1914 case MAG_CURRENTTIME:
1915 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1916 case MAG_CURRENTWEEK:
1917 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1918 case MAG_CURRENTDOW:
1919 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1920 case MAG_NUMBEROFARTICLES:
1921 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1922 case MAG_NUMBEROFFILES:
1923 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1924 case MAG_SITENAME:
1925 return $wgSitename;
1926 case MAG_SERVER:
1927 return $wgServer;
1928 case MAG_SERVERNAME:
1929 return $wgServerName;
1930 case MAG_SCRIPTPATH:
1931 return $wgScriptPath;
1932 default:
1933 return NULL;
1934 }
1935 }
1936
1937 /**
1938 * initialise the magic variables (like CURRENTMONTHNAME)
1939 *
1940 * @access private
1941 */
1942 function initialiseVariables() {
1943 $fname = 'Parser::initialiseVariables';
1944 wfProfileIn( $fname );
1945 global $wgVariableIDs;
1946 $this->mVariables = array();
1947 foreach ( $wgVariableIDs as $id ) {
1948 $mw =& MagicWord::get( $id );
1949 $mw->addToArray( $this->mVariables, $id );
1950 }
1951 wfProfileOut( $fname );
1952 }
1953
1954 /**
1955 * Replace magic variables, templates, and template arguments
1956 * with the appropriate text. Templates are substituted recursively,
1957 * taking care to avoid infinite loops.
1958 *
1959 * Note that the substitution depends on value of $mOutputType:
1960 * OT_WIKI: only {{subst:}} templates
1961 * OT_MSG: only magic variables
1962 * OT_HTML: all templates and magic variables
1963 *
1964 * @param string $tex The text to transform
1965 * @param array $args Key-value pairs representing template parameters to substitute
1966 * @access private
1967 */
1968 function replaceVariables( $text, $args = array() ) {
1969
1970 # Prevent too big inclusions
1971 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
1972 return $text;
1973 }
1974
1975 $fname = 'Parser::replaceVariables';
1976 wfProfileIn( $fname );
1977
1978 $titleChars = Title::legalChars();
1979
1980 # This function is called recursively. To keep track of arguments we need a stack:
1981 array_push( $this->mArgStack, $args );
1982
1983 # Variable substitution
1984 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1985
1986 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
1987 # Argument substitution
1988 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1989 }
1990 # Template substitution
1991 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1992 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1993
1994 array_pop( $this->mArgStack );
1995
1996 wfProfileOut( $fname );
1997 return $text;
1998 }
1999
2000 /**
2001 * Replace magic variables
2002 * @access private
2003 */
2004 function variableSubstitution( $matches ) {
2005 $fname = 'parser::variableSubstitution';
2006 $varname = $matches[1];
2007 wfProfileIn( $fname );
2008 if ( !$this->mVariables ) {
2009 $this->initialiseVariables();
2010 }
2011 $skip = false;
2012 if ( $this->mOutputType == OT_WIKI ) {
2013 # Do only magic variables prefixed by SUBST
2014 $mwSubst =& MagicWord::get( MAG_SUBST );
2015 if (!$mwSubst->matchStartAndRemove( $varname ))
2016 $skip = true;
2017 # Note that if we don't substitute the variable below,
2018 # we don't remove the {{subst:}} magic word, in case
2019 # it is a template rather than a magic variable.
2020 }
2021 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2022 $id = $this->mVariables[$varname];
2023 $text = $this->getVariableValue( $id );
2024 $this->mOutput->mContainsOldMagic = true;
2025 } else {
2026 $text = $matches[0];
2027 }
2028 wfProfileOut( $fname );
2029 return $text;
2030 }
2031
2032 # Split template arguments
2033 function getTemplateArgs( $argsString ) {
2034 if ( $argsString === '' ) {
2035 return array();
2036 }
2037
2038 $args = explode( '|', substr( $argsString, 1 ) );
2039
2040 # If any of the arguments contains a '[[' but no ']]', it needs to be
2041 # merged with the next arg because the '|' character between belongs
2042 # to the link syntax and not the template parameter syntax.
2043 $argc = count($args);
2044
2045 for ( $i = 0; $i < $argc-1; $i++ ) {
2046 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2047 $args[$i] .= '|'.$args[$i+1];
2048 array_splice($args, $i+1, 1);
2049 $i--;
2050 $argc--;
2051 }
2052 }
2053
2054 return $args;
2055 }
2056
2057 /**
2058 * Return the text of a template, after recursively
2059 * replacing any variables or templates within the template.
2060 *
2061 * @param array $matches The parts of the template
2062 * $matches[1]: the title, i.e. the part before the |
2063 * $matches[2]: the parameters (including a leading |), if any
2064 * @return string the text of the template
2065 * @access private
2066 */
2067 function braceSubstitution( $matches ) {
2068 global $wgLinkCache, $wgContLang;
2069 $fname = 'Parser::braceSubstitution';
2070 wfProfileIn( $fname );
2071
2072 $found = false;
2073 $nowiki = false;
2074 $noparse = false;
2075
2076 $title = NULL;
2077
2078 # Need to know if the template comes at the start of a line,
2079 # to treat the beginning of the template like the beginning
2080 # of a line for tables and block-level elements.
2081 $linestart = $matches[1];
2082
2083 # $part1 is the bit before the first |, and must contain only title characters
2084 # $args is a list of arguments, starting from index 0, not including $part1
2085
2086 $part1 = $matches[2];
2087 # If the third subpattern matched anything, it will start with |
2088
2089 $args = $this->getTemplateArgs($matches[3]);
2090 $argc = count( $args );
2091
2092 # Don't parse {{{}}} because that's only for template arguments
2093 if ( $linestart === '{' ) {
2094 $text = $matches[0];
2095 $found = true;
2096 $noparse = true;
2097 }
2098
2099 # SUBST
2100 if ( !$found ) {
2101 $mwSubst =& MagicWord::get( MAG_SUBST );
2102 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2103 # One of two possibilities is true:
2104 # 1) Found SUBST but not in the PST phase
2105 # 2) Didn't find SUBST and in the PST phase
2106 # In either case, return without further processing
2107 $text = $matches[0];
2108 $found = true;
2109 $noparse = true;
2110 }
2111 }
2112
2113 # MSG, MSGNW and INT
2114 if ( !$found ) {
2115 # Check for MSGNW:
2116 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2117 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2118 $nowiki = true;
2119 } else {
2120 # Remove obsolete MSG:
2121 $mwMsg =& MagicWord::get( MAG_MSG );
2122 $mwMsg->matchStartAndRemove( $part1 );
2123 }
2124
2125 # Check if it is an internal message
2126 $mwInt =& MagicWord::get( MAG_INT );
2127 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2128 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2129 $text = $linestart . wfMsgReal( $part1, $args, true );
2130 $found = true;
2131 }
2132 }
2133 }
2134
2135 # NS
2136 if ( !$found ) {
2137 # Check for NS: (namespace expansion)
2138 $mwNs = MagicWord::get( MAG_NS );
2139 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2140 if ( intval( $part1 ) ) {
2141 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2142 $found = true;
2143 } else {
2144 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2145 if ( !is_null( $index ) ) {
2146 $text = $linestart . $wgContLang->getNsText( $index );
2147 $found = true;
2148 }
2149 }
2150 }
2151 }
2152
2153 # LOCALURL and LOCALURLE
2154 if ( !$found ) {
2155 $mwLocal = MagicWord::get( MAG_LOCALURL );
2156 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
2157
2158 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2159 $func = 'getLocalURL';
2160 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2161 $func = 'escapeLocalURL';
2162 } else {
2163 $func = '';
2164 }
2165
2166 if ( $func !== '' ) {
2167 $title = Title::newFromText( $part1 );
2168 if ( !is_null( $title ) ) {
2169 if ( $argc > 0 ) {
2170 $text = $linestart . $title->$func( $args[0] );
2171 } else {
2172 $text = $linestart . $title->$func();
2173 }
2174 $found = true;
2175 }
2176 }
2177 }
2178
2179 # GRAMMAR
2180 if ( !$found && $argc == 1 ) {
2181 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2182 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2183 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2184 $found = true;
2185 }
2186 }
2187
2188 # Template table test
2189
2190 # Did we encounter this template already? If yes, it is in the cache
2191 # and we need to check for loops.
2192 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
2193 $found = true;
2194
2195 # Infinite loop test
2196 if ( isset( $this->mTemplatePath[$part1] ) ) {
2197 $noparse = true;
2198 $found = true;
2199 $text = $linestart .
2200 "\{\{$part1}}" .
2201 '<!-- WARNING: template loop detected -->';
2202 wfDebug( "$fname: template loop broken at '$part1'\n" );
2203 } else {
2204 # set $text to cached message.
2205 $text = $linestart . $this->mTemplates[$part1];
2206 }
2207 }
2208
2209 # Load from database
2210 $replaceHeadings = false;
2211 $isHTML = false;
2212 $lastPathLevel = $this->mTemplatePath;
2213 if ( !$found ) {
2214 $ns = NS_TEMPLATE;
2215 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2216 if ($subpage !== '') {
2217 $ns = $this->mTitle->getNamespace();
2218 }
2219 $title = Title::newFromText( $part1, $ns );
2220
2221 if ($title) {
2222 $interwiki = Title::getInterwikiLink($title->getInterwiki());
2223 if ($interwiki != '' && $title->isTrans()) {
2224 return $this->scarytransclude($title, $interwiki);
2225 }
2226 }
2227
2228 if ( !is_null( $title ) && !$title->isExternal() ) {
2229 # Check for excessive inclusion
2230 $dbk = $title->getPrefixedDBkey();
2231 if ( $this->incrementIncludeCount( $dbk ) ) {
2232 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2233 # Capture special page output
2234 $text = SpecialPage::capturePath( $title );
2235 if ( is_string( $text ) ) {
2236 $found = true;
2237 $noparse = true;
2238 $isHTML = true;
2239 $this->disableCache();
2240 }
2241 } else {
2242 $article = new Article( $title );
2243 $articleContent = $article->fetchContent();
2244 if ( $articleContent !== false ) {
2245 $found = true;
2246 $text = $articleContent;
2247 $replaceHeadings = true;
2248 }
2249 }
2250 }
2251
2252 # If the title is valid but undisplayable, make a link to it
2253 if ( $this->mOutputType == OT_HTML && !$found ) {
2254 $text = '[['.$title->getPrefixedText().']]';
2255 $found = true;
2256 }
2257
2258 # Template cache array insertion
2259 if( $found ) {
2260 $this->mTemplates[$part1] = $text;
2261 $text = $linestart . $text;
2262 }
2263 }
2264 }
2265
2266 # Recursive parsing, escaping and link table handling
2267 # Only for HTML output
2268 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2269 $text = wfEscapeWikiText( $text );
2270 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2271 # Clean up argument array
2272 $this->mAssocArgs = array();
2273 $index = 1;
2274 foreach( $args as $arg ) {
2275 $eqpos = strpos( $arg, '=' );
2276 if ( $eqpos === false ) {
2277 $this->mAssocArgs[$index++] = $arg;
2278 } else {
2279 $name = trim( substr( $arg, 0, $eqpos ) );
2280 $value = trim( substr( $arg, $eqpos+1 ) );
2281 if ( $value === false ) {
2282 $value = '';
2283 }
2284 if ( $name !== false ) {
2285 $this->mAssocArgs[$name] = $value;
2286 }
2287 }
2288 }
2289
2290 # Add a new element to the templace recursion path
2291 $this->mTemplatePath[$part1] = 1;
2292
2293 if( $this->mOutputType == OT_HTML ) {
2294 # Remove <noinclude> sections and <includeonly> tags
2295 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2296 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2297 # Strip <nowiki>, <pre>, etc.
2298 $text = $this->strip( $text, $this->mStripState );
2299 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $this->mAssocArgs );
2300 }
2301 $text = $this->replaceVariables( $text, $this->mAssocArgs );
2302
2303 # Resume the link cache and register the inclusion as a link
2304 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2305 $wgLinkCache->addLinkObj( $title );
2306 }
2307
2308 # If the template begins with a table or block-level
2309 # element, it should be treated as beginning a new line.
2310 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2311 $text = "\n" . $text;
2312 }
2313 }
2314 # Prune lower levels off the recursion check path
2315 $this->mTemplatePath = $lastPathLevel;
2316
2317 if ( !$found ) {
2318 wfProfileOut( $fname );
2319 return $matches[0];
2320 } else {
2321 if ( $isHTML ) {
2322 # Replace raw HTML by a placeholder
2323 # Add a blank line preceding, to prevent it from mucking up
2324 # immediately preceding headings
2325 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2326 } else {
2327 # replace ==section headers==
2328 # XXX this needs to go away once we have a better parser.
2329 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2330 if( !is_null( $title ) )
2331 $encodedname = base64_encode($title->getPrefixedDBkey());
2332 else
2333 $encodedname = base64_encode("");
2334 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2335 PREG_SPLIT_DELIM_CAPTURE);
2336 $text = '';
2337 $nsec = 0;
2338 for( $i = 0; $i < count($m); $i += 2 ) {
2339 $text .= $m[$i];
2340 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2341 $hl = $m[$i + 1];
2342 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2343 $text .= $hl;
2344 continue;
2345 }
2346 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2347 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2348 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2349
2350 $nsec++;
2351 }
2352 }
2353 }
2354 }
2355
2356 # Prune lower levels off the recursion check path
2357 $this->mTemplatePath = $lastPathLevel;
2358
2359 if ( !$found ) {
2360 wfProfileOut( $fname );
2361 return $matches[0];
2362 } else {
2363 wfProfileOut( $fname );
2364 return $text;
2365 }
2366 }
2367
2368 /**
2369 * Translude an interwiki link.
2370 */
2371 function scarytransclude($title, $interwiki) {
2372 global $wgEnableScaryTranscluding;
2373
2374 if (!$wgEnableScaryTranscluding)
2375 return wfMsg('scarytranscludedisabled');
2376
2377 $articlename = "Template:" . $title->getDBkey();
2378 $url = str_replace('$1', urlencode($articlename), $interwiki);
2379 if (strlen($url) > 255)
2380 return wfMsg('scarytranscludetoolong');
2381 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2382 $this->mIWTransData[] = $text;
2383 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData) - 1)."-->";
2384 }
2385
2386 function fetchScaryTemplateMaybeFromCache($url) {
2387 $dbr =& wfGetDB(DB_SLAVE);
2388 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2389 array('tc_url' => $url));
2390 if ($obj) {
2391 $time = $obj->tc_time;
2392 $text = $obj->tc_contents;
2393 if ($time && $time < (time() + (60*60))) {
2394 return $text;
2395 }
2396 }
2397
2398 $text = wfGetHTTP($url . '?action=render');
2399 if (!$text)
2400 return wfMsg('scarytranscludefailed', $url);
2401
2402 $dbw =& wfGetDB(DB_MASTER);
2403 $dbw->replace('transcache', array(), array(
2404 'tc_url' => $url,
2405 'tc_time' => time(),
2406 'tc_contents' => $text));
2407 return $text;
2408 }
2409
2410
2411 /**
2412 * Triple brace replacement -- used for template arguments
2413 * @access private
2414 */
2415 function argSubstitution( $matches ) {
2416 $arg = trim( $matches[1] );
2417 $text = $matches[0];
2418 $inputArgs = end( $this->mArgStack );
2419
2420 if ( array_key_exists( $arg, $inputArgs ) ) {
2421 $text = $inputArgs[$arg];
2422 }
2423
2424 return $text;
2425 }
2426
2427 /**
2428 * Returns true if the function is allowed to include this entity
2429 * @access private
2430 */
2431 function incrementIncludeCount( $dbk ) {
2432 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2433 $this->mIncludeCount[$dbk] = 0;
2434 }
2435 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2436 return true;
2437 } else {
2438 return false;
2439 }
2440 }
2441
2442 /**
2443 * This function accomplishes several tasks:
2444 * 1) Auto-number headings if that option is enabled
2445 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2446 * 3) Add a Table of contents on the top for users who have enabled the option
2447 * 4) Auto-anchor headings
2448 *
2449 * It loops through all headlines, collects the necessary data, then splits up the
2450 * string and re-inserts the newly formatted headlines.
2451 *
2452 * @param string $text
2453 * @param boolean $isMain
2454 * @access private
2455 */
2456 function formatHeadings( $text, $isMain=true ) {
2457 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2458
2459 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2460 $doShowToc = true;
2461 $forceTocHere = false;
2462 if( !$this->mTitle->userCanEdit() ) {
2463 $showEditLink = 0;
2464 } else {
2465 $showEditLink = $this->mOptions->getEditSection();
2466 }
2467
2468 # Inhibit editsection links if requested in the page
2469 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2470 if( $esw->matchAndRemove( $text ) ) {
2471 $showEditLink = 0;
2472 }
2473 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2474 # do not add TOC
2475 $mw =& MagicWord::get( MAG_NOTOC );
2476 if( $mw->matchAndRemove( $text ) ) {
2477 $doShowToc = false;
2478 }
2479
2480 # Get all headlines for numbering them and adding funky stuff like [edit]
2481 # links - this is for later, but we need the number of headlines right now
2482 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2483
2484 # if there are fewer than 4 headlines in the article, do not show TOC
2485 if( $numMatches < 4 ) {
2486 $doShowToc = false;
2487 }
2488
2489 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2490 # override above conditions and always show TOC at that place
2491
2492 $mw =& MagicWord::get( MAG_TOC );
2493 if($mw->match( $text ) ) {
2494 $doShowToc = true;
2495 $forceTocHere = true;
2496 } else {
2497 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2498 # override above conditions and always show TOC above first header
2499 $mw =& MagicWord::get( MAG_FORCETOC );
2500 if ($mw->matchAndRemove( $text ) ) {
2501 $doShowToc = true;
2502 }
2503 }
2504
2505 # Never ever show TOC if no headers
2506 if( $numMatches < 1 ) {
2507 $doShowToc = false;
2508 }
2509
2510 # We need this to perform operations on the HTML
2511 $sk =& $this->mOptions->getSkin();
2512
2513 # headline counter
2514 $headlineCount = 0;
2515 $sectionCount = 0; # headlineCount excluding template sections
2516
2517 # Ugh .. the TOC should have neat indentation levels which can be
2518 # passed to the skin functions. These are determined here
2519 $toc = '';
2520 $full = '';
2521 $head = array();
2522 $sublevelCount = array();
2523 $levelCount = array();
2524 $toclevel = 0;
2525 $level = 0;
2526 $prevlevel = 0;
2527 $toclevel = 0;
2528 $prevtoclevel = 0;
2529
2530 foreach( $matches[3] as $headline ) {
2531 $istemplate = 0;
2532 $templatetitle = '';
2533 $templatesection = 0;
2534 $numbering = '';
2535
2536 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2537 $istemplate = 1;
2538 $templatetitle = base64_decode($mat[1]);
2539 $templatesection = 1 + (int)base64_decode($mat[2]);
2540 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2541 }
2542
2543 if( $toclevel ) {
2544 $prevlevel = $level;
2545 $prevtoclevel = $toclevel;
2546 }
2547 $level = $matches[1][$headlineCount];
2548
2549 if( $doNumberHeadings || $doShowToc ) {
2550
2551 if ( $level > $prevlevel ) {
2552 # Increase TOC level
2553 $toclevel++;
2554 $sublevelCount[$toclevel] = 0;
2555 $toc .= $sk->tocIndent();
2556 }
2557 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2558 # Decrease TOC level, find level to jump to
2559
2560 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2561 # Can only go down to level 1
2562 $toclevel = 1;
2563 } else {
2564 for ($i = $toclevel; $i > 0; $i--) {
2565 if ( $levelCount[$i] == $level ) {
2566 # Found last matching level
2567 $toclevel = $i;
2568 break;
2569 }
2570 elseif ( $levelCount[$i] < $level ) {
2571 # Found first matching level below current level
2572 $toclevel = $i + 1;
2573 break;
2574 }
2575 }
2576 }
2577
2578 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2579 }
2580 else {
2581 # No change in level, end TOC line
2582 $toc .= $sk->tocLineEnd();
2583 }
2584
2585 $levelCount[$toclevel] = $level;
2586
2587 # count number of headlines for each level
2588 @$sublevelCount[$toclevel]++;
2589 $dot = 0;
2590 for( $i = 1; $i <= $toclevel; $i++ ) {
2591 if( !empty( $sublevelCount[$i] ) ) {
2592 if( $dot ) {
2593 $numbering .= '.';
2594 }
2595 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2596 $dot = 1;
2597 }
2598 }
2599 }
2600
2601 # The canonized header is a version of the header text safe to use for links
2602 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2603 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2604 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2605
2606 # Remove link placeholders by the link text.
2607 # <!--LINK number-->
2608 # turns into
2609 # link text with suffix
2610 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2611 "\$this->mLinkHolders['texts'][\$1]",
2612 $canonized_headline );
2613 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2614 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2615 $canonized_headline );
2616
2617 # strip out HTML
2618 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2619 $tocline = trim( $canonized_headline );
2620 $canonized_headline = urlencode( Sanitizer::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2621 $replacearray = array(
2622 '%3A' => ':',
2623 '%' => '.'
2624 );
2625 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2626 $refers[$headlineCount] = $canonized_headline;
2627
2628 # count how many in assoc. array so we can track dupes in anchors
2629 @$refers[$canonized_headline]++;
2630 $refcount[$headlineCount]=$refers[$canonized_headline];
2631
2632 # Don't number the heading if it is the only one (looks silly)
2633 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2634 # the two are different if the line contains a link
2635 $headline=$numbering . ' ' . $headline;
2636 }
2637
2638 # Create the anchor for linking from the TOC to the section
2639 $anchor = $canonized_headline;
2640 if($refcount[$headlineCount] > 1 ) {
2641 $anchor .= '_' . $refcount[$headlineCount];
2642 }
2643 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2644 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2645 }
2646 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2647 if ( empty( $head[$headlineCount] ) ) {
2648 $head[$headlineCount] = '';
2649 }
2650 if( $istemplate )
2651 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2652 else
2653 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2654 }
2655
2656 # give headline the correct <h#> tag
2657 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2658
2659 $headlineCount++;
2660 if( !$istemplate )
2661 $sectionCount++;
2662 }
2663
2664 if( $doShowToc ) {
2665 $toc .= $sk->tocUnindent( $toclevel - 1 );
2666 $toc = $sk->tocList( $toc );
2667 }
2668
2669 # split up and insert constructed headlines
2670
2671 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2672 $i = 0;
2673
2674 foreach( $blocks as $block ) {
2675 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2676 # This is the [edit] link that appears for the top block of text when
2677 # section editing is enabled
2678
2679 # Disabled because it broke block formatting
2680 # For example, a bullet point in the top line
2681 # $full .= $sk->editSectionLink(0);
2682 }
2683 $full .= $block;
2684 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2685 # Top anchor now in skin
2686 $full = $full.$toc;
2687 }
2688
2689 if( !empty( $head[$i] ) ) {
2690 $full .= $head[$i];
2691 }
2692 $i++;
2693 }
2694 if($forceTocHere) {
2695 $mw =& MagicWord::get( MAG_TOC );
2696 return $mw->replace( $toc, $full );
2697 } else {
2698 return $full;
2699 }
2700 }
2701
2702 /**
2703 * Return an HTML link for the "ISBN 123456" text
2704 * @access private
2705 */
2706 function magicISBN( $text ) {
2707 $fname = 'Parser::magicISBN';
2708 wfProfileIn( $fname );
2709
2710 $a = split( 'ISBN ', ' '.$text );
2711 if ( count ( $a ) < 2 ) {
2712 wfProfileOut( $fname );
2713 return $text;
2714 }
2715 $text = substr( array_shift( $a ), 1);
2716 $valid = '0123456789-Xx';
2717
2718 foreach ( $a as $x ) {
2719 $isbn = $blank = '' ;
2720 while ( ' ' == $x{0} ) {
2721 $blank .= ' ';
2722 $x = substr( $x, 1 );
2723 }
2724 if ( $x == '' ) { # blank isbn
2725 $text .= "ISBN $blank";
2726 continue;
2727 }
2728 while ( strstr( $valid, $x{0} ) != false ) {
2729 $isbn .= $x{0};
2730 $x = substr( $x, 1 );
2731 }
2732 $num = str_replace( '-', '', $isbn );
2733 $num = str_replace( ' ', '', $num );
2734 $num = str_replace( 'x', 'X', $num );
2735
2736 if ( '' == $num ) {
2737 $text .= "ISBN $blank$x";
2738 } else {
2739 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2740 $text .= '<a href="' .
2741 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2742 "\" class=\"internal\">ISBN $isbn</a>";
2743 $text .= $x;
2744 }
2745 }
2746 wfProfileOut( $fname );
2747 return $text;
2748 }
2749
2750 /**
2751 * Return an HTML link for the "RFC 1234" text
2752 *
2753 * @access private
2754 * @param string $text Text to be processed
2755 * @param string $keyword Magic keyword to use (default RFC)
2756 * @param string $urlmsg Interface message to use (default rfcurl)
2757 * @return string
2758 */
2759 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2760
2761 $valid = '0123456789';
2762 $internal = false;
2763
2764 $a = split( $keyword, ' '.$text );
2765 if ( count ( $a ) < 2 ) {
2766 return $text;
2767 }
2768 $text = substr( array_shift( $a ), 1);
2769
2770 /* Check if keyword is preceed by [[.
2771 * This test is made here cause of the array_shift above
2772 * that prevent the test to be done in the foreach.
2773 */
2774 if ( substr( $text, -2 ) == '[[' ) {
2775 $internal = true;
2776 }
2777
2778 foreach ( $a as $x ) {
2779 /* token might be empty if we have RFC RFC 1234 */
2780 if ( $x=='' ) {
2781 $text.=$keyword;
2782 continue;
2783 }
2784
2785 $id = $blank = '' ;
2786
2787 /** remove and save whitespaces in $blank */
2788 while ( $x{0} == ' ' ) {
2789 $blank .= ' ';
2790 $x = substr( $x, 1 );
2791 }
2792
2793 /** remove and save the rfc number in $id */
2794 while ( strstr( $valid, $x{0} ) != false ) {
2795 $id .= $x{0};
2796 $x = substr( $x, 1 );
2797 }
2798
2799 if ( $id == '' ) {
2800 /* call back stripped spaces*/
2801 $text .= $keyword.$blank.$x;
2802 } elseif( $internal ) {
2803 /* normal link */
2804 $text .= $keyword.$id.$x;
2805 } else {
2806 /* build the external link*/
2807 $url = wfMsg( $urlmsg, $id);
2808 $sk =& $this->mOptions->getSkin();
2809 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2810 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2811 }
2812
2813 /* Check if the next RFC keyword is preceed by [[ */
2814 $internal = ( substr($x,-2) == '[[' );
2815 }
2816 return $text;
2817 }
2818
2819 /**
2820 * Transform wiki markup when saving a page by doing \r\n -> \n
2821 * conversion, substitting signatures, {{subst:}} templates, etc.
2822 *
2823 * @param string $text the text to transform
2824 * @param Title &$title the Title object for the current article
2825 * @param User &$user the User object describing the current user
2826 * @param ParserOptions $options parsing options
2827 * @param bool $clearState whether to clear the parser state first
2828 * @return string the altered wiki markup
2829 * @access public
2830 */
2831 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2832 $this->mOptions = $options;
2833 $this->mTitle =& $title;
2834 $this->mOutputType = OT_WIKI;
2835
2836 if ( $clearState ) {
2837 $this->clearState();
2838 }
2839
2840 $stripState = false;
2841 $pairs = array(
2842 "\r\n" => "\n",
2843 );
2844 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2845 $text = $this->strip( $text, $stripState, false );
2846 $text = $this->pstPass2( $text, $user );
2847 $text = $this->unstrip( $text, $stripState );
2848 $text = $this->unstripNoWiki( $text, $stripState );
2849 return $text;
2850 }
2851
2852 /**
2853 * Pre-save transform helper function
2854 * @access private
2855 */
2856 function pstPass2( $text, &$user ) {
2857 global $wgContLang, $wgLocaltimezone;
2858
2859 # Variable replacement
2860 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2861 $text = $this->replaceVariables( $text );
2862
2863 # Signatures
2864 #
2865 $n = $user->getName();
2866 $k = $user->getOption( 'nickname' );
2867 if ( '' == $k ) { $k = $n; }
2868 if ( isset( $wgLocaltimezone ) ) {
2869 $oldtz = getenv( 'TZ' );
2870 putenv( 'TZ='.$wgLocaltimezone );
2871 }
2872
2873 /* Note: This is the timestamp saved as hardcoded wikitext to
2874 * the database, we use $wgContLang here in order to give
2875 * everyone the same signiture and use the default one rather
2876 * than the one selected in each users preferences.
2877 */
2878 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
2879 ' (' . date( 'T' ) . ')';
2880 if ( isset( $wgLocaltimezone ) ) {
2881 putenv( 'TZ='.$oldtz );
2882 }
2883
2884 if( $user->getOption( 'fancysig' ) ) {
2885 $sigText = $k;
2886 } else {
2887 $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
2888 }
2889 $text = preg_replace( '/~~~~~/', $d, $text );
2890 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2891 $text = preg_replace( '/~~~/', $sigText, $text );
2892
2893 # Context links: [[|name]] and [[name (context)|]]
2894 #
2895 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2896 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2897 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2898 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2899
2900 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2901 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2902 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2903 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2904 $context = '';
2905 $t = $this->mTitle->getText();
2906 if ( preg_match( $conpat, $t, $m ) ) {
2907 $context = $m[2];
2908 }
2909 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2910 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2911 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2912
2913 if ( '' == $context ) {
2914 $text = preg_replace( $p2, '[[\\1]]', $text );
2915 } else {
2916 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2917 }
2918
2919 # Trim trailing whitespace
2920 # MAG_END (__END__) tag allows for trailing
2921 # whitespace to be deliberately included
2922 $text = rtrim( $text );
2923 $mw =& MagicWord::get( MAG_END );
2924 $mw->matchAndRemove( $text );
2925
2926 return $text;
2927 }
2928
2929 /**
2930 * Set up some variables which are usually set up in parse()
2931 * so that an external function can call some class members with confidence
2932 * @access public
2933 */
2934 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2935 $this->mTitle =& $title;
2936 $this->mOptions = $options;
2937 $this->mOutputType = $outputType;
2938 if ( $clearState ) {
2939 $this->clearState();
2940 }
2941 }
2942
2943 /**
2944 * Transform a MediaWiki message by replacing magic variables.
2945 *
2946 * @param string $text the text to transform
2947 * @param ParserOptions $options options
2948 * @return string the text with variables substituted
2949 * @access public
2950 */
2951 function transformMsg( $text, $options ) {
2952 global $wgTitle;
2953 static $executing = false;
2954
2955 # Guard against infinite recursion
2956 if ( $executing ) {
2957 return $text;
2958 }
2959 $executing = true;
2960
2961 $this->mTitle = $wgTitle;
2962 $this->mOptions = $options;
2963 $this->mOutputType = OT_MSG;
2964 $this->clearState();
2965 $text = $this->replaceVariables( $text );
2966
2967 $executing = false;
2968 return $text;
2969 }
2970
2971 /**
2972 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2973 * Callback will be called with the text within
2974 * Transform and return the text within
2975 * @access public
2976 */
2977 function setHook( $tag, $callback ) {
2978 $oldVal = @$this->mTagHooks[$tag];
2979 $this->mTagHooks[$tag] = $callback;
2980 return $oldVal;
2981 }
2982
2983 /**
2984 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2985 * Placeholders created in Skin::makeLinkObj()
2986 * Returns an array of links found, indexed by PDBK:
2987 * 0 - broken
2988 * 1 - normal link
2989 * 2 - stub
2990 * $options is a bit field, RLH_FOR_UPDATE to select for update
2991 */
2992 function replaceLinkHolders( &$text, $options = 0 ) {
2993 global $wgUser, $wgLinkCache;
2994 global $wgOutputReplace;
2995
2996 $fname = 'Parser::replaceLinkHolders';
2997 wfProfileIn( $fname );
2998
2999 $pdbks = array();
3000 $colours = array();
3001 $sk = $this->mOptions->getSkin();
3002
3003 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3004 wfProfileIn( $fname.'-check' );
3005 $dbr =& wfGetDB( DB_SLAVE );
3006 $page = $dbr->tableName( 'page' );
3007 $threshold = $wgUser->getOption('stubthreshold');
3008
3009 # Sort by namespace
3010 asort( $this->mLinkHolders['namespaces'] );
3011
3012 # Generate query
3013 $query = false;
3014 foreach ( $this->mLinkHolders['namespaces'] as $key => $val ) {
3015 # Make title object
3016 $title = $this->mLinkHolders['titles'][$key];
3017
3018 # Skip invalid entries.
3019 # Result will be ugly, but prevents crash.
3020 if ( is_null( $title ) ) {
3021 continue;
3022 }
3023 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3024
3025 # Check if it's in the link cache already
3026 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
3027 $colours[$pdbk] = 1;
3028 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3029 $colours[$pdbk] = 0;
3030 } else {
3031 # Not in the link cache, add it to the query
3032 if ( !isset( $current ) ) {
3033 $current = $val;
3034 $query = "SELECT page_id, page_namespace, page_title";
3035 if ( $threshold > 0 ) {
3036 $query .= ', page_len, page_is_redirect';
3037 }
3038 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3039 } elseif ( $current != $val ) {
3040 $current = $val;
3041 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3042 } else {
3043 $query .= ', ';
3044 }
3045
3046 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3047 }
3048 }
3049 if ( $query ) {
3050 $query .= '))';
3051 if ( $options & RLH_FOR_UPDATE ) {
3052 $query .= ' FOR UPDATE';
3053 }
3054
3055 $res = $dbr->query( $query, $fname );
3056
3057 # Fetch data and form into an associative array
3058 # non-existent = broken
3059 # 1 = known
3060 # 2 = stub
3061 while ( $s = $dbr->fetchObject($res) ) {
3062 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3063 $pdbk = $title->getPrefixedDBkey();
3064 $wgLinkCache->addGoodLinkObj( $s->page_id, $title );
3065
3066 if ( $threshold > 0 ) {
3067 $size = $s->page_len;
3068 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3069 $colours[$pdbk] = 1;
3070 } else {
3071 $colours[$pdbk] = 2;
3072 }
3073 } else {
3074 $colours[$pdbk] = 1;
3075 }
3076 }
3077 }
3078 wfProfileOut( $fname.'-check' );
3079
3080 # Construct search and replace arrays
3081 wfProfileIn( $fname.'-construct' );
3082 $wgOutputReplace = array();
3083 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3084 $pdbk = $pdbks[$key];
3085 $searchkey = "<!--LINK $key-->";
3086 $title = $this->mLinkHolders['titles'][$key];
3087 if ( empty( $colours[$pdbk] ) ) {
3088 $wgLinkCache->addBadLinkObj( $title );
3089 $colours[$pdbk] = 0;
3090 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3091 $this->mLinkHolders['texts'][$key],
3092 $this->mLinkHolders['queries'][$key] );
3093 } elseif ( $colours[$pdbk] == 1 ) {
3094 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3095 $this->mLinkHolders['texts'][$key],
3096 $this->mLinkHolders['queries'][$key] );
3097 } elseif ( $colours[$pdbk] == 2 ) {
3098 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3099 $this->mLinkHolders['texts'][$key],
3100 $this->mLinkHolders['queries'][$key] );
3101 }
3102 }
3103 wfProfileOut( $fname.'-construct' );
3104
3105 # Do the thing
3106 wfProfileIn( $fname.'-replace' );
3107
3108 $text = preg_replace_callback(
3109 '/(<!--LINK .*?-->)/',
3110 "wfOutputReplaceMatches",
3111 $text);
3112
3113 wfProfileOut( $fname.'-replace' );
3114 }
3115
3116 # Now process interwiki link holders
3117 # This is quite a bit simpler than internal links
3118 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3119 wfProfileIn( $fname.'-interwiki' );
3120 # Make interwiki link HTML
3121 $wgOutputReplace = array();
3122 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3123 $title = $this->mInterwikiLinkHolders['titles'][$key];
3124 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3125 }
3126
3127 $text = preg_replace_callback(
3128 '/<!--IWLINK (.*?)-->/',
3129 "wfOutputReplaceMatches",
3130 $text );
3131 wfProfileOut( $fname.'-interwiki' );
3132 }
3133
3134 wfProfileOut( $fname );
3135 return $colours;
3136 }
3137
3138 /**
3139 * Replace <!--LINK--> link placeholders with plain text of links
3140 * (not HTML-formatted).
3141 * @param string $text
3142 * @return string
3143 */
3144 function replaceLinkHoldersText( $text ) {
3145 global $wgUser, $wgLinkCache;
3146 global $wgOutputReplace;
3147
3148 $fname = 'Parser::replaceLinkHoldersText';
3149 wfProfileIn( $fname );
3150
3151 $text = preg_replace_callback(
3152 '/<!--(LINK|IWLINK) (.*?)-->/',
3153 array( &$this, 'replaceLinkHoldersTextCallback' ),
3154 $text );
3155
3156 wfProfileOut( $fname );
3157 return $text;
3158 }
3159
3160 /**
3161 * @param array $matches
3162 * @return string
3163 * @access private
3164 */
3165 function replaceLinkHoldersTextCallback( $matches ) {
3166 $type = $matches[1];
3167 $key = $matches[2];
3168 if( $type == 'LINK' ) {
3169 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3170 return $this->mLinkHolders['texts'][$key];
3171 }
3172 } elseif( $type == 'IWLINK' ) {
3173 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3174 return $this->mInterwikiLinkHolders['texts'][$key];
3175 }
3176 }
3177 return $matches[0];
3178 }
3179
3180 /**
3181 * Renders an image gallery from a text with one line per image.
3182 * text labels may be given by using |-style alternative text. E.g.
3183 * Image:one.jpg|The number "1"
3184 * Image:tree.jpg|A tree
3185 * given as text will return the HTML of a gallery with two images,
3186 * labeled 'The number "1"' and
3187 * 'A tree'.
3188 *
3189 * @static
3190 */
3191 function renderImageGallery( $text ) {
3192 # Setup the parser
3193 global $wgUser, $wgTitle;
3194 $parserOptions = ParserOptions::newFromUser( $wgUser );
3195 $localParser = new Parser();
3196
3197 global $wgLinkCache;
3198 $ig = new ImageGallery();
3199 $ig->setShowBytes( false );
3200 $ig->setShowFilename( false );
3201 $lines = explode( "\n", $text );
3202
3203 foreach ( $lines as $line ) {
3204 # match lines like these:
3205 # Image:someimage.jpg|This is some image
3206 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3207 # Skip empty lines
3208 if ( count( $matches ) == 0 ) {
3209 continue;
3210 }
3211 $nt = Title::newFromURL( $matches[1] );
3212 if( is_null( $nt ) ) {
3213 # Bogus title. Ignore these so we don't bomb out later.
3214 continue;
3215 }
3216 if ( isset( $matches[3] ) ) {
3217 $label = $matches[3];
3218 } else {
3219 $label = '';
3220 }
3221
3222 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3223 $html = $html->mText;
3224
3225 $ig->add( new Image( $nt ), $html );
3226 $wgLinkCache->addImageLinkObj( $nt );
3227 }
3228 return $ig->toHTML();
3229 }
3230
3231 /**
3232 * Parse image options text and use it to make an image
3233 */
3234 function makeImage( &$nt, $options ) {
3235 global $wgContLang, $wgUseImageResize;
3236 global $wgUser, $wgThumbLimits;
3237
3238 $align = '';
3239
3240 # Check if the options text is of the form "options|alt text"
3241 # Options are:
3242 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3243 # * left no resizing, just left align. label is used for alt= only
3244 # * right same, but right aligned
3245 # * none same, but not aligned
3246 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3247 # * center center the image
3248 # * framed Keep original image size, no magnify-button.
3249
3250 $part = explode( '|', $options);
3251
3252 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3253 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3254 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3255 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3256 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3257 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3258 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3259 $caption = '';
3260
3261 $width = $height = $framed = $thumb = false;
3262 $manual_thumb = '' ;
3263
3264 foreach( $part as $key => $val ) {
3265 $val_parts = explode ( '=' , $val , 2 ) ;
3266 $left_part = array_shift ( $val_parts ) ;
3267 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3268 $thumb=true;
3269 } elseif ( $wgUseImageResize && count ( $val_parts ) == 1 && ! is_null( $mwThumb->matchVariableStartToEnd($left_part) ) ) {
3270 # use manually specified thumbnail
3271 $thumb=true;
3272 $manual_thumb = array_shift ( $val_parts ) ;
3273 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3274 # remember to set an alignment, don't render immediately
3275 $align = 'right';
3276 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3277 # remember to set an alignment, don't render immediately
3278 $align = 'left';
3279 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3280 # remember to set an alignment, don't render immediately
3281 $align = 'center';
3282 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3283 # remember to set an alignment, don't render immediately
3284 $align = 'none';
3285 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3286 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3287 # $match is the image width in pixels
3288 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3289 $width = intval( $m[1] );
3290 $height = intval( $m[2] );
3291 } else {
3292 $width = intval($match);
3293 }
3294 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3295 $framed=true;
3296 } else {
3297 $caption = $val;
3298 }
3299 }
3300 # Strip bad stuff out of the alt text
3301 $alt = $this->replaceLinkHoldersText( $caption );
3302 $alt = Sanitizer::stripAllTags( $alt );
3303
3304 # Linker does the rest
3305 $sk =& $this->mOptions->getSkin();
3306 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3307 }
3308
3309 /**
3310 * Set a flag in the output object indicating that the content is dynamic and
3311 * shouldn't be cached.
3312 */
3313 function disableCache() {
3314 $this->mOutput->mCacheTime = -1;
3315 }
3316 }
3317
3318 /**
3319 * @todo document
3320 * @package MediaWiki
3321 */
3322 class ParserOutput
3323 {
3324 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3325 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3326 var $mVersion; # Compatibility check
3327 var $mTitleText; # title text of the chosen language variant
3328
3329 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3330 $containsOldMagic = false, $titletext = '' )
3331 {
3332 $this->mText = $text;
3333 $this->mLanguageLinks = $languageLinks;
3334 $this->mCategoryLinks = $categoryLinks;
3335 $this->mContainsOldMagic = $containsOldMagic;
3336 $this->mCacheTime = '';
3337 $this->mVersion = MW_PARSER_VERSION;
3338 $this->mTitleText = $titletext;
3339 }
3340
3341 function getText() { return $this->mText; }
3342 function getLanguageLinks() { return $this->mLanguageLinks; }
3343 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
3344 function getCacheTime() { return $this->mCacheTime; }
3345 function getTitleText() { return $this->mTitleText; }
3346 function containsOldMagic() { return $this->mContainsOldMagic; }
3347 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3348 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3349 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
3350 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3351 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3352 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3353
3354 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
3355
3356 function merge( $other ) {
3357 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3358 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3359 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3360 }
3361
3362 /**
3363 * Return true if this cached output object predates the global or
3364 * per-article cache invalidation timestamps, or if it comes from
3365 * an incompatible older version.
3366 *
3367 * @param string $touched the affected article's last touched timestamp
3368 * @return bool
3369 * @access public
3370 */
3371 function expired( $touched ) {
3372 global $wgCacheEpoch;
3373 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3374 $this->getCacheTime() <= $touched ||
3375 $this->getCacheTime() <= $wgCacheEpoch ||
3376 !isset( $this->mVersion ) ||
3377 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3378 }
3379 }
3380
3381 /**
3382 * Set options of the Parser
3383 * @todo document
3384 * @package MediaWiki
3385 */
3386 class ParserOptions
3387 {
3388 # All variables are private
3389 var $mUseTeX; # Use texvc to expand <math> tags
3390 var $mUseDynamicDates; # Use DateFormatter to format dates
3391 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3392 var $mAllowExternalImages; # Allow external images inline
3393 var $mSkin; # Reference to the preferred skin
3394 var $mDateFormat; # Date format index
3395 var $mEditSection; # Create "edit section" links
3396 var $mNumberHeadings; # Automatically number headings
3397 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3398
3399 function getUseTeX() { return $this->mUseTeX; }
3400 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3401 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3402 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3403 function &getSkin() { return $this->mSkin; }
3404 function getDateFormat() { return $this->mDateFormat; }
3405 function getEditSection() { return $this->mEditSection; }
3406 function getNumberHeadings() { return $this->mNumberHeadings; }
3407 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3408
3409
3410 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3411 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3412 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3413 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3414 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3415 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3416 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3417 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3418
3419 function setSkin( &$x ) { $this->mSkin =& $x; }
3420
3421 function ParserOptions() {
3422 global $wgUser;
3423 $this->initialiseFromUser( $wgUser );
3424 }
3425
3426 /**
3427 * Get parser options
3428 * @static
3429 */
3430 function newFromUser( &$user ) {
3431 $popts = new ParserOptions;
3432 $popts->initialiseFromUser( $user );
3433 return $popts;
3434 }
3435
3436 /** Get user options */
3437 function initialiseFromUser( &$userInput ) {
3438 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3439 $wgAllowSpecialInclusion;
3440 $fname = 'ParserOptions::initialiseFromUser';
3441 wfProfileIn( $fname );
3442 if ( !$userInput ) {
3443 $user = new User;
3444 $user->setLoaded( true );
3445 } else {
3446 $user =& $userInput;
3447 }
3448
3449 $this->mUseTeX = $wgUseTeX;
3450 $this->mUseDynamicDates = $wgUseDynamicDates;
3451 $this->mInterwikiMagic = $wgInterwikiMagic;
3452 $this->mAllowExternalImages = $wgAllowExternalImages;
3453 wfProfileIn( $fname.'-skin' );
3454 $this->mSkin =& $user->getSkin();
3455 wfProfileOut( $fname.'-skin' );
3456 $this->mDateFormat = $user->getOption( 'date' );
3457 $this->mEditSection = true;
3458 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3459 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
3460 wfProfileOut( $fname );
3461 }
3462 }
3463
3464 /**
3465 * Callback function used by Parser::replaceLinkHolders()
3466 * to substitute link placeholders.
3467 */
3468 function &wfOutputReplaceMatches( $matches ) {
3469 global $wgOutputReplace;
3470 return $wgOutputReplace[$matches[1]];
3471 }
3472
3473 /**
3474 * Return the total number of articles
3475 */
3476 function wfNumberOfArticles() {
3477 global $wgNumberOfArticles;
3478
3479 wfLoadSiteStats();
3480 return $wgNumberOfArticles;
3481 }
3482
3483 /**
3484 * Return the number of files
3485 */
3486 function wfNumberOfFiles() {
3487 $fname = 'Parser::wfNumberOfFiles';
3488
3489 wfProfileIn( $fname );
3490 $dbr =& wfGetDB( DB_SLAVE );
3491 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3492 wfProfileOut( $fname );
3493
3494 return $res;
3495 }
3496
3497 /**
3498 * Get various statistics from the database
3499 * @private
3500 */
3501 function wfLoadSiteStats() {
3502 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3503 $fname = 'wfLoadSiteStats';
3504
3505 if ( -1 != $wgNumberOfArticles ) return;
3506 $dbr =& wfGetDB( DB_SLAVE );
3507 $s = $dbr->selectRow( 'site_stats',
3508 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3509 array( 'ss_row_id' => 1 ), $fname
3510 );
3511
3512 if ( $s === false ) {
3513 return;
3514 } else {
3515 $wgTotalViews = $s->ss_total_views;
3516 $wgTotalEdits = $s->ss_total_edits;
3517 $wgNumberOfArticles = $s->ss_good_articles;
3518 }
3519 }
3520
3521 /**
3522 * Escape html tags
3523 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3524 *
3525 * @param string $in Text that might contain HTML tags
3526 * @return string Escaped string
3527 */
3528 function wfEscapeHTMLTagsOnly( $in ) {
3529 return str_replace(
3530 array( '"', '>', '<' ),
3531 array( '&quot;', '&gt;', '&lt;' ),
3532 $in );
3533 }
3534
3535 ?>