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