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