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