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