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