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