* (bug 3420) Allow extensions to specify new parser variables ({{VAR}})
[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_FULLPAGENAME:
1910 return $this->mTitle->getPrefixedText();
1911 case MAG_FULLPAGENAMEE:
1912 return wfUrlencode( $this->mTitle->getPrefixedText() );
1913 case MAG_REVISIONID:
1914 return $wgArticle->getRevIdFetched();
1915 case MAG_NAMESPACE:
1916 return $wgContLang->getNsText( $this->mTitle->getNamespace() );
1917 case MAG_NAMESPACEE:
1918 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
1919 case MAG_CURRENTDAYNAME:
1920 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1921 case MAG_CURRENTYEAR:
1922 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ), true );
1923 case MAG_CURRENTTIME:
1924 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1925 case MAG_CURRENTWEEK:
1926 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1927 case MAG_CURRENTDOW:
1928 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1929 case MAG_NUMBEROFARTICLES:
1930 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1931 case MAG_NUMBEROFFILES:
1932 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1933 case MAG_SITENAME:
1934 return $wgSitename;
1935 case MAG_SERVER:
1936 return $wgServer;
1937 case MAG_SERVERNAME:
1938 return $wgServerName;
1939 case MAG_SCRIPTPATH:
1940 return $wgScriptPath;
1941 default:
1942 $ret = null;
1943 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
1944 return $ret;
1945 else
1946 return null;
1947 }
1948 }
1949
1950 /**
1951 * initialise the magic variables (like CURRENTMONTHNAME)
1952 *
1953 * @access private
1954 */
1955 function initialiseVariables() {
1956 $fname = 'Parser::initialiseVariables';
1957 wfProfileIn( $fname );
1958 global $wgVariableIDs;
1959 $this->mVariables = array();
1960 foreach ( $wgVariableIDs as $id ) {
1961 $mw =& MagicWord::get( $id );
1962 $mw->addToArray( $this->mVariables, $id );
1963 }
1964 wfProfileOut( $fname );
1965 }
1966
1967 /**
1968 * parse any parentheses in format ((title|part|part))
1969 * and call callbacks to get a replacement text for any found piece
1970 *
1971 * @param string $text The text to parse
1972 * @param array $callbacks rules in form:
1973 * '{' => array( # opening parentheses
1974 * 'end' => '}', # closing parentheses
1975 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
1976 * 4 => callback # replacement callback to call if {{{{..}}}} is found
1977 * )
1978 * )
1979 * @access private
1980 */
1981 function replace_callback ($text, $callbacks) {
1982 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
1983 $lastOpeningBrace = -1; # last not closed parentheses
1984
1985 for ($i = 0; $i < strlen($text); $i++) {
1986 # check for any opening brace
1987 $rule = null;
1988 $nextPos = -1;
1989 foreach ($callbacks as $key => $value) {
1990 $pos = strpos ($text, $key, $i);
1991 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
1992 $rule = $value;
1993 $nextPos = $pos;
1994 }
1995 }
1996
1997 if ($lastOpeningBrace >= 0) {
1998 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
1999
2000 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2001 $rule = null;
2002 $nextPos = $pos;
2003 }
2004
2005 $pos = strpos ($text, '|', $i);
2006
2007 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2008 $rule = null;
2009 $nextPos = $pos;
2010 }
2011 }
2012
2013 if ($nextPos == -1)
2014 break;
2015
2016 $i = $nextPos;
2017
2018 # found openning brace, lets add it to parentheses stack
2019 if (null != $rule) {
2020 $piece = array('brace' => $text[$i],
2021 'braceEnd' => $rule['end'],
2022 'count' => 1,
2023 'title' => '',
2024 'parts' => null);
2025
2026 # count openning brace characters
2027 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2028 $piece['count']++;
2029 $i++;
2030 }
2031
2032 $piece['startAt'] = $i+1;
2033 $piece['partStart'] = $i+1;
2034
2035 # we need to add to stack only if openning brace count is enough for any given rule
2036 foreach ($rule['cb'] as $cnt => $fn) {
2037 if ($piece['count'] >= $cnt) {
2038 $lastOpeningBrace ++;
2039 $openingBraceStack[$lastOpeningBrace] = $piece;
2040 break;
2041 }
2042 }
2043
2044 continue;
2045 }
2046 else if ($lastOpeningBrace >= 0) {
2047 # first check if it is a closing brace
2048 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2049 # lets check if it is enough characters for closing brace
2050 $count = 1;
2051 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2052 $count++;
2053
2054 # if there are more closing parentheses than opening ones, we parse less
2055 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2056 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2057
2058 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2059 $matchingCount = 0;
2060 $matchingCallback = null;
2061 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2062 if ($count >= $cnt && $matchingCount < $cnt) {
2063 $matchingCount = $cnt;
2064 $matchingCallback = $fn;
2065 }
2066 }
2067
2068 if ($matchingCount == 0) {
2069 $i += $count - 1;
2070 continue;
2071 }
2072
2073 # lets set a title or last part (if '|' was found)
2074 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2075 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2076 else
2077 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2078
2079 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2080 $pieceEnd = $i + $matchingCount;
2081
2082 if( is_callable( $matchingCallback ) ) {
2083 $cbArgs = array (
2084 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2085 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2086 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2087 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2088 );
2089 # finally we can call a user callback and replace piece of text
2090 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2091 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2092 $i = $pieceStart + strlen($replaceWith) - 1;
2093 }
2094 else {
2095 # null value for callback means that parentheses should be parsed, but not replaced
2096 $i += $matchingCount - 1;
2097 }
2098
2099 # reset last openning parentheses, but keep it in case there are unused characters
2100 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2101 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2102 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2103 'title' => '',
2104 'parts' => null,
2105 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2106 $openingBraceStack[$lastOpeningBrace--] = null;
2107
2108 if ($matchingCount < $piece['count']) {
2109 $piece['count'] -= $matchingCount;
2110 $piece['startAt'] -= $matchingCount;
2111 $piece['partStart'] = $piece['startAt'];
2112 # do we still qualify for any callback with remaining count?
2113 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2114 if ($piece['count'] >= $cnt) {
2115 $lastOpeningBrace ++;
2116 $openingBraceStack[$lastOpeningBrace] = $piece;
2117 break;
2118 }
2119 }
2120 }
2121 continue;
2122 }
2123
2124 # lets set a title if it is a first separator, or next part otherwise
2125 if ($text[$i] == '|') {
2126 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2127 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2128 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2129 }
2130 else
2131 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2132
2133 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2134 }
2135 }
2136 }
2137
2138 return $text;
2139 }
2140
2141 /**
2142 * Replace magic variables, templates, and template arguments
2143 * with the appropriate text. Templates are substituted recursively,
2144 * taking care to avoid infinite loops.
2145 *
2146 * Note that the substitution depends on value of $mOutputType:
2147 * OT_WIKI: only {{subst:}} templates
2148 * OT_MSG: only magic variables
2149 * OT_HTML: all templates and magic variables
2150 *
2151 * @param string $tex The text to transform
2152 * @param array $args Key-value pairs representing template parameters to substitute
2153 * @access private
2154 */
2155 function replaceVariables( $text, $args = array() ) {
2156 # Prevent too big inclusions
2157 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2158 return $text;
2159 }
2160
2161 $fname = 'Parser::replaceVariables';
2162 wfProfileIn( $fname );
2163
2164 # This function is called recursively. To keep track of arguments we need a stack:
2165 array_push( $this->mArgStack, $args );
2166
2167 $braceCallbacks = array();
2168 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2169 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2170 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2171 }
2172 $callbacks = array();
2173 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2174 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2175 $text = $this->replace_callback ($text, $callbacks);
2176
2177 array_pop( $this->mArgStack );
2178
2179 wfProfileOut( $fname );
2180 return $text;
2181 }
2182
2183 /**
2184 * Replace magic variables
2185 * @access private
2186 */
2187 function variableSubstitution( $matches ) {
2188 $fname = 'parser::variableSubstitution';
2189 $varname = $matches[1];
2190 wfProfileIn( $fname );
2191 if ( !$this->mVariables ) {
2192 $this->initialiseVariables();
2193 }
2194 $skip = false;
2195 if ( $this->mOutputType == OT_WIKI ) {
2196 # Do only magic variables prefixed by SUBST
2197 $mwSubst =& MagicWord::get( MAG_SUBST );
2198 if (!$mwSubst->matchStartAndRemove( $varname ))
2199 $skip = true;
2200 # Note that if we don't substitute the variable below,
2201 # we don't remove the {{subst:}} magic word, in case
2202 # it is a template rather than a magic variable.
2203 }
2204 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2205 $id = $this->mVariables[$varname];
2206 $text = $this->getVariableValue( $id );
2207 $this->mOutput->mContainsOldMagic = true;
2208 } else {
2209 $text = $matches[0];
2210 }
2211 wfProfileOut( $fname );
2212 return $text;
2213 }
2214
2215 # Split template arguments
2216 function getTemplateArgs( $argsString ) {
2217 if ( $argsString === '' ) {
2218 return array();
2219 }
2220
2221 $args = explode( '|', substr( $argsString, 1 ) );
2222
2223 # If any of the arguments contains a '[[' but no ']]', it needs to be
2224 # merged with the next arg because the '|' character between belongs
2225 # to the link syntax and not the template parameter syntax.
2226 $argc = count($args);
2227
2228 for ( $i = 0; $i < $argc-1; $i++ ) {
2229 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2230 $args[$i] .= '|'.$args[$i+1];
2231 array_splice($args, $i+1, 1);
2232 $i--;
2233 $argc--;
2234 }
2235 }
2236
2237 return $args;
2238 }
2239
2240 /**
2241 * Return the text of a template, after recursively
2242 * replacing any variables or templates within the template.
2243 *
2244 * @param array $piece The parts of the template
2245 * $piece['text']: matched text
2246 * $piece['title']: the title, i.e. the part before the |
2247 * $piece['parts']: the parameter array
2248 * @return string the text of the template
2249 * @access private
2250 */
2251 function braceSubstitution( $piece ) {
2252 global $wgLinkCache, $wgContLang;
2253 $fname = 'Parser::braceSubstitution';
2254 wfProfileIn( $fname );
2255
2256 $found = false;
2257 $nowiki = false;
2258 $noparse = false;
2259
2260 $title = NULL;
2261
2262 $linestart = '';
2263
2264 # $part1 is the bit before the first |, and must contain only title characters
2265 # $args is a list of arguments, starting from index 0, not including $part1
2266
2267 $part1 = $piece['title'];
2268 # If the third subpattern matched anything, it will start with |
2269
2270 if (null == $piece['parts']) {
2271 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2272 if ($replaceWith != $piece['text']) {
2273 $text = $replaceWith;
2274 $found = true;
2275 $noparse = true;
2276 }
2277 }
2278
2279 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2280 $argc = count( $args );
2281
2282 # SUBST
2283 if ( !$found ) {
2284 $mwSubst =& MagicWord::get( MAG_SUBST );
2285 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2286 # One of two possibilities is true:
2287 # 1) Found SUBST but not in the PST phase
2288 # 2) Didn't find SUBST and in the PST phase
2289 # In either case, return without further processing
2290 $text = $piece['text'];
2291 $found = true;
2292 $noparse = true;
2293 }
2294 }
2295
2296 # MSG, MSGNW and INT
2297 if ( !$found ) {
2298 # Check for MSGNW:
2299 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2300 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2301 $nowiki = true;
2302 } else {
2303 # Remove obsolete MSG:
2304 $mwMsg =& MagicWord::get( MAG_MSG );
2305 $mwMsg->matchStartAndRemove( $part1 );
2306 }
2307
2308 # Check if it is an internal message
2309 $mwInt =& MagicWord::get( MAG_INT );
2310 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2311 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2312 $text = $linestart . wfMsgReal( $part1, $args, true );
2313 $found = true;
2314 }
2315 }
2316 }
2317
2318 # NS
2319 if ( !$found ) {
2320 # Check for NS: (namespace expansion)
2321 $mwNs = MagicWord::get( MAG_NS );
2322 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2323 if ( intval( $part1 ) ) {
2324 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2325 $found = true;
2326 } else {
2327 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2328 if ( !is_null( $index ) ) {
2329 $text = $linestart . $wgContLang->getNsText( $index );
2330 $found = true;
2331 }
2332 }
2333 }
2334 }
2335
2336 # LCFIRST, UCFIRST, LC and UC
2337 if ( !$found ) {
2338 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2339 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2340 $lc =& MagicWord::get( MAG_LC );
2341 $uc =& MagicWord::get( MAG_UC );
2342 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2343 $text = $linestart . $wgContLang->lcfirst( $part1 );
2344 $found = true;
2345 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2346 $text = $linestart . $wgContLang->ucfirst( $part1 );
2347 $found = true;
2348 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2349 $text = $linestart . $wgContLang->lc( $part1 );
2350 $found = true;
2351 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2352 $text = $linestart . $wgContLang->uc( $part1 );
2353 $found = true;
2354 }
2355 }
2356
2357 # LOCALURL and FULLURL
2358 if ( !$found ) {
2359 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2360 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2361 $mwFull =& MagicWord::get( MAG_FULLURL );
2362 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2363
2364
2365 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2366 $func = 'getLocalURL';
2367 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2368 $func = 'escapeLocalURL';
2369 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2370 $func = 'getFullURL';
2371 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2372 $func = 'escapeFullURL';
2373 } else {
2374 $func = false;
2375 }
2376
2377 if ( $func !== false ) {
2378 $title = Title::newFromText( $part1 );
2379 if ( !is_null( $title ) ) {
2380 if ( $argc > 0 ) {
2381 $text = $linestart . $title->$func( $args[0] );
2382 } else {
2383 $text = $linestart . $title->$func();
2384 }
2385 $found = true;
2386 }
2387 }
2388 }
2389
2390 # GRAMMAR
2391 if ( !$found && $argc == 1 ) {
2392 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2393 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2394 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2395 $found = true;
2396 }
2397 }
2398
2399 # PLURAL
2400 if ( !$found && $argc >= 2 ) {
2401 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2402 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2403 if ($argc==2) {$args[2]=$args[1];}
2404 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2405 $found = true;
2406 }
2407 }
2408
2409 # Template table test
2410
2411 # Did we encounter this template already? If yes, it is in the cache
2412 # and we need to check for loops.
2413 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
2414 $found = true;
2415
2416 # Infinite loop test
2417 if ( isset( $this->mTemplatePath[$part1] ) ) {
2418 $noparse = true;
2419 $found = true;
2420 $text = $linestart .
2421 "\{\{$part1}}" .
2422 '<!-- WARNING: template loop detected -->';
2423 wfDebug( "$fname: template loop broken at '$part1'\n" );
2424 } else {
2425 # set $text to cached message.
2426 $text = $linestart . $this->mTemplates[$part1];
2427 }
2428 }
2429
2430 # Load from database
2431 $replaceHeadings = false;
2432 $isHTML = false;
2433 $lastPathLevel = $this->mTemplatePath;
2434 if ( !$found ) {
2435 $ns = NS_TEMPLATE;
2436 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2437 if ($subpage !== '') {
2438 $ns = $this->mTitle->getNamespace();
2439 }
2440 $title = Title::newFromText( $part1, $ns );
2441
2442 if ($title) {
2443 $interwiki = Title::getInterwikiLink($title->getInterwiki());
2444 if ($interwiki != '' && $title->isTrans()) {
2445 return $this->scarytransclude($title, $interwiki);
2446 }
2447 }
2448
2449 if ( !is_null( $title ) && !$title->isExternal() ) {
2450 # Check for excessive inclusion
2451 $dbk = $title->getPrefixedDBkey();
2452 if ( $this->incrementIncludeCount( $dbk ) ) {
2453 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2454 # Capture special page output
2455 $text = SpecialPage::capturePath( $title );
2456 if ( is_string( $text ) ) {
2457 $found = true;
2458 $noparse = true;
2459 $isHTML = true;
2460 $this->disableCache();
2461 }
2462 } else {
2463 $article = new Article( $title );
2464 $articleContent = $article->fetchContent(0, false);
2465 if ( $articleContent !== false ) {
2466 $found = true;
2467 $text = $articleContent;
2468 $replaceHeadings = true;
2469 }
2470 }
2471 }
2472
2473 # If the title is valid but undisplayable, make a link to it
2474 if ( $this->mOutputType == OT_HTML && !$found ) {
2475 $text = '[['.$title->getPrefixedText().']]';
2476 $found = true;
2477 }
2478
2479 # Template cache array insertion
2480 if( $found ) {
2481 $this->mTemplates[$part1] = $text;
2482 $text = $linestart . $text;
2483 }
2484 }
2485 }
2486
2487 # Recursive parsing, escaping and link table handling
2488 # Only for HTML output
2489 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2490 $text = wfEscapeWikiText( $text );
2491 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2492 # Clean up argument array
2493 $assocArgs = array();
2494 $index = 1;
2495 foreach( $args as $arg ) {
2496 $eqpos = strpos( $arg, '=' );
2497 if ( $eqpos === false ) {
2498 $assocArgs[$index++] = $arg;
2499 } else {
2500 $name = trim( substr( $arg, 0, $eqpos ) );
2501 $value = trim( substr( $arg, $eqpos+1 ) );
2502 if ( $value === false ) {
2503 $value = '';
2504 }
2505 if ( $name !== false ) {
2506 $assocArgs[$name] = $value;
2507 }
2508 }
2509 }
2510
2511 # Add a new element to the templace recursion path
2512 $this->mTemplatePath[$part1] = 1;
2513
2514 # If there are any <onlyinclude> tags, only include them
2515 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2516 preg_match_all( '/<onlyinclude>(.*?)<\/onlyinclude>/s', $text, $m );
2517 $text = '';
2518 foreach ($m[1] as $piece)
2519 $text .= $this->trimOnlyinclude( $piece );
2520 }
2521 # Remove <noinclude> sections and <includeonly> tags
2522 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2523 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2524
2525 if( $this->mOutputType == OT_HTML ) {
2526 # Strip <nowiki>, <pre>, etc.
2527 $text = $this->strip( $text, $this->mStripState );
2528 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2529 }
2530 $text = $this->replaceVariables( $text, $assocArgs );
2531
2532 # Resume the link cache and register the inclusion as a link
2533 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2534 $wgLinkCache->addLinkObj( $title );
2535 }
2536
2537 # If the template begins with a table or block-level
2538 # element, it should be treated as beginning a new line.
2539 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2540 $text = "\n" . $text;
2541 }
2542 }
2543 # Prune lower levels off the recursion check path
2544 $this->mTemplatePath = $lastPathLevel;
2545
2546 if ( !$found ) {
2547 wfProfileOut( $fname );
2548 return $piece['text'];
2549 } else {
2550 if ( $isHTML ) {
2551 # Replace raw HTML by a placeholder
2552 # Add a blank line preceding, to prevent it from mucking up
2553 # immediately preceding headings
2554 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2555 } else {
2556 # replace ==section headers==
2557 # XXX this needs to go away once we have a better parser.
2558 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2559 if( !is_null( $title ) )
2560 $encodedname = base64_encode($title->getPrefixedDBkey());
2561 else
2562 $encodedname = base64_encode("");
2563 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2564 PREG_SPLIT_DELIM_CAPTURE);
2565 $text = '';
2566 $nsec = 0;
2567 for( $i = 0; $i < count($m); $i += 2 ) {
2568 $text .= $m[$i];
2569 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2570 $hl = $m[$i + 1];
2571 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2572 $text .= $hl;
2573 continue;
2574 }
2575 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2576 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2577 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2578
2579 $nsec++;
2580 }
2581 }
2582 }
2583 }
2584
2585 # Prune lower levels off the recursion check path
2586 $this->mTemplatePath = $lastPathLevel;
2587
2588 if ( !$found ) {
2589 wfProfileOut( $fname );
2590 return $piece['text'];
2591 } else {
2592 wfProfileOut( $fname );
2593 return $text;
2594 }
2595 }
2596
2597 /**
2598 * Trim the first and last newlines of a string, this is not equivalent
2599 * to trim( $str, "\n" ) which would trim them all.
2600 *
2601 * @param string $str The string to trim
2602 * @return string
2603 */
2604 function trimOnlyinclude( $str ) {
2605 $str = preg_replace( "/^\n/", '', $str );
2606 $str = preg_replace( "/\n$/", '', $str );
2607 return $str;
2608 }
2609
2610 /**
2611 * Translude an interwiki link.
2612 */
2613 function scarytransclude($title, $interwiki) {
2614 global $wgEnableScaryTranscluding;
2615
2616 if (!$wgEnableScaryTranscluding)
2617 return wfMsg('scarytranscludedisabled');
2618
2619 $articlename = "Template:" . $title->getDBkey();
2620 $url = str_replace('$1', urlencode($articlename), $interwiki);
2621 if (strlen($url) > 255)
2622 return wfMsg('scarytranscludetoolong');
2623 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2624 $this->mIWTransData[] = $text;
2625 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData) - 1)."-->";
2626 }
2627
2628 function fetchScaryTemplateMaybeFromCache($url) {
2629 $dbr =& wfGetDB(DB_SLAVE);
2630 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2631 array('tc_url' => $url));
2632 if ($obj) {
2633 $time = $obj->tc_time;
2634 $text = $obj->tc_contents;
2635 if ($time && $time < (time() + (60*60))) {
2636 return $text;
2637 }
2638 }
2639
2640 $text = wfGetHTTP($url . '?action=render');
2641 if (!$text)
2642 return wfMsg('scarytranscludefailed', $url);
2643
2644 $dbw =& wfGetDB(DB_MASTER);
2645 $dbw->replace('transcache', array(), array(
2646 'tc_url' => $url,
2647 'tc_time' => time(),
2648 'tc_contents' => $text));
2649 return $text;
2650 }
2651
2652
2653 /**
2654 * Triple brace replacement -- used for template arguments
2655 * @access private
2656 */
2657 function argSubstitution( $matches ) {
2658 $arg = trim( $matches['title'] );
2659 $text = $matches['text'];
2660 $inputArgs = end( $this->mArgStack );
2661
2662 if ( array_key_exists( $arg, $inputArgs ) ) {
2663 $text = $inputArgs[$arg];
2664 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
2665 $text = $matches['parts'][0];
2666 }
2667
2668 return $text;
2669 }
2670
2671 /**
2672 * Returns true if the function is allowed to include this entity
2673 * @access private
2674 */
2675 function incrementIncludeCount( $dbk ) {
2676 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2677 $this->mIncludeCount[$dbk] = 0;
2678 }
2679 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2680 return true;
2681 } else {
2682 return false;
2683 }
2684 }
2685
2686 /**
2687 * This function accomplishes several tasks:
2688 * 1) Auto-number headings if that option is enabled
2689 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2690 * 3) Add a Table of contents on the top for users who have enabled the option
2691 * 4) Auto-anchor headings
2692 *
2693 * It loops through all headlines, collects the necessary data, then splits up the
2694 * string and re-inserts the newly formatted headlines.
2695 *
2696 * @param string $text
2697 * @param boolean $isMain
2698 * @access private
2699 */
2700 function formatHeadings( $text, $isMain=true ) {
2701 global $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2702
2703 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2704 $doShowToc = true;
2705 $forceTocHere = false;
2706 if( !$this->mTitle->userCanEdit() ) {
2707 $showEditLink = 0;
2708 } else {
2709 $showEditLink = $this->mOptions->getEditSection();
2710 }
2711
2712 # Inhibit editsection links if requested in the page
2713 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2714 if( $esw->matchAndRemove( $text ) ) {
2715 $showEditLink = 0;
2716 }
2717 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2718 # do not add TOC
2719 $mw =& MagicWord::get( MAG_NOTOC );
2720 if( $mw->matchAndRemove( $text ) ) {
2721 $doShowToc = false;
2722 }
2723
2724 # Get all headlines for numbering them and adding funky stuff like [edit]
2725 # links - this is for later, but we need the number of headlines right now
2726 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2727
2728 # if there are fewer than 4 headlines in the article, do not show TOC
2729 if( $numMatches < 4 ) {
2730 $doShowToc = false;
2731 }
2732
2733 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2734 # override above conditions and always show TOC at that place
2735
2736 $mw =& MagicWord::get( MAG_TOC );
2737 if($mw->match( $text ) ) {
2738 $doShowToc = true;
2739 $forceTocHere = true;
2740 } else {
2741 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2742 # override above conditions and always show TOC above first header
2743 $mw =& MagicWord::get( MAG_FORCETOC );
2744 if ($mw->matchAndRemove( $text ) ) {
2745 $doShowToc = true;
2746 }
2747 }
2748
2749 # Never ever show TOC if no headers
2750 if( $numMatches < 1 ) {
2751 $doShowToc = false;
2752 }
2753
2754 # We need this to perform operations on the HTML
2755 $sk =& $this->mOptions->getSkin();
2756
2757 # headline counter
2758 $headlineCount = 0;
2759 $sectionCount = 0; # headlineCount excluding template sections
2760
2761 # Ugh .. the TOC should have neat indentation levels which can be
2762 # passed to the skin functions. These are determined here
2763 $toc = '';
2764 $full = '';
2765 $head = array();
2766 $sublevelCount = array();
2767 $levelCount = array();
2768 $toclevel = 0;
2769 $level = 0;
2770 $prevlevel = 0;
2771 $toclevel = 0;
2772 $prevtoclevel = 0;
2773
2774 foreach( $matches[3] as $headline ) {
2775 $istemplate = 0;
2776 $templatetitle = '';
2777 $templatesection = 0;
2778 $numbering = '';
2779
2780 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2781 $istemplate = 1;
2782 $templatetitle = base64_decode($mat[1]);
2783 $templatesection = 1 + (int)base64_decode($mat[2]);
2784 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2785 }
2786
2787 if( $toclevel ) {
2788 $prevlevel = $level;
2789 $prevtoclevel = $toclevel;
2790 }
2791 $level = $matches[1][$headlineCount];
2792
2793 if( $doNumberHeadings || $doShowToc ) {
2794
2795 if ( $level > $prevlevel ) {
2796 # Increase TOC level
2797 $toclevel++;
2798 $sublevelCount[$toclevel] = 0;
2799 $toc .= $sk->tocIndent();
2800 }
2801 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2802 # Decrease TOC level, find level to jump to
2803
2804 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2805 # Can only go down to level 1
2806 $toclevel = 1;
2807 } else {
2808 for ($i = $toclevel; $i > 0; $i--) {
2809 if ( $levelCount[$i] == $level ) {
2810 # Found last matching level
2811 $toclevel = $i;
2812 break;
2813 }
2814 elseif ( $levelCount[$i] < $level ) {
2815 # Found first matching level below current level
2816 $toclevel = $i + 1;
2817 break;
2818 }
2819 }
2820 }
2821
2822 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2823 }
2824 else {
2825 # No change in level, end TOC line
2826 $toc .= $sk->tocLineEnd();
2827 }
2828
2829 $levelCount[$toclevel] = $level;
2830
2831 # count number of headlines for each level
2832 @$sublevelCount[$toclevel]++;
2833 $dot = 0;
2834 for( $i = 1; $i <= $toclevel; $i++ ) {
2835 if( !empty( $sublevelCount[$i] ) ) {
2836 if( $dot ) {
2837 $numbering .= '.';
2838 }
2839 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2840 $dot = 1;
2841 }
2842 }
2843 }
2844
2845 # The canonized header is a version of the header text safe to use for links
2846 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2847 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2848 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2849
2850 # Remove link placeholders by the link text.
2851 # <!--LINK number-->
2852 # turns into
2853 # link text with suffix
2854 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2855 "\$this->mLinkHolders['texts'][\$1]",
2856 $canonized_headline );
2857 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2858 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2859 $canonized_headline );
2860
2861 # strip out HTML
2862 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2863 $tocline = trim( $canonized_headline );
2864 $canonized_headline = urlencode( Sanitizer::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2865 $replacearray = array(
2866 '%3A' => ':',
2867 '%' => '.'
2868 );
2869 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2870 $refers[$headlineCount] = $canonized_headline;
2871
2872 # count how many in assoc. array so we can track dupes in anchors
2873 @$refers[$canonized_headline]++;
2874 $refcount[$headlineCount]=$refers[$canonized_headline];
2875
2876 # Don't number the heading if it is the only one (looks silly)
2877 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2878 # the two are different if the line contains a link
2879 $headline=$numbering . ' ' . $headline;
2880 }
2881
2882 # Create the anchor for linking from the TOC to the section
2883 $anchor = $canonized_headline;
2884 if($refcount[$headlineCount] > 1 ) {
2885 $anchor .= '_' . $refcount[$headlineCount];
2886 }
2887 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2888 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2889 }
2890 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2891 if ( empty( $head[$headlineCount] ) ) {
2892 $head[$headlineCount] = '';
2893 }
2894 if( $istemplate )
2895 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2896 else
2897 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2898 }
2899
2900 # give headline the correct <h#> tag
2901 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2902
2903 $headlineCount++;
2904 if( !$istemplate )
2905 $sectionCount++;
2906 }
2907
2908 if( $doShowToc ) {
2909 $toc .= $sk->tocUnindent( $toclevel - 1 );
2910 $toc = $sk->tocList( $toc );
2911 }
2912
2913 # split up and insert constructed headlines
2914
2915 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2916 $i = 0;
2917
2918 foreach( $blocks as $block ) {
2919 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2920 # This is the [edit] link that appears for the top block of text when
2921 # section editing is enabled
2922
2923 # Disabled because it broke block formatting
2924 # For example, a bullet point in the top line
2925 # $full .= $sk->editSectionLink(0);
2926 }
2927 $full .= $block;
2928 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2929 # Top anchor now in skin
2930 $full = $full.$toc;
2931 }
2932
2933 if( !empty( $head[$i] ) ) {
2934 $full .= $head[$i];
2935 }
2936 $i++;
2937 }
2938 if($forceTocHere) {
2939 $mw =& MagicWord::get( MAG_TOC );
2940 return $mw->replace( $toc, $full );
2941 } else {
2942 return $full;
2943 }
2944 }
2945
2946 /**
2947 * Return an HTML link for the "ISBN 123456" text
2948 * @access private
2949 */
2950 function magicISBN( $text ) {
2951 $fname = 'Parser::magicISBN';
2952 wfProfileIn( $fname );
2953
2954 $a = split( 'ISBN ', ' '.$text );
2955 if ( count ( $a ) < 2 ) {
2956 wfProfileOut( $fname );
2957 return $text;
2958 }
2959 $text = substr( array_shift( $a ), 1);
2960 $valid = '0123456789-Xx';
2961
2962 foreach ( $a as $x ) {
2963 $isbn = $blank = '' ;
2964 while ( ' ' == $x{0} ) {
2965 $blank .= ' ';
2966 $x = substr( $x, 1 );
2967 }
2968 if ( $x == '' ) { # blank isbn
2969 $text .= "ISBN $blank";
2970 continue;
2971 }
2972 while ( strstr( $valid, $x{0} ) != false ) {
2973 $isbn .= $x{0};
2974 $x = substr( $x, 1 );
2975 }
2976 $num = str_replace( '-', '', $isbn );
2977 $num = str_replace( ' ', '', $num );
2978 $num = str_replace( 'x', 'X', $num );
2979
2980 if ( '' == $num ) {
2981 $text .= "ISBN $blank$x";
2982 } else {
2983 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2984 $text .= '<a href="' .
2985 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2986 "\" class=\"internal\">ISBN $isbn</a>";
2987 $text .= $x;
2988 }
2989 }
2990 wfProfileOut( $fname );
2991 return $text;
2992 }
2993
2994 /**
2995 * Return an HTML link for the "RFC 1234" text
2996 *
2997 * @access private
2998 * @param string $text Text to be processed
2999 * @param string $keyword Magic keyword to use (default RFC)
3000 * @param string $urlmsg Interface message to use (default rfcurl)
3001 * @return string
3002 */
3003 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3004
3005 $valid = '0123456789';
3006 $internal = false;
3007
3008 $a = split( $keyword, ' '.$text );
3009 if ( count ( $a ) < 2 ) {
3010 return $text;
3011 }
3012 $text = substr( array_shift( $a ), 1);
3013
3014 /* Check if keyword is preceed by [[.
3015 * This test is made here cause of the array_shift above
3016 * that prevent the test to be done in the foreach.
3017 */
3018 if ( substr( $text, -2 ) == '[[' ) {
3019 $internal = true;
3020 }
3021
3022 foreach ( $a as $x ) {
3023 /* token might be empty if we have RFC RFC 1234 */
3024 if ( $x=='' ) {
3025 $text.=$keyword;
3026 continue;
3027 }
3028
3029 $id = $blank = '' ;
3030
3031 /** remove and save whitespaces in $blank */
3032 while ( $x{0} == ' ' ) {
3033 $blank .= ' ';
3034 $x = substr( $x, 1 );
3035 }
3036
3037 /** remove and save the rfc number in $id */
3038 while ( strstr( $valid, $x{0} ) != false ) {
3039 $id .= $x{0};
3040 $x = substr( $x, 1 );
3041 }
3042
3043 if ( $id == '' ) {
3044 /* call back stripped spaces*/
3045 $text .= $keyword.$blank.$x;
3046 } elseif( $internal ) {
3047 /* normal link */
3048 $text .= $keyword.$id.$x;
3049 } else {
3050 /* build the external link*/
3051 $url = wfMsg( $urlmsg, $id);
3052 $sk =& $this->mOptions->getSkin();
3053 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3054 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3055 }
3056
3057 /* Check if the next RFC keyword is preceed by [[ */
3058 $internal = ( substr($x,-2) == '[[' );
3059 }
3060 return $text;
3061 }
3062
3063 /**
3064 * Transform wiki markup when saving a page by doing \r\n -> \n
3065 * conversion, substitting signatures, {{subst:}} templates, etc.
3066 *
3067 * @param string $text the text to transform
3068 * @param Title &$title the Title object for the current article
3069 * @param User &$user the User object describing the current user
3070 * @param ParserOptions $options parsing options
3071 * @param bool $clearState whether to clear the parser state first
3072 * @return string the altered wiki markup
3073 * @access public
3074 */
3075 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3076 $this->mOptions = $options;
3077 $this->mTitle =& $title;
3078 $this->mOutputType = OT_WIKI;
3079
3080 if ( $clearState ) {
3081 $this->clearState();
3082 }
3083
3084 $stripState = false;
3085 $pairs = array(
3086 "\r\n" => "\n",
3087 );
3088 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3089 $text = $this->strip( $text, $stripState, true );
3090 $text = $this->pstPass2( $text, $user );
3091 $text = $this->unstrip( $text, $stripState );
3092 $text = $this->unstripNoWiki( $text, $stripState );
3093 return $text;
3094 }
3095
3096 /**
3097 * Pre-save transform helper function
3098 * @access private
3099 */
3100 function pstPass2( $text, &$user ) {
3101 global $wgContLang, $wgLocaltimezone;
3102
3103 # Variable replacement
3104 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3105 $text = $this->replaceVariables( $text );
3106
3107 # Signatures
3108 #
3109 $sigText = $this->getUserSig( $user );
3110
3111 /* Note: This is the timestamp saved as hardcoded wikitext to
3112 * the database, we use $wgContLang here in order to give
3113 * everyone the same signiture and use the default one rather
3114 * than the one selected in each users preferences.
3115 */
3116 if ( isset( $wgLocaltimezone ) ) {
3117 $oldtz = getenv( 'TZ' );
3118 putenv( 'TZ='.$wgLocaltimezone );
3119 }
3120 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3121 ' (' . date( 'T' ) . ')';
3122 if ( isset( $wgLocaltimezone ) ) {
3123 putenv( 'TZ='.$oldtz );
3124 }
3125
3126 $text = preg_replace( '/~~~~~/', $d, $text );
3127 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3128 $text = preg_replace( '/~~~/', $sigText, $text );
3129
3130 # Context links: [[|name]] and [[name (context)|]]
3131 #
3132 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
3133 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
3134 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3135 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3136
3137 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3138 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3139 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3140 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3141 $context = '';
3142 $t = $this->mTitle->getText();
3143 if ( preg_match( $conpat, $t, $m ) ) {
3144 $context = $m[2];
3145 }
3146 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3147 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3148 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3149
3150 if ( '' == $context ) {
3151 $text = preg_replace( $p2, '[[\\1]]', $text );
3152 } else {
3153 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3154 }
3155
3156 # Trim trailing whitespace
3157 # MAG_END (__END__) tag allows for trailing
3158 # whitespace to be deliberately included
3159 $text = rtrim( $text );
3160 $mw =& MagicWord::get( MAG_END );
3161 $mw->matchAndRemove( $text );
3162
3163 return $text;
3164 }
3165
3166 /**
3167 * Fetch the user's signature text, if any, and normalize to
3168 * validated, ready-to-insert wikitext.
3169 *
3170 * @param User $user
3171 * @return string
3172 * @access private
3173 */
3174 function getUserSig( &$user ) {
3175 $name = $user->getName();
3176 $nick = trim( $user->getOption( 'nickname' ) );
3177 if ( '' == $nick ) {
3178 $nick = $name;
3179 }
3180
3181 if( $user->getOption( 'fancysig' ) ) {
3182 // A wikitext signature.
3183 $valid = $this->validateSig( $nick );
3184 if( $valid === false ) {
3185 // Fall back to default sig
3186 $nick = $name;
3187 wfDebug( "Parser::getUserSig: $name has bad XML tags in signature.\n" );
3188 } else {
3189 return $nick;
3190 }
3191 }
3192
3193 // Plain text linking to the user's homepage
3194 global $wgContLang;
3195 $page = $user->getUserPage();
3196 return '[[' .
3197 $page->getPrefixedText() .
3198 "|" .
3199 wfEscapeWikIText( $nick ) .
3200 "]]";
3201 }
3202
3203 /**
3204 * We want to enforce two rules on wikitext sigs here:
3205 * 1) Expand any templates at save time (forced subst:)
3206 * 2) Check for unbalanced XML tags, and reject if so.
3207 *
3208 * @param string $text
3209 * @return mixed An expanded string, or false if invalid.
3210 *
3211 * @todo Run brace substitutions
3212 * @todo ?? Check for unbalanced '' and ''' quotes, etc
3213 */
3214 function validateSig( $text ) {
3215 if( wfIsWellFormedXmlFragment( $text ) ) {
3216 return $text;
3217 } else {
3218 return false;
3219 }
3220 }
3221
3222 /**
3223 * Set up some variables which are usually set up in parse()
3224 * so that an external function can call some class members with confidence
3225 * @access public
3226 */
3227 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3228 $this->mTitle =& $title;
3229 $this->mOptions = $options;
3230 $this->mOutputType = $outputType;
3231 if ( $clearState ) {
3232 $this->clearState();
3233 }
3234 }
3235
3236 /**
3237 * Transform a MediaWiki message by replacing magic variables.
3238 *
3239 * @param string $text the text to transform
3240 * @param ParserOptions $options options
3241 * @return string the text with variables substituted
3242 * @access public
3243 */
3244 function transformMsg( $text, $options ) {
3245 global $wgTitle;
3246 static $executing = false;
3247
3248 # Guard against infinite recursion
3249 if ( $executing ) {
3250 return $text;
3251 }
3252 $executing = true;
3253
3254 $this->mTitle = $wgTitle;
3255 $this->mOptions = $options;
3256 $this->mOutputType = OT_MSG;
3257 $this->clearState();
3258 $text = $this->replaceVariables( $text );
3259
3260 $executing = false;
3261 return $text;
3262 }
3263
3264 /**
3265 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3266 * Callback will be called with the text within
3267 * Transform and return the text within
3268 * @access public
3269 */
3270 function setHook( $tag, $callback ) {
3271 $oldVal = @$this->mTagHooks[$tag];
3272 $this->mTagHooks[$tag] = $callback;
3273 return $oldVal;
3274 }
3275
3276 /**
3277 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3278 * Placeholders created in Skin::makeLinkObj()
3279 * Returns an array of links found, indexed by PDBK:
3280 * 0 - broken
3281 * 1 - normal link
3282 * 2 - stub
3283 * $options is a bit field, RLH_FOR_UPDATE to select for update
3284 */
3285 function replaceLinkHolders( &$text, $options = 0 ) {
3286 global $wgUser, $wgLinkCache;
3287 global $wgOutputReplace;
3288
3289 $fname = 'Parser::replaceLinkHolders';
3290 wfProfileIn( $fname );
3291
3292 $pdbks = array();
3293 $colours = array();
3294 $sk = $this->mOptions->getSkin();
3295
3296 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3297 wfProfileIn( $fname.'-check' );
3298 $dbr =& wfGetDB( DB_SLAVE );
3299 $page = $dbr->tableName( 'page' );
3300 $threshold = $wgUser->getOption('stubthreshold');
3301
3302 # Sort by namespace
3303 asort( $this->mLinkHolders['namespaces'] );
3304
3305 # Generate query
3306 $query = false;
3307 foreach ( $this->mLinkHolders['namespaces'] as $key => $val ) {
3308 # Make title object
3309 $title = $this->mLinkHolders['titles'][$key];
3310
3311 # Skip invalid entries.
3312 # Result will be ugly, but prevents crash.
3313 if ( is_null( $title ) ) {
3314 continue;
3315 }
3316 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3317
3318 # Check if it's in the link cache already
3319 if ( $title->isAlwaysKnown() || $wgLinkCache->getGoodLinkID( $pdbk ) ) {
3320 $colours[$pdbk] = 1;
3321 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3322 $colours[$pdbk] = 0;
3323 } else {
3324 # Not in the link cache, add it to the query
3325 if ( !isset( $current ) ) {
3326 $current = $val;
3327 $query = "SELECT page_id, page_namespace, page_title";
3328 if ( $threshold > 0 ) {
3329 $query .= ', page_len, page_is_redirect';
3330 }
3331 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3332 } elseif ( $current != $val ) {
3333 $current = $val;
3334 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3335 } else {
3336 $query .= ', ';
3337 }
3338
3339 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3340 }
3341 }
3342 if ( $query ) {
3343 $query .= '))';
3344 if ( $options & RLH_FOR_UPDATE ) {
3345 $query .= ' FOR UPDATE';
3346 }
3347
3348 $res = $dbr->query( $query, $fname );
3349
3350 # Fetch data and form into an associative array
3351 # non-existent = broken
3352 # 1 = known
3353 # 2 = stub
3354 while ( $s = $dbr->fetchObject($res) ) {
3355 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3356 $pdbk = $title->getPrefixedDBkey();
3357 $wgLinkCache->addGoodLinkObj( $s->page_id, $title );
3358
3359 if ( $threshold > 0 ) {
3360 $size = $s->page_len;
3361 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3362 $colours[$pdbk] = 1;
3363 } else {
3364 $colours[$pdbk] = 2;
3365 }
3366 } else {
3367 $colours[$pdbk] = 1;
3368 }
3369 }
3370 }
3371 wfProfileOut( $fname.'-check' );
3372
3373 # Construct search and replace arrays
3374 wfProfileIn( $fname.'-construct' );
3375 $wgOutputReplace = array();
3376 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3377 $pdbk = $pdbks[$key];
3378 $searchkey = "<!--LINK $key-->";
3379 $title = $this->mLinkHolders['titles'][$key];
3380 if ( empty( $colours[$pdbk] ) ) {
3381 $wgLinkCache->addBadLinkObj( $title );
3382 $colours[$pdbk] = 0;
3383 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3384 $this->mLinkHolders['texts'][$key],
3385 $this->mLinkHolders['queries'][$key] );
3386 } elseif ( $colours[$pdbk] == 1 ) {
3387 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3388 $this->mLinkHolders['texts'][$key],
3389 $this->mLinkHolders['queries'][$key] );
3390 } elseif ( $colours[$pdbk] == 2 ) {
3391 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3392 $this->mLinkHolders['texts'][$key],
3393 $this->mLinkHolders['queries'][$key] );
3394 }
3395 }
3396 wfProfileOut( $fname.'-construct' );
3397
3398 # Do the thing
3399 wfProfileIn( $fname.'-replace' );
3400
3401 $text = preg_replace_callback(
3402 '/(<!--LINK .*?-->)/',
3403 "wfOutputReplaceMatches",
3404 $text);
3405
3406 wfProfileOut( $fname.'-replace' );
3407 }
3408
3409 # Now process interwiki link holders
3410 # This is quite a bit simpler than internal links
3411 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3412 wfProfileIn( $fname.'-interwiki' );
3413 # Make interwiki link HTML
3414 $wgOutputReplace = array();
3415 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3416 $title = $this->mInterwikiLinkHolders['titles'][$key];
3417 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3418 }
3419
3420 $text = preg_replace_callback(
3421 '/<!--IWLINK (.*?)-->/',
3422 "wfOutputReplaceMatches",
3423 $text );
3424 wfProfileOut( $fname.'-interwiki' );
3425 }
3426
3427 wfProfileOut( $fname );
3428 return $colours;
3429 }
3430
3431 /**
3432 * Replace <!--LINK--> link placeholders with plain text of links
3433 * (not HTML-formatted).
3434 * @param string $text
3435 * @return string
3436 */
3437 function replaceLinkHoldersText( $text ) {
3438 global $wgUser, $wgLinkCache;
3439 global $wgOutputReplace;
3440
3441 $fname = 'Parser::replaceLinkHoldersText';
3442 wfProfileIn( $fname );
3443
3444 $text = preg_replace_callback(
3445 '/<!--(LINK|IWLINK) (.*?)-->/',
3446 array( &$this, 'replaceLinkHoldersTextCallback' ),
3447 $text );
3448
3449 wfProfileOut( $fname );
3450 return $text;
3451 }
3452
3453 /**
3454 * @param array $matches
3455 * @return string
3456 * @access private
3457 */
3458 function replaceLinkHoldersTextCallback( $matches ) {
3459 $type = $matches[1];
3460 $key = $matches[2];
3461 if( $type == 'LINK' ) {
3462 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3463 return $this->mLinkHolders['texts'][$key];
3464 }
3465 } elseif( $type == 'IWLINK' ) {
3466 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3467 return $this->mInterwikiLinkHolders['texts'][$key];
3468 }
3469 }
3470 return $matches[0];
3471 }
3472
3473 /**
3474 * Renders an image gallery from a text with one line per image.
3475 * text labels may be given by using |-style alternative text. E.g.
3476 * Image:one.jpg|The number "1"
3477 * Image:tree.jpg|A tree
3478 * given as text will return the HTML of a gallery with two images,
3479 * labeled 'The number "1"' and
3480 * 'A tree'.
3481 *
3482 * @static
3483 */
3484 function renderImageGallery( $text ) {
3485 # Setup the parser
3486 global $wgUser, $wgTitle;
3487 $parserOptions = ParserOptions::newFromUser( $wgUser );
3488 $localParser = new Parser();
3489
3490 global $wgLinkCache;
3491 $ig = new ImageGallery();
3492 $ig->setShowBytes( false );
3493 $ig->setShowFilename( false );
3494 $lines = explode( "\n", $text );
3495
3496 foreach ( $lines as $line ) {
3497 # match lines like these:
3498 # Image:someimage.jpg|This is some image
3499 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3500 # Skip empty lines
3501 if ( count( $matches ) == 0 ) {
3502 continue;
3503 }
3504 $nt = Title::newFromURL( $matches[1] );
3505 if( is_null( $nt ) ) {
3506 # Bogus title. Ignore these so we don't bomb out later.
3507 continue;
3508 }
3509 if ( isset( $matches[3] ) ) {
3510 $label = $matches[3];
3511 } else {
3512 $label = '';
3513 }
3514
3515 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3516 $html = $html->mText;
3517
3518 $ig->add( new Image( $nt ), $html );
3519 $wgLinkCache->addImageLinkObj( $nt );
3520 }
3521 return $ig->toHTML();
3522 }
3523
3524 /**
3525 * Parse image options text and use it to make an image
3526 */
3527 function makeImage( &$nt, $options ) {
3528 global $wgContLang, $wgUseImageResize;
3529 global $wgUser, $wgThumbLimits;
3530
3531 $align = '';
3532
3533 # Check if the options text is of the form "options|alt text"
3534 # Options are:
3535 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3536 # * left no resizing, just left align. label is used for alt= only
3537 # * right same, but right aligned
3538 # * none same, but not aligned
3539 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3540 # * center center the image
3541 # * framed Keep original image size, no magnify-button.
3542
3543 $part = explode( '|', $options);
3544
3545 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3546 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
3547 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3548 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3549 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3550 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3551 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3552 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3553 $caption = '';
3554
3555 $width = $height = $framed = $thumb = false;
3556 $manual_thumb = '' ;
3557
3558 foreach( $part as $key => $val ) {
3559 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3560 $thumb=true;
3561 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3562 # use manually specified thumbnail
3563 $thumb=true;
3564 $manual_thumb = $match;
3565 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3566 # remember to set an alignment, don't render immediately
3567 $align = 'right';
3568 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3569 # remember to set an alignment, don't render immediately
3570 $align = 'left';
3571 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3572 # remember to set an alignment, don't render immediately
3573 $align = 'center';
3574 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3575 # remember to set an alignment, don't render immediately
3576 $align = 'none';
3577 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3578 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3579 # $match is the image width in pixels
3580 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3581 $width = intval( $m[1] );
3582 $height = intval( $m[2] );
3583 } else {
3584 $width = intval($match);
3585 }
3586 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3587 $framed=true;
3588 } else {
3589 $caption = $val;
3590 }
3591 }
3592 # Strip bad stuff out of the alt text
3593 $alt = $this->replaceLinkHoldersText( $caption );
3594 $alt = Sanitizer::stripAllTags( $alt );
3595
3596 # Linker does the rest
3597 $sk =& $this->mOptions->getSkin();
3598 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3599 }
3600
3601 /**
3602 * Set a flag in the output object indicating that the content is dynamic and
3603 * shouldn't be cached.
3604 */
3605 function disableCache() {
3606 $this->mOutput->mCacheTime = -1;
3607 }
3608
3609 /**
3610 * Callback from the Sanitizer for expanding items found in HTML attribute
3611 * values, so they can be safely tested and escaped.
3612 * @param string $text
3613 * @param array $args
3614 * @return string
3615 * @access private
3616 */
3617 function attributeStripCallback( &$text, $args ) {
3618 $text = $this->replaceVariables( $text, $args );
3619 $text = $this->unstripForHTML( $text );
3620 return $text;
3621 }
3622
3623 function unstripForHTML( $text ) {
3624 $text = $this->unstrip( $text, $this->mStripState );
3625 $text = $this->unstripNoWiki( $text, $this->mStripState );
3626 return $text;
3627 }
3628 }
3629
3630 /**
3631 * @todo document
3632 * @package MediaWiki
3633 */
3634 class ParserOutput
3635 {
3636 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3637 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3638 var $mVersion; # Compatibility check
3639 var $mTitleText; # title text of the chosen language variant
3640
3641 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3642 $containsOldMagic = false, $titletext = '' )
3643 {
3644 $this->mText = $text;
3645 $this->mLanguageLinks = $languageLinks;
3646 $this->mCategoryLinks = $categoryLinks;
3647 $this->mContainsOldMagic = $containsOldMagic;
3648 $this->mCacheTime = '';
3649 $this->mVersion = MW_PARSER_VERSION;
3650 $this->mTitleText = $titletext;
3651 }
3652
3653 function getText() { return $this->mText; }
3654 function getLanguageLinks() { return $this->mLanguageLinks; }
3655 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
3656 function getCacheTime() { return $this->mCacheTime; }
3657 function getTitleText() { return $this->mTitleText; }
3658 function containsOldMagic() { return $this->mContainsOldMagic; }
3659 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3660 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3661 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
3662 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3663 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3664 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3665
3666 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
3667
3668 function merge( $other ) {
3669 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3670 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3671 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3672 }
3673
3674 /**
3675 * Return true if this cached output object predates the global or
3676 * per-article cache invalidation timestamps, or if it comes from
3677 * an incompatible older version.
3678 *
3679 * @param string $touched the affected article's last touched timestamp
3680 * @return bool
3681 * @access public
3682 */
3683 function expired( $touched ) {
3684 global $wgCacheEpoch;
3685 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3686 $this->getCacheTime() < $touched ||
3687 $this->getCacheTime() <= $wgCacheEpoch ||
3688 !isset( $this->mVersion ) ||
3689 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3690 }
3691 }
3692
3693 /**
3694 * Set options of the Parser
3695 * @todo document
3696 * @package MediaWiki
3697 */
3698 class ParserOptions
3699 {
3700 # All variables are private
3701 var $mUseTeX; # Use texvc to expand <math> tags
3702 var $mUseDynamicDates; # Use DateFormatter to format dates
3703 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3704 var $mAllowExternalImages; # Allow external images inline
3705 var $mAllowExternalImagesFrom; # If not, any exception?
3706 var $mSkin; # Reference to the preferred skin
3707 var $mDateFormat; # Date format index
3708 var $mEditSection; # Create "edit section" links
3709 var $mNumberHeadings; # Automatically number headings
3710 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3711
3712 function getUseTeX() { return $this->mUseTeX; }
3713 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3714 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3715 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3716 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
3717 function &getSkin() { return $this->mSkin; }
3718 function getDateFormat() { return $this->mDateFormat; }
3719 function getEditSection() { return $this->mEditSection; }
3720 function getNumberHeadings() { return $this->mNumberHeadings; }
3721 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3722
3723
3724 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3725 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3726 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3727 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3728 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
3729 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3730 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3731 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3732 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3733
3734 function setSkin( &$x ) { $this->mSkin =& $x; }
3735
3736 function ParserOptions() {
3737 global $wgUser;
3738 $this->initialiseFromUser( $wgUser );
3739 }
3740
3741 /**
3742 * Get parser options
3743 * @static
3744 */
3745 function newFromUser( &$user ) {
3746 $popts = new ParserOptions;
3747 $popts->initialiseFromUser( $user );
3748 return $popts;
3749 }
3750
3751 /** Get user options */
3752 function initialiseFromUser( &$userInput ) {
3753 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3754 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3755 $fname = 'ParserOptions::initialiseFromUser';
3756 wfProfileIn( $fname );
3757 if ( !$userInput ) {
3758 $user = new User;
3759 $user->setLoaded( true );
3760 } else {
3761 $user =& $userInput;
3762 }
3763
3764 $this->mUseTeX = $wgUseTeX;
3765 $this->mUseDynamicDates = $wgUseDynamicDates;
3766 $this->mInterwikiMagic = $wgInterwikiMagic;
3767 $this->mAllowExternalImages = $wgAllowExternalImages;
3768 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
3769 wfProfileIn( $fname.'-skin' );
3770 $this->mSkin =& $user->getSkin();
3771 wfProfileOut( $fname.'-skin' );
3772 $this->mDateFormat = $user->getOption( 'date' );
3773 $this->mEditSection = true;
3774 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3775 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
3776 wfProfileOut( $fname );
3777 }
3778 }
3779
3780 /**
3781 * Callback function used by Parser::replaceLinkHolders()
3782 * to substitute link placeholders.
3783 */
3784 function &wfOutputReplaceMatches( $matches ) {
3785 global $wgOutputReplace;
3786 return $wgOutputReplace[$matches[1]];
3787 }
3788
3789 /**
3790 * Return the total number of articles
3791 */
3792 function wfNumberOfArticles() {
3793 global $wgNumberOfArticles;
3794
3795 wfLoadSiteStats();
3796 return $wgNumberOfArticles;
3797 }
3798
3799 /**
3800 * Return the number of files
3801 */
3802 function wfNumberOfFiles() {
3803 $fname = 'Parser::wfNumberOfFiles';
3804
3805 wfProfileIn( $fname );
3806 $dbr =& wfGetDB( DB_SLAVE );
3807 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3808 wfProfileOut( $fname );
3809
3810 return $res;
3811 }
3812
3813 /**
3814 * Get various statistics from the database
3815 * @private
3816 */
3817 function wfLoadSiteStats() {
3818 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3819 $fname = 'wfLoadSiteStats';
3820
3821 if ( -1 != $wgNumberOfArticles ) return;
3822 $dbr =& wfGetDB( DB_SLAVE );
3823 $s = $dbr->selectRow( 'site_stats',
3824 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3825 array( 'ss_row_id' => 1 ), $fname
3826 );
3827
3828 if ( $s === false ) {
3829 return;
3830 } else {
3831 $wgTotalViews = $s->ss_total_views;
3832 $wgTotalEdits = $s->ss_total_edits;
3833 $wgNumberOfArticles = $s->ss_good_articles;
3834 }
3835 }
3836
3837 /**
3838 * Escape html tags
3839 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3840 *
3841 * @param string $in Text that might contain HTML tags
3842 * @return string Escaped string
3843 */
3844 function wfEscapeHTMLTagsOnly( $in ) {
3845 return str_replace(
3846 array( '"', '>', '<' ),
3847 array( '&quot;', '&gt;', '&lt;' ),
3848 $in );
3849 }
3850
3851 ?>