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