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