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