* Adding a hook to Parser::clearState() (ParserClearState)
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2 /**
3 * File for Parser and related classes
4 *
5 * @package MediaWiki
6 * @subpackage Parser
7 */
8
9 /** */
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
12
13 /**
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
17 */
18 define( 'MW_PARSER_VERSION', '1.5.0' );
19
20 /**
21 * Variable substitution O(N^2) attack
22 *
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
28 */
29
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32
33 define( 'RLH_FOR_UPDATE', 1 );
34
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
39
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
50 # Including space
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
59 );
60
61 /**
62 * PHP Parser
63 *
64 * Processes wiki markup
65 *
66 * <pre>
67 * There are three main entry points into the Parser class:
68 * parse()
69 * produces HTML output
70 * preSaveTransform().
71 * produces altered wiki markup.
72 * transformMsg()
73 * performs brace substitution on MediaWiki messages
74 *
75 * Globals used:
76 * objects: $wgLang, $wgLinkCache
77 *
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
79 *
80 * settings:
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
84 *
85 * * only within ParserOptions
86 * </pre>
87 *
88 * @package MediaWiki
89 */
90 class Parser
91 {
92 /**#@+
93 * @access private
94 */
95 # Persistent:
96 var $mTagHooks;
97
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102
103 # Temporary:
104 var $mOptions, $mTitle, $mOutputType,
105 $mTemplates, // cache of already loaded templates, avoids
106 // multiple SQL queries for the same string
107 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
108 // in this path. Used for loop detection.
109
110 var $mIWTransData = array();
111
112 /**#@-*/
113
114 /**
115 * Constructor
116 *
117 * @access public
118 */
119 function Parser() {
120 $this->mTemplates = array();
121 $this->mTemplatePath = array();
122 $this->mTagHooks = array();
123 $this->clearState();
124 }
125
126 /**
127 * Clear Parser state
128 *
129 * @access private
130 */
131 function clearState() {
132 $this->mOutput = new ParserOutput;
133 $this->mAutonumber = 0;
134 $this->mLastSection = '';
135 $this->mDTopen = false;
136 $this->mVariables = false;
137 $this->mIncludeCount = array();
138 $this->mStripState = array();
139 $this->mArgStack = array();
140 $this->mInPre = false;
141 $this->mInterwikiLinkHolders = array(
142 'texts' => array(),
143 'titles' => array()
144 );
145 $this->mLinkHolders = array(
146 'namespaces' => array(),
147 'dbkeys' => array(),
148 'queries' => array(),
149 'texts' => array(),
150 'titles' => array()
151 );
152 $this->mRevisionId = null;
153 $this->mUniqPrefix = 'UNIQ' . Parser::getRandomString();
154
155 wfRunHooks( 'ParserClearState', array( &$this ) );
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 = $this->mUniqPrefix;
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 = $this->mUniqPrefix . '-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($this->mUniqPrefix."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() . ')/', "{$this->mUniqPrefix}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 $link = $sk->makeMediaLinkObj( $nt, $text );
1467 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1468 $s .= $prefix . str_replace( 'http://', "http{$this->mUniqPrefix}NOPARSE://", $link ) . $trail;
1469 $wgLinkCache->addImageLinkObj( $nt );
1470 continue;
1471 } elseif( $ns == NS_SPECIAL ) {
1472 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1473 continue;
1474 } elseif( $ns == NS_IMAGE ) {
1475 $img = Image::newFromTitle( $nt );
1476 if( $img->exists() ) {
1477 // Force a blue link if the file exists; may be a remote
1478 // upload on the shared repository, and we want to see its
1479 // auto-generated page.
1480 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1481 continue;
1482 }
1483 }
1484 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1485 }
1486 wfProfileOut( $fname );
1487 return $s;
1488 }
1489
1490 /**
1491 * Make a link placeholder. The text returned can be later resolved to a real link with
1492 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1493 * parsing of interwiki links, and secondly to allow all extistence checks and
1494 * article length checks (for stub links) to be bundled into a single query.
1495 *
1496 */
1497 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1498 if ( ! is_object($nt) ) {
1499 # Fail gracefully
1500 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1501 } else {
1502 # Separate the link trail from the rest of the link
1503 list( $inside, $trail ) = Linker::splitTrail( $trail );
1504
1505 if ( $nt->isExternal() ) {
1506 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1507 $this->mInterwikiLinkHolders['titles'][] = $nt;
1508 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1509 } else {
1510 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1511 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1512 $this->mLinkHolders['queries'][] = $query;
1513 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1514 $this->mLinkHolders['titles'][] = $nt;
1515
1516 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1517 }
1518 }
1519 return $retVal;
1520 }
1521
1522 /**
1523 * Return true if subpage links should be expanded on this page.
1524 * @return bool
1525 */
1526 function areSubpagesAllowed() {
1527 # Some namespaces don't allow subpages
1528 global $wgNamespacesWithSubpages;
1529 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1530 }
1531
1532 /**
1533 * Handle link to subpage if necessary
1534 * @param string $target the source of the link
1535 * @param string &$text the link text, modified as necessary
1536 * @return string the full name of the link
1537 * @access private
1538 */
1539 function maybeDoSubpageLink($target, &$text) {
1540 # Valid link forms:
1541 # Foobar -- normal
1542 # :Foobar -- override special treatment of prefix (images, language links)
1543 # /Foobar -- convert to CurrentPage/Foobar
1544 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1545 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1546 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1547
1548 $fname = 'Parser::maybeDoSubpageLink';
1549 wfProfileIn( $fname );
1550 $ret = $target; # default return value is no change
1551
1552 # Some namespaces don't allow subpages,
1553 # so only perform processing if subpages are allowed
1554 if( $this->areSubpagesAllowed() ) {
1555 # Look at the first character
1556 if( $target != '' && $target{0} == '/' ) {
1557 # / at end means we don't want the slash to be shown
1558 if( substr( $target, -1, 1 ) == '/' ) {
1559 $target = substr( $target, 1, -1 );
1560 $noslash = $target;
1561 } else {
1562 $noslash = substr( $target, 1 );
1563 }
1564
1565 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1566 if( '' === $text ) {
1567 $text = $target;
1568 } # this might be changed for ugliness reasons
1569 } else {
1570 # check for .. subpage backlinks
1571 $dotdotcount = 0;
1572 $nodotdot = $target;
1573 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1574 ++$dotdotcount;
1575 $nodotdot = substr( $nodotdot, 3 );
1576 }
1577 if($dotdotcount > 0) {
1578 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1579 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1580 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1581 # / at the end means don't show full path
1582 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1583 $nodotdot = substr( $nodotdot, 0, -1 );
1584 if( '' === $text ) {
1585 $text = $nodotdot;
1586 }
1587 }
1588 $nodotdot = trim( $nodotdot );
1589 if( $nodotdot != '' ) {
1590 $ret .= '/' . $nodotdot;
1591 }
1592 }
1593 }
1594 }
1595 }
1596
1597 wfProfileOut( $fname );
1598 return $ret;
1599 }
1600
1601 /**#@+
1602 * Used by doBlockLevels()
1603 * @access private
1604 */
1605 /* private */ function closeParagraph() {
1606 $result = '';
1607 if ( '' != $this->mLastSection ) {
1608 $result = '</' . $this->mLastSection . ">\n";
1609 }
1610 $this->mInPre = false;
1611 $this->mLastSection = '';
1612 return $result;
1613 }
1614 # getCommon() returns the length of the longest common substring
1615 # of both arguments, starting at the beginning of both.
1616 #
1617 /* private */ function getCommon( $st1, $st2 ) {
1618 $fl = strlen( $st1 );
1619 $shorter = strlen( $st2 );
1620 if ( $fl < $shorter ) { $shorter = $fl; }
1621
1622 for ( $i = 0; $i < $shorter; ++$i ) {
1623 if ( $st1{$i} != $st2{$i} ) { break; }
1624 }
1625 return $i;
1626 }
1627 # These next three functions open, continue, and close the list
1628 # element appropriate to the prefix character passed into them.
1629 #
1630 /* private */ function openList( $char ) {
1631 $result = $this->closeParagraph();
1632
1633 if ( '*' == $char ) { $result .= '<ul><li>'; }
1634 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1635 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1636 else if ( ';' == $char ) {
1637 $result .= '<dl><dt>';
1638 $this->mDTopen = true;
1639 }
1640 else { $result = '<!-- ERR 1 -->'; }
1641
1642 return $result;
1643 }
1644
1645 /* private */ function nextItem( $char ) {
1646 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1647 else if ( ':' == $char || ';' == $char ) {
1648 $close = '</dd>';
1649 if ( $this->mDTopen ) { $close = '</dt>'; }
1650 if ( ';' == $char ) {
1651 $this->mDTopen = true;
1652 return $close . '<dt>';
1653 } else {
1654 $this->mDTopen = false;
1655 return $close . '<dd>';
1656 }
1657 }
1658 return '<!-- ERR 2 -->';
1659 }
1660
1661 /* private */ function closeList( $char ) {
1662 if ( '*' == $char ) { $text = '</li></ul>'; }
1663 else if ( '#' == $char ) { $text = '</li></ol>'; }
1664 else if ( ':' == $char ) {
1665 if ( $this->mDTopen ) {
1666 $this->mDTopen = false;
1667 $text = '</dt></dl>';
1668 } else {
1669 $text = '</dd></dl>';
1670 }
1671 }
1672 else { return '<!-- ERR 3 -->'; }
1673 return $text."\n";
1674 }
1675 /**#@-*/
1676
1677 /**
1678 * Make lists from lines starting with ':', '*', '#', etc.
1679 *
1680 * @access private
1681 * @return string the lists rendered as HTML
1682 */
1683 function doBlockLevels( $text, $linestart ) {
1684 $fname = 'Parser::doBlockLevels';
1685 wfProfileIn( $fname );
1686
1687 # Parsing through the text line by line. The main thing
1688 # happening here is handling of block-level elements p, pre,
1689 # and making lists from lines starting with * # : etc.
1690 #
1691 $textLines = explode( "\n", $text );
1692
1693 $lastPrefix = $output = '';
1694 $this->mDTopen = $inBlockElem = false;
1695 $prefixLength = 0;
1696 $paragraphStack = false;
1697
1698 if ( !$linestart ) {
1699 $output .= array_shift( $textLines );
1700 }
1701 foreach ( $textLines as $oLine ) {
1702 $lastPrefixLength = strlen( $lastPrefix );
1703 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1704 $preOpenMatch = preg_match('/<pre/i', $oLine );
1705 if ( !$this->mInPre ) {
1706 # Multiple prefixes may abut each other for nested lists.
1707 $prefixLength = strspn( $oLine, '*#:;' );
1708 $pref = substr( $oLine, 0, $prefixLength );
1709
1710 # eh?
1711 $pref2 = str_replace( ';', ':', $pref );
1712 $t = substr( $oLine, $prefixLength );
1713 $this->mInPre = !empty($preOpenMatch);
1714 } else {
1715 # Don't interpret any other prefixes in preformatted text
1716 $prefixLength = 0;
1717 $pref = $pref2 = '';
1718 $t = $oLine;
1719 }
1720
1721 # List generation
1722 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1723 # Same as the last item, so no need to deal with nesting or opening stuff
1724 $output .= $this->nextItem( substr( $pref, -1 ) );
1725 $paragraphStack = false;
1726
1727 if ( substr( $pref, -1 ) == ';') {
1728 # The one nasty exception: definition lists work like this:
1729 # ; title : definition text
1730 # So we check for : in the remainder text to split up the
1731 # title and definition, without b0rking links.
1732 $term = $t2 = '';
1733 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1734 $t = $t2;
1735 $output .= $term . $this->nextItem( ':' );
1736 }
1737 }
1738 } elseif( $prefixLength || $lastPrefixLength ) {
1739 # Either open or close a level...
1740 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1741 $paragraphStack = false;
1742
1743 while( $commonPrefixLength < $lastPrefixLength ) {
1744 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1745 --$lastPrefixLength;
1746 }
1747 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1748 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1749 }
1750 while ( $prefixLength > $commonPrefixLength ) {
1751 $char = substr( $pref, $commonPrefixLength, 1 );
1752 $output .= $this->openList( $char );
1753
1754 if ( ';' == $char ) {
1755 # FIXME: This is dupe of code above
1756 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1757 $t = $t2;
1758 $output .= $term . $this->nextItem( ':' );
1759 }
1760 }
1761 ++$commonPrefixLength;
1762 }
1763 $lastPrefix = $pref2;
1764 }
1765 if( 0 == $prefixLength ) {
1766 wfProfileIn( "$fname-paragraph" );
1767 # No prefix (not in list)--go to paragraph mode
1768 // XXX: use a stack for nestable elements like span, table and div
1769 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1770 $closematch = preg_match(
1771 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1772 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1773 if ( $openmatch or $closematch ) {
1774 $paragraphStack = false;
1775 $output .= $this->closeParagraph();
1776 if ( $preOpenMatch and !$preCloseMatch ) {
1777 $this->mInPre = true;
1778 }
1779 if ( $closematch ) {
1780 $inBlockElem = false;
1781 } else {
1782 $inBlockElem = true;
1783 }
1784 } else if ( !$inBlockElem && !$this->mInPre ) {
1785 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1786 // pre
1787 if ($this->mLastSection != 'pre') {
1788 $paragraphStack = false;
1789 $output .= $this->closeParagraph().'<pre>';
1790 $this->mLastSection = 'pre';
1791 }
1792 $t = substr( $t, 1 );
1793 } else {
1794 // paragraph
1795 if ( '' == trim($t) ) {
1796 if ( $paragraphStack ) {
1797 $output .= $paragraphStack.'<br />';
1798 $paragraphStack = false;
1799 $this->mLastSection = 'p';
1800 } else {
1801 if ($this->mLastSection != 'p' ) {
1802 $output .= $this->closeParagraph();
1803 $this->mLastSection = '';
1804 $paragraphStack = '<p>';
1805 } else {
1806 $paragraphStack = '</p><p>';
1807 }
1808 }
1809 } else {
1810 if ( $paragraphStack ) {
1811 $output .= $paragraphStack;
1812 $paragraphStack = false;
1813 $this->mLastSection = 'p';
1814 } else if ($this->mLastSection != 'p') {
1815 $output .= $this->closeParagraph().'<p>';
1816 $this->mLastSection = 'p';
1817 }
1818 }
1819 }
1820 }
1821 wfProfileOut( "$fname-paragraph" );
1822 }
1823 // somewhere above we forget to get out of pre block (bug 785)
1824 if($preCloseMatch && $this->mInPre) {
1825 $this->mInPre = false;
1826 }
1827 if ($paragraphStack === false) {
1828 $output .= $t."\n";
1829 }
1830 }
1831 while ( $prefixLength ) {
1832 $output .= $this->closeList( $pref2{$prefixLength-1} );
1833 --$prefixLength;
1834 }
1835 if ( '' != $this->mLastSection ) {
1836 $output .= '</' . $this->mLastSection . '>';
1837 $this->mLastSection = '';
1838 }
1839
1840 wfProfileOut( $fname );
1841 return $output;
1842 }
1843
1844 /**
1845 * Split up a string on ':', ignoring any occurences inside
1846 * <a>..</a> or <span>...</span>
1847 * @param string $str the string to split
1848 * @param string &$before set to everything before the ':'
1849 * @param string &$after set to everything after the ':'
1850 * return string the position of the ':', or false if none found
1851 */
1852 function findColonNoLinks($str, &$before, &$after) {
1853 # I wonder if we should make this count all tags, not just <a>
1854 # and <span>. That would prevent us from matching a ':' that
1855 # comes in the middle of italics other such formatting....
1856 # -- Wil
1857 $fname = 'Parser::findColonNoLinks';
1858 wfProfileIn( $fname );
1859 $pos = 0;
1860 do {
1861 $colon = strpos($str, ':', $pos);
1862
1863 if ($colon !== false) {
1864 $before = substr($str, 0, $colon);
1865 $after = substr($str, $colon + 1);
1866
1867 # Skip any ':' within <a> or <span> pairs
1868 $a = substr_count($before, '<a');
1869 $s = substr_count($before, '<span');
1870 $ca = substr_count($before, '</a>');
1871 $cs = substr_count($before, '</span>');
1872
1873 if ($a <= $ca and $s <= $cs) {
1874 # Tags are balanced before ':'; ok
1875 break;
1876 }
1877 $pos = $colon + 1;
1878 }
1879 } while ($colon !== false);
1880 wfProfileOut( $fname );
1881 return $colon;
1882 }
1883
1884 /**
1885 * Return value of a magic variable (like PAGENAME)
1886 *
1887 * @access private
1888 */
1889 function getVariableValue( $index ) {
1890 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1891
1892 /**
1893 * Some of these require message or data lookups and can be
1894 * expensive to check many times.
1895 */
1896 static $varCache = array();
1897 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1898 if ( isset( $varCache[$index] ) )
1899 return $varCache[$index];
1900
1901 $ts = time();
1902 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1903
1904 switch ( $index ) {
1905 case MAG_CURRENTMONTH:
1906 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1907 case MAG_CURRENTMONTHNAME:
1908 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
1909 case MAG_CURRENTMONTHNAMEGEN:
1910 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
1911 case MAG_CURRENTMONTHABBREV:
1912 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
1913 case MAG_CURRENTDAY:
1914 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
1915 case MAG_PAGENAME:
1916 return $this->mTitle->getText();
1917 case MAG_PAGENAMEE:
1918 return $this->mTitle->getPartialURL();
1919 case MAG_FULLPAGENAME:
1920 return $this->mTitle->getPrefixedText();
1921 case MAG_FULLPAGENAMEE:
1922 return wfUrlencode( $this->mTitle->getPrefixedText() );
1923 case MAG_REVISIONID:
1924 return $this->mRevisionId;
1925 case MAG_NAMESPACE:
1926 return $wgContLang->getNsText( $this->mTitle->getNamespace() );
1927 case MAG_NAMESPACEE:
1928 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
1929 case MAG_CURRENTDAYNAME:
1930 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
1931 case MAG_CURRENTYEAR:
1932 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
1933 case MAG_CURRENTTIME:
1934 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
1935 case MAG_CURRENTWEEK:
1936 return $varCache[$index] = $wgContLang->formatNum( date( 'W', $ts ) );
1937 case MAG_CURRENTDOW:
1938 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
1939 case MAG_NUMBEROFARTICLES:
1940 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1941 case MAG_NUMBEROFFILES:
1942 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
1943 case MAG_SITENAME:
1944 return $wgSitename;
1945 case MAG_SERVER:
1946 return $wgServer;
1947 case MAG_SERVERNAME:
1948 return $wgServerName;
1949 case MAG_SCRIPTPATH:
1950 return $wgScriptPath;
1951 default:
1952 $ret = null;
1953 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
1954 return $ret;
1955 else
1956 return null;
1957 }
1958 }
1959
1960 /**
1961 * initialise the magic variables (like CURRENTMONTHNAME)
1962 *
1963 * @access private
1964 */
1965 function initialiseVariables() {
1966 $fname = 'Parser::initialiseVariables';
1967 wfProfileIn( $fname );
1968 global $wgVariableIDs;
1969 $this->mVariables = array();
1970 foreach ( $wgVariableIDs as $id ) {
1971 $mw =& MagicWord::get( $id );
1972 $mw->addToArray( $this->mVariables, $id );
1973 }
1974 wfProfileOut( $fname );
1975 }
1976
1977 /**
1978 * parse any parentheses in format ((title|part|part))
1979 * and call callbacks to get a replacement text for any found piece
1980 *
1981 * @param string $text The text to parse
1982 * @param array $callbacks rules in form:
1983 * '{' => array( # opening parentheses
1984 * 'end' => '}', # closing parentheses
1985 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
1986 * 4 => callback # replacement callback to call if {{{{..}}}} is found
1987 * )
1988 * )
1989 * @access private
1990 */
1991 function replace_callback ($text, $callbacks) {
1992 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
1993 $lastOpeningBrace = -1; # last not closed parentheses
1994
1995 for ($i = 0; $i < strlen($text); $i++) {
1996 # check for any opening brace
1997 $rule = null;
1998 $nextPos = -1;
1999 foreach ($callbacks as $key => $value) {
2000 $pos = strpos ($text, $key, $i);
2001 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
2002 $rule = $value;
2003 $nextPos = $pos;
2004 }
2005 }
2006
2007 if ($lastOpeningBrace >= 0) {
2008 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2009
2010 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2011 $rule = null;
2012 $nextPos = $pos;
2013 }
2014
2015 $pos = strpos ($text, '|', $i);
2016
2017 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2018 $rule = null;
2019 $nextPos = $pos;
2020 }
2021 }
2022
2023 if ($nextPos == -1)
2024 break;
2025
2026 $i = $nextPos;
2027
2028 # found openning brace, lets add it to parentheses stack
2029 if (null != $rule) {
2030 $piece = array('brace' => $text[$i],
2031 'braceEnd' => $rule['end'],
2032 'count' => 1,
2033 'title' => '',
2034 'parts' => null);
2035
2036 # count openning brace characters
2037 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2038 $piece['count']++;
2039 $i++;
2040 }
2041
2042 $piece['startAt'] = $i+1;
2043 $piece['partStart'] = $i+1;
2044
2045 # we need to add to stack only if openning brace count is enough for any given rule
2046 foreach ($rule['cb'] as $cnt => $fn) {
2047 if ($piece['count'] >= $cnt) {
2048 $lastOpeningBrace ++;
2049 $openingBraceStack[$lastOpeningBrace] = $piece;
2050 break;
2051 }
2052 }
2053
2054 continue;
2055 }
2056 else if ($lastOpeningBrace >= 0) {
2057 # first check if it is a closing brace
2058 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2059 # lets check if it is enough characters for closing brace
2060 $count = 1;
2061 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2062 $count++;
2063
2064 # if there are more closing parentheses than opening ones, we parse less
2065 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2066 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2067
2068 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2069 $matchingCount = 0;
2070 $matchingCallback = null;
2071 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2072 if ($count >= $cnt && $matchingCount < $cnt) {
2073 $matchingCount = $cnt;
2074 $matchingCallback = $fn;
2075 }
2076 }
2077
2078 if ($matchingCount == 0) {
2079 $i += $count - 1;
2080 continue;
2081 }
2082
2083 # lets set a title or last part (if '|' was found)
2084 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2085 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2086 else
2087 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2088
2089 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2090 $pieceEnd = $i + $matchingCount;
2091
2092 if( is_callable( $matchingCallback ) ) {
2093 $cbArgs = array (
2094 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2095 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2096 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2097 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2098 );
2099 # finally we can call a user callback and replace piece of text
2100 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2101 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2102 $i = $pieceStart + strlen($replaceWith) - 1;
2103 }
2104 else {
2105 # null value for callback means that parentheses should be parsed, but not replaced
2106 $i += $matchingCount - 1;
2107 }
2108
2109 # reset last openning parentheses, but keep it in case there are unused characters
2110 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2111 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2112 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2113 'title' => '',
2114 'parts' => null,
2115 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2116 $openingBraceStack[$lastOpeningBrace--] = null;
2117
2118 if ($matchingCount < $piece['count']) {
2119 $piece['count'] -= $matchingCount;
2120 $piece['startAt'] -= $matchingCount;
2121 $piece['partStart'] = $piece['startAt'];
2122 # do we still qualify for any callback with remaining count?
2123 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2124 if ($piece['count'] >= $cnt) {
2125 $lastOpeningBrace ++;
2126 $openingBraceStack[$lastOpeningBrace] = $piece;
2127 break;
2128 }
2129 }
2130 }
2131 continue;
2132 }
2133
2134 # lets set a title if it is a first separator, or next part otherwise
2135 if ($text[$i] == '|') {
2136 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2137 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2138 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2139 }
2140 else
2141 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2142
2143 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2144 }
2145 }
2146 }
2147
2148 return $text;
2149 }
2150
2151 /**
2152 * Replace magic variables, templates, and template arguments
2153 * with the appropriate text. Templates are substituted recursively,
2154 * taking care to avoid infinite loops.
2155 *
2156 * Note that the substitution depends on value of $mOutputType:
2157 * OT_WIKI: only {{subst:}} templates
2158 * OT_MSG: only magic variables
2159 * OT_HTML: all templates and magic variables
2160 *
2161 * @param string $tex The text to transform
2162 * @param array $args Key-value pairs representing template parameters to substitute
2163 * @access private
2164 */
2165 function replaceVariables( $text, $args = array() ) {
2166 # Prevent too big inclusions
2167 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2168 return $text;
2169 }
2170
2171 $fname = 'Parser::replaceVariables';
2172 wfProfileIn( $fname );
2173
2174 # This function is called recursively. To keep track of arguments we need a stack:
2175 array_push( $this->mArgStack, $args );
2176
2177 $braceCallbacks = array();
2178 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2179 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2180 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2181 }
2182 $callbacks = array();
2183 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2184 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2185 $text = $this->replace_callback ($text, $callbacks);
2186
2187 array_pop( $this->mArgStack );
2188
2189 wfProfileOut( $fname );
2190 return $text;
2191 }
2192
2193 /**
2194 * Replace magic variables
2195 * @access private
2196 */
2197 function variableSubstitution( $matches ) {
2198 $fname = 'parser::variableSubstitution';
2199 $varname = $matches[1];
2200 wfProfileIn( $fname );
2201 if ( !$this->mVariables ) {
2202 $this->initialiseVariables();
2203 }
2204 $skip = false;
2205 if ( $this->mOutputType == OT_WIKI ) {
2206 # Do only magic variables prefixed by SUBST
2207 $mwSubst =& MagicWord::get( MAG_SUBST );
2208 if (!$mwSubst->matchStartAndRemove( $varname ))
2209 $skip = true;
2210 # Note that if we don't substitute the variable below,
2211 # we don't remove the {{subst:}} magic word, in case
2212 # it is a template rather than a magic variable.
2213 }
2214 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2215 $id = $this->mVariables[$varname];
2216 $text = $this->getVariableValue( $id );
2217 $this->mOutput->mContainsOldMagic = true;
2218 } else {
2219 $text = $matches[0];
2220 }
2221 wfProfileOut( $fname );
2222 return $text;
2223 }
2224
2225 # Split template arguments
2226 function getTemplateArgs( $argsString ) {
2227 if ( $argsString === '' ) {
2228 return array();
2229 }
2230
2231 $args = explode( '|', substr( $argsString, 1 ) );
2232
2233 # If any of the arguments contains a '[[' but no ']]', it needs to be
2234 # merged with the next arg because the '|' character between belongs
2235 # to the link syntax and not the template parameter syntax.
2236 $argc = count($args);
2237
2238 for ( $i = 0; $i < $argc-1; $i++ ) {
2239 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2240 $args[$i] .= '|'.$args[$i+1];
2241 array_splice($args, $i+1, 1);
2242 $i--;
2243 $argc--;
2244 }
2245 }
2246
2247 return $args;
2248 }
2249
2250 /**
2251 * Return the text of a template, after recursively
2252 * replacing any variables or templates within the template.
2253 *
2254 * @param array $piece The parts of the template
2255 * $piece['text']: matched text
2256 * $piece['title']: the title, i.e. the part before the |
2257 * $piece['parts']: the parameter array
2258 * @return string the text of the template
2259 * @access private
2260 */
2261 function braceSubstitution( $piece ) {
2262 global $wgLinkCache, $wgContLang;
2263 $fname = 'Parser::braceSubstitution';
2264 wfProfileIn( $fname );
2265
2266 $found = false;
2267 $nowiki = false;
2268 $noparse = false;
2269
2270 $title = NULL;
2271
2272 $linestart = '';
2273
2274 # $part1 is the bit before the first |, and must contain only title characters
2275 # $args is a list of arguments, starting from index 0, not including $part1
2276
2277 $part1 = $piece['title'];
2278 # If the third subpattern matched anything, it will start with |
2279
2280 if (null == $piece['parts']) {
2281 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2282 if ($replaceWith != $piece['text']) {
2283 $text = $replaceWith;
2284 $found = true;
2285 $noparse = true;
2286 }
2287 }
2288
2289 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2290 $argc = count( $args );
2291
2292 # SUBST
2293 if ( !$found ) {
2294 $mwSubst =& MagicWord::get( MAG_SUBST );
2295 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2296 # One of two possibilities is true:
2297 # 1) Found SUBST but not in the PST phase
2298 # 2) Didn't find SUBST and in the PST phase
2299 # In either case, return without further processing
2300 $text = $piece['text'];
2301 $found = true;
2302 $noparse = true;
2303 }
2304 }
2305
2306 # MSG, MSGNW and INT
2307 if ( !$found ) {
2308 # Check for MSGNW:
2309 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2310 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2311 $nowiki = true;
2312 } else {
2313 # Remove obsolete MSG:
2314 $mwMsg =& MagicWord::get( MAG_MSG );
2315 $mwMsg->matchStartAndRemove( $part1 );
2316 }
2317
2318 # Check if it is an internal message
2319 $mwInt =& MagicWord::get( MAG_INT );
2320 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2321 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2322 $text = $linestart . wfMsgReal( $part1, $args, true );
2323 $found = true;
2324 }
2325 }
2326 }
2327
2328 # NS
2329 if ( !$found ) {
2330 # Check for NS: (namespace expansion)
2331 $mwNs = MagicWord::get( MAG_NS );
2332 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2333 if ( intval( $part1 ) ) {
2334 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2335 $found = true;
2336 } else {
2337 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2338 if ( !is_null( $index ) ) {
2339 $text = $linestart . $wgContLang->getNsText( $index );
2340 $found = true;
2341 }
2342 }
2343 }
2344 }
2345
2346 # LCFIRST, UCFIRST, LC and UC
2347 if ( !$found ) {
2348 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2349 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2350 $lc =& MagicWord::get( MAG_LC );
2351 $uc =& MagicWord::get( MAG_UC );
2352 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2353 $text = $linestart . $wgContLang->lcfirst( $part1 );
2354 $found = true;
2355 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2356 $text = $linestart . $wgContLang->ucfirst( $part1 );
2357 $found = true;
2358 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2359 $text = $linestart . $wgContLang->lc( $part1 );
2360 $found = true;
2361 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2362 $text = $linestart . $wgContLang->uc( $part1 );
2363 $found = true;
2364 }
2365 }
2366
2367 # LOCALURL and FULLURL
2368 if ( !$found ) {
2369 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2370 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2371 $mwFull =& MagicWord::get( MAG_FULLURL );
2372 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2373
2374
2375 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2376 $func = 'getLocalURL';
2377 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2378 $func = 'escapeLocalURL';
2379 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2380 $func = 'getFullURL';
2381 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2382 $func = 'escapeFullURL';
2383 } else {
2384 $func = false;
2385 }
2386
2387 if ( $func !== false ) {
2388 $title = Title::newFromText( $part1 );
2389 if ( !is_null( $title ) ) {
2390 if ( $argc > 0 ) {
2391 $text = $linestart . $title->$func( $args[0] );
2392 } else {
2393 $text = $linestart . $title->$func();
2394 }
2395 $found = true;
2396 }
2397 }
2398 }
2399
2400 # GRAMMAR
2401 if ( !$found && $argc == 1 ) {
2402 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2403 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2404 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2405 $found = true;
2406 }
2407 }
2408
2409 # PLURAL
2410 if ( !$found && $argc >= 2 ) {
2411 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2412 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2413 if ($argc==2) {$args[2]=$args[1];}
2414 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2415 $found = true;
2416 }
2417 }
2418
2419 # Template table test
2420
2421 # Did we encounter this template already? If yes, it is in the cache
2422 # and we need to check for loops.
2423 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
2424 $found = true;
2425
2426 # Infinite loop test
2427 if ( isset( $this->mTemplatePath[$part1] ) ) {
2428 $noparse = true;
2429 $found = true;
2430 $text = $linestart .
2431 '{{' . $part1 . '}}' .
2432 '<!-- WARNING: template loop detected -->';
2433 wfDebug( "$fname: template loop broken at '$part1'\n" );
2434 } else {
2435 # set $text to cached message.
2436 $text = $linestart . $this->mTemplates[$part1];
2437 }
2438 }
2439
2440 # Load from database
2441 $replaceHeadings = false;
2442 $isHTML = false;
2443 $lastPathLevel = $this->mTemplatePath;
2444 if ( !$found ) {
2445 $ns = NS_TEMPLATE;
2446 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2447 if ($subpage !== '') {
2448 $ns = $this->mTitle->getNamespace();
2449 }
2450 $title = Title::newFromText( $part1, $ns );
2451
2452 if ($title) {
2453 $interwiki = Title::getInterwikiLink($title->getInterwiki());
2454 if ($interwiki != '' && $title->isTrans()) {
2455 return $this->scarytransclude($title, $interwiki);
2456 }
2457 }
2458
2459 if ( !is_null( $title ) && !$title->isExternal() ) {
2460 # Check for excessive inclusion
2461 $dbk = $title->getPrefixedDBkey();
2462 if ( $this->incrementIncludeCount( $dbk ) ) {
2463 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2464 # Capture special page output
2465 $text = SpecialPage::capturePath( $title );
2466 if ( is_string( $text ) ) {
2467 $found = true;
2468 $noparse = true;
2469 $isHTML = true;
2470 $this->disableCache();
2471 }
2472 } else {
2473 $article = new Article( $title );
2474 $articleContent = $article->fetchContent(0, false);
2475 if ( $articleContent !== false ) {
2476 $found = true;
2477 $text = $articleContent;
2478 $replaceHeadings = true;
2479 }
2480 }
2481 }
2482
2483 # If the title is valid but undisplayable, make a link to it
2484 if ( $this->mOutputType == OT_HTML && !$found ) {
2485 $text = '[['.$title->getPrefixedText().']]';
2486 $found = true;
2487 }
2488
2489 # Template cache array insertion
2490 if( $found ) {
2491 $this->mTemplates[$part1] = $text;
2492 $text = $linestart . $text;
2493 }
2494 }
2495 }
2496
2497 # Recursive parsing, escaping and link table handling
2498 # Only for HTML output
2499 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2500 $text = wfEscapeWikiText( $text );
2501 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2502 # Clean up argument array
2503 $assocArgs = array();
2504 $index = 1;
2505 foreach( $args as $arg ) {
2506 $eqpos = strpos( $arg, '=' );
2507 if ( $eqpos === false ) {
2508 $assocArgs[$index++] = $arg;
2509 } else {
2510 $name = trim( substr( $arg, 0, $eqpos ) );
2511 $value = trim( substr( $arg, $eqpos+1 ) );
2512 if ( $value === false ) {
2513 $value = '';
2514 }
2515 if ( $name !== false ) {
2516 $assocArgs[$name] = $value;
2517 }
2518 }
2519 }
2520
2521 # Add a new element to the templace recursion path
2522 $this->mTemplatePath[$part1] = 1;
2523
2524 # If there are any <onlyinclude> tags, only include them
2525 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2526 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2527 $text = '';
2528 foreach ($m[1] as $piece)
2529 $text .= $piece;
2530 }
2531 # Remove <noinclude> sections and <includeonly> tags
2532 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2533 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2534
2535 if( $this->mOutputType == OT_HTML ) {
2536 # Strip <nowiki>, <pre>, etc.
2537 $text = $this->strip( $text, $this->mStripState );
2538 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2539 }
2540 $text = $this->replaceVariables( $text, $assocArgs );
2541
2542 # Resume the link cache and register the inclusion as a link
2543 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2544 $wgLinkCache->addLinkObj( $title );
2545 }
2546
2547 # If the template begins with a table or block-level
2548 # element, it should be treated as beginning a new line.
2549 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2550 $text = "\n" . $text;
2551 }
2552 }
2553 # Prune lower levels off the recursion check path
2554 $this->mTemplatePath = $lastPathLevel;
2555
2556 if ( !$found ) {
2557 wfProfileOut( $fname );
2558 return $piece['text'];
2559 } else {
2560 if ( $isHTML ) {
2561 # Replace raw HTML by a placeholder
2562 # Add a blank line preceding, to prevent it from mucking up
2563 # immediately preceding headings
2564 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2565 } else {
2566 # replace ==section headers==
2567 # XXX this needs to go away once we have a better parser.
2568 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2569 if( !is_null( $title ) )
2570 $encodedname = base64_encode($title->getPrefixedDBkey());
2571 else
2572 $encodedname = base64_encode("");
2573 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2574 PREG_SPLIT_DELIM_CAPTURE);
2575 $text = '';
2576 $nsec = 0;
2577 for( $i = 0; $i < count($m); $i += 2 ) {
2578 $text .= $m[$i];
2579 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2580 $hl = $m[$i + 1];
2581 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2582 $text .= $hl;
2583 continue;
2584 }
2585 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2586 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2587 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2588
2589 $nsec++;
2590 }
2591 }
2592 }
2593 }
2594
2595 # Prune lower levels off the recursion check path
2596 $this->mTemplatePath = $lastPathLevel;
2597
2598 if ( !$found ) {
2599 wfProfileOut( $fname );
2600 return $piece['text'];
2601 } else {
2602 wfProfileOut( $fname );
2603 return $text;
2604 }
2605 }
2606
2607 /**
2608 * Translude an interwiki link.
2609 */
2610 function scarytransclude($title, $interwiki) {
2611 global $wgEnableScaryTranscluding;
2612
2613 if (!$wgEnableScaryTranscluding)
2614 return wfMsg('scarytranscludedisabled');
2615
2616 $articlename = "Template:" . $title->getDBkey();
2617 $url = str_replace('$1', urlencode($articlename), $interwiki);
2618 if (strlen($url) > 255)
2619 return wfMsg('scarytranscludetoolong');
2620 $text = $this->fetchScaryTemplateMaybeFromCache($url);
2621 $this->mIWTransData[] = $text;
2622 return "<!--IW_TRANSCLUDE ".(count($this->mIWTransData) - 1)."-->";
2623 }
2624
2625 function fetchScaryTemplateMaybeFromCache($url) {
2626 $dbr =& wfGetDB(DB_SLAVE);
2627 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2628 array('tc_url' => $url));
2629 if ($obj) {
2630 $time = $obj->tc_time;
2631 $text = $obj->tc_contents;
2632 if ($time && $time < (time() + (60*60))) {
2633 return $text;
2634 }
2635 }
2636
2637 $text = wfGetHTTP($url . '?action=render');
2638 if (!$text)
2639 return wfMsg('scarytranscludefailed', $url);
2640
2641 $dbw =& wfGetDB(DB_MASTER);
2642 $dbw->replace('transcache', array(), array(
2643 'tc_url' => $url,
2644 'tc_time' => time(),
2645 'tc_contents' => $text));
2646 return $text;
2647 }
2648
2649
2650 /**
2651 * Triple brace replacement -- used for template arguments
2652 * @access private
2653 */
2654 function argSubstitution( $matches ) {
2655 $arg = trim( $matches['title'] );
2656 $text = $matches['text'];
2657 $inputArgs = end( $this->mArgStack );
2658
2659 if ( array_key_exists( $arg, $inputArgs ) ) {
2660 $text = $inputArgs[$arg];
2661 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
2662 $text = $matches['parts'][0];
2663 }
2664
2665 return $text;
2666 }
2667
2668 /**
2669 * Returns true if the function is allowed to include this entity
2670 * @access private
2671 */
2672 function incrementIncludeCount( $dbk ) {
2673 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2674 $this->mIncludeCount[$dbk] = 0;
2675 }
2676 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2677 return true;
2678 } else {
2679 return false;
2680 }
2681 }
2682
2683 /**
2684 * This function accomplishes several tasks:
2685 * 1) Auto-number headings if that option is enabled
2686 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2687 * 3) Add a Table of contents on the top for users who have enabled the option
2688 * 4) Auto-anchor headings
2689 *
2690 * It loops through all headlines, collects the necessary data, then splits up the
2691 * string and re-inserts the newly formatted headlines.
2692 *
2693 * @param string $text
2694 * @param boolean $isMain
2695 * @access private
2696 */
2697 function formatHeadings( $text, $isMain=true ) {
2698 global $wgMaxTocLevel, $wgContLang;
2699
2700 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2701 $doShowToc = true;
2702 $forceTocHere = false;
2703 if( !$this->mTitle->userCanEdit() ) {
2704 $showEditLink = 0;
2705 } else {
2706 $showEditLink = $this->mOptions->getEditSection();
2707 }
2708
2709 # Inhibit editsection links if requested in the page
2710 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2711 if( $esw->matchAndRemove( $text ) ) {
2712 $showEditLink = 0;
2713 }
2714 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2715 # do not add TOC
2716 $mw =& MagicWord::get( MAG_NOTOC );
2717 if( $mw->matchAndRemove( $text ) ) {
2718 $doShowToc = false;
2719 }
2720
2721 # Get all headlines for numbering them and adding funky stuff like [edit]
2722 # links - this is for later, but we need the number of headlines right now
2723 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2724
2725 # if there are fewer than 4 headlines in the article, do not show TOC
2726 if( $numMatches < 4 ) {
2727 $doShowToc = false;
2728 }
2729
2730 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2731 # override above conditions and always show TOC at that place
2732
2733 $mw =& MagicWord::get( MAG_TOC );
2734 if($mw->match( $text ) ) {
2735 $doShowToc = true;
2736 $forceTocHere = true;
2737 } else {
2738 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2739 # override above conditions and always show TOC above first header
2740 $mw =& MagicWord::get( MAG_FORCETOC );
2741 if ($mw->matchAndRemove( $text ) ) {
2742 $doShowToc = true;
2743 }
2744 }
2745
2746 # Never ever show TOC if no headers
2747 if( $numMatches < 1 ) {
2748 $doShowToc = false;
2749 }
2750
2751 # We need this to perform operations on the HTML
2752 $sk =& $this->mOptions->getSkin();
2753
2754 # headline counter
2755 $headlineCount = 0;
2756 $sectionCount = 0; # headlineCount excluding template sections
2757
2758 # Ugh .. the TOC should have neat indentation levels which can be
2759 # passed to the skin functions. These are determined here
2760 $toc = '';
2761 $full = '';
2762 $head = array();
2763 $sublevelCount = array();
2764 $levelCount = array();
2765 $toclevel = 0;
2766 $level = 0;
2767 $prevlevel = 0;
2768 $toclevel = 0;
2769 $prevtoclevel = 0;
2770
2771 foreach( $matches[3] as $headline ) {
2772 $istemplate = 0;
2773 $templatetitle = '';
2774 $templatesection = 0;
2775 $numbering = '';
2776
2777 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2778 $istemplate = 1;
2779 $templatetitle = base64_decode($mat[1]);
2780 $templatesection = 1 + (int)base64_decode($mat[2]);
2781 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2782 }
2783
2784 if( $toclevel ) {
2785 $prevlevel = $level;
2786 $prevtoclevel = $toclevel;
2787 }
2788 $level = $matches[1][$headlineCount];
2789
2790 if( $doNumberHeadings || $doShowToc ) {
2791
2792 if ( $level > $prevlevel ) {
2793 # Increase TOC level
2794 $toclevel++;
2795 $sublevelCount[$toclevel] = 0;
2796 $toc .= $sk->tocIndent();
2797 }
2798 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2799 # Decrease TOC level, find level to jump to
2800
2801 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2802 # Can only go down to level 1
2803 $toclevel = 1;
2804 } else {
2805 for ($i = $toclevel; $i > 0; $i--) {
2806 if ( $levelCount[$i] == $level ) {
2807 # Found last matching level
2808 $toclevel = $i;
2809 break;
2810 }
2811 elseif ( $levelCount[$i] < $level ) {
2812 # Found first matching level below current level
2813 $toclevel = $i + 1;
2814 break;
2815 }
2816 }
2817 }
2818
2819 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2820 }
2821 else {
2822 # No change in level, end TOC line
2823 $toc .= $sk->tocLineEnd();
2824 }
2825
2826 $levelCount[$toclevel] = $level;
2827
2828 # count number of headlines for each level
2829 @$sublevelCount[$toclevel]++;
2830 $dot = 0;
2831 for( $i = 1; $i <= $toclevel; $i++ ) {
2832 if( !empty( $sublevelCount[$i] ) ) {
2833 if( $dot ) {
2834 $numbering .= '.';
2835 }
2836 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2837 $dot = 1;
2838 }
2839 }
2840 }
2841
2842 # The canonized header is a version of the header text safe to use for links
2843 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2844 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2845 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2846
2847 # Remove link placeholders by the link text.
2848 # <!--LINK number-->
2849 # turns into
2850 # link text with suffix
2851 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2852 "\$this->mLinkHolders['texts'][\$1]",
2853 $canonized_headline );
2854 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2855 "\$this->mInterwikiLinkHolders['texts'][\$1]",
2856 $canonized_headline );
2857
2858 # strip out HTML
2859 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2860 $tocline = trim( $canonized_headline );
2861 $canonized_headline = urlencode( Sanitizer::decodeCharReferences( str_replace(' ', '_', $tocline) ) );
2862 $replacearray = array(
2863 '%3A' => ':',
2864 '%' => '.'
2865 );
2866 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2867 $refers[$headlineCount] = $canonized_headline;
2868
2869 # count how many in assoc. array so we can track dupes in anchors
2870 @$refers[$canonized_headline]++;
2871 $refcount[$headlineCount]=$refers[$canonized_headline];
2872
2873 # Don't number the heading if it is the only one (looks silly)
2874 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2875 # the two are different if the line contains a link
2876 $headline=$numbering . ' ' . $headline;
2877 }
2878
2879 # Create the anchor for linking from the TOC to the section
2880 $anchor = $canonized_headline;
2881 if($refcount[$headlineCount] > 1 ) {
2882 $anchor .= '_' . $refcount[$headlineCount];
2883 }
2884 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2885 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2886 }
2887 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2888 if ( empty( $head[$headlineCount] ) ) {
2889 $head[$headlineCount] = '';
2890 }
2891 if( $istemplate )
2892 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2893 else
2894 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2895 }
2896
2897 # give headline the correct <h#> tag
2898 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2899
2900 $headlineCount++;
2901 if( !$istemplate )
2902 $sectionCount++;
2903 }
2904
2905 if( $doShowToc ) {
2906 $toc .= $sk->tocUnindent( $toclevel - 1 );
2907 $toc = $sk->tocList( $toc );
2908 }
2909
2910 # split up and insert constructed headlines
2911
2912 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2913 $i = 0;
2914
2915 foreach( $blocks as $block ) {
2916 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2917 # This is the [edit] link that appears for the top block of text when
2918 # section editing is enabled
2919
2920 # Disabled because it broke block formatting
2921 # For example, a bullet point in the top line
2922 # $full .= $sk->editSectionLink(0);
2923 }
2924 $full .= $block;
2925 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2926 # Top anchor now in skin
2927 $full = $full.$toc;
2928 }
2929
2930 if( !empty( $head[$i] ) ) {
2931 $full .= $head[$i];
2932 }
2933 $i++;
2934 }
2935 if($forceTocHere) {
2936 $mw =& MagicWord::get( MAG_TOC );
2937 return $mw->replace( $toc, $full );
2938 } else {
2939 return $full;
2940 }
2941 }
2942
2943 /**
2944 * Return an HTML link for the "ISBN 123456" text
2945 * @access private
2946 */
2947 function magicISBN( $text ) {
2948 $fname = 'Parser::magicISBN';
2949 wfProfileIn( $fname );
2950
2951 $a = split( 'ISBN ', ' '.$text );
2952 if ( count ( $a ) < 2 ) {
2953 wfProfileOut( $fname );
2954 return $text;
2955 }
2956 $text = substr( array_shift( $a ), 1);
2957 $valid = '0123456789-Xx';
2958
2959 foreach ( $a as $x ) {
2960 $isbn = $blank = '' ;
2961 while ( ' ' == $x{0} ) {
2962 $blank .= ' ';
2963 $x = substr( $x, 1 );
2964 }
2965 if ( $x == '' ) { # blank isbn
2966 $text .= "ISBN $blank";
2967 continue;
2968 }
2969 while ( strstr( $valid, $x{0} ) != false ) {
2970 $isbn .= $x{0};
2971 $x = substr( $x, 1 );
2972 }
2973 $num = str_replace( '-', '', $isbn );
2974 $num = str_replace( ' ', '', $num );
2975 $num = str_replace( 'x', 'X', $num );
2976
2977 if ( '' == $num ) {
2978 $text .= "ISBN $blank$x";
2979 } else {
2980 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2981 $text .= '<a href="' .
2982 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2983 "\" class=\"internal\">ISBN $isbn</a>";
2984 $text .= $x;
2985 }
2986 }
2987 wfProfileOut( $fname );
2988 return $text;
2989 }
2990
2991 /**
2992 * Return an HTML link for the "RFC 1234" text
2993 *
2994 * @access private
2995 * @param string $text Text to be processed
2996 * @param string $keyword Magic keyword to use (default RFC)
2997 * @param string $urlmsg Interface message to use (default rfcurl)
2998 * @return string
2999 */
3000 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3001
3002 $valid = '0123456789';
3003 $internal = false;
3004
3005 $a = split( $keyword, ' '.$text );
3006 if ( count ( $a ) < 2 ) {
3007 return $text;
3008 }
3009 $text = substr( array_shift( $a ), 1);
3010
3011 /* Check if keyword is preceed by [[.
3012 * This test is made here cause of the array_shift above
3013 * that prevent the test to be done in the foreach.
3014 */
3015 if ( substr( $text, -2 ) == '[[' ) {
3016 $internal = true;
3017 }
3018
3019 foreach ( $a as $x ) {
3020 /* token might be empty if we have RFC RFC 1234 */
3021 if ( $x=='' ) {
3022 $text.=$keyword;
3023 continue;
3024 }
3025
3026 $id = $blank = '' ;
3027
3028 /** remove and save whitespaces in $blank */
3029 while ( $x{0} == ' ' ) {
3030 $blank .= ' ';
3031 $x = substr( $x, 1 );
3032 }
3033
3034 /** remove and save the rfc number in $id */
3035 while ( strstr( $valid, $x{0} ) != false ) {
3036 $id .= $x{0};
3037 $x = substr( $x, 1 );
3038 }
3039
3040 if ( $id == '' ) {
3041 /* call back stripped spaces*/
3042 $text .= $keyword.$blank.$x;
3043 } elseif( $internal ) {
3044 /* normal link */
3045 $text .= $keyword.$id.$x;
3046 } else {
3047 /* build the external link*/
3048 $url = wfMsg( $urlmsg, $id);
3049 $sk =& $this->mOptions->getSkin();
3050 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3051 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3052 }
3053
3054 /* Check if the next RFC keyword is preceed by [[ */
3055 $internal = ( substr($x,-2) == '[[' );
3056 }
3057 return $text;
3058 }
3059
3060 /**
3061 * Transform wiki markup when saving a page by doing \r\n -> \n
3062 * conversion, substitting signatures, {{subst:}} templates, etc.
3063 *
3064 * @param string $text the text to transform
3065 * @param Title &$title the Title object for the current article
3066 * @param User &$user the User object describing the current user
3067 * @param ParserOptions $options parsing options
3068 * @param bool $clearState whether to clear the parser state first
3069 * @return string the altered wiki markup
3070 * @access public
3071 */
3072 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3073 $this->mOptions = $options;
3074 $this->mTitle =& $title;
3075 $this->mOutputType = OT_WIKI;
3076
3077 if ( $clearState ) {
3078 $this->clearState();
3079 }
3080
3081 $stripState = false;
3082 $pairs = array(
3083 "\r\n" => "\n",
3084 );
3085 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3086 $text = $this->strip( $text, $stripState, true );
3087 $text = $this->pstPass2( $text, $user );
3088 $text = $this->unstrip( $text, $stripState );
3089 $text = $this->unstripNoWiki( $text, $stripState );
3090 return $text;
3091 }
3092
3093 /**
3094 * Pre-save transform helper function
3095 * @access private
3096 */
3097 function pstPass2( $text, &$user ) {
3098 global $wgContLang, $wgLocaltimezone;
3099
3100 # Variable replacement
3101 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3102 $text = $this->replaceVariables( $text );
3103
3104 # Signatures
3105 #
3106 $sigText = $this->getUserSig( $user );
3107
3108 /* Note: This is the timestamp saved as hardcoded wikitext to
3109 * the database, we use $wgContLang here in order to give
3110 * everyone the same signiture and use the default one rather
3111 * than the one selected in each users preferences.
3112 */
3113 if ( isset( $wgLocaltimezone ) ) {
3114 $oldtz = getenv( 'TZ' );
3115 putenv( 'TZ='.$wgLocaltimezone );
3116 }
3117 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3118 ' (' . date( 'T' ) . ')';
3119 if ( isset( $wgLocaltimezone ) ) {
3120 putenv( 'TZ='.$oldtz );
3121 }
3122
3123 $text = preg_replace( '/~~~~~/', $d, $text );
3124 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
3125 $text = preg_replace( '/~~~/', $sigText, $text );
3126
3127 # Context links: [[|name]] and [[name (context)|]]
3128 #
3129 global $wgLegalTitleChars;
3130 $tc = "[$wgLegalTitleChars]";
3131 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3132
3133 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3134 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3135
3136 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3137 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3138 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3139 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3140 $context = '';
3141 $t = $this->mTitle->getText();
3142 if ( preg_match( $conpat, $t, $m ) ) {
3143 $context = $m[2];
3144 }
3145 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3146 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3147 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3148
3149 if ( '' == $context ) {
3150 $text = preg_replace( $p2, '[[\\1]]', $text );
3151 } else {
3152 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3153 }
3154
3155 # Trim trailing whitespace
3156 # MAG_END (__END__) tag allows for trailing
3157 # whitespace to be deliberately included
3158 $text = rtrim( $text );
3159 $mw =& MagicWord::get( MAG_END );
3160 $mw->matchAndRemove( $text );
3161
3162 return $text;
3163 }
3164
3165 /**
3166 * Fetch the user's signature text, if any, and normalize to
3167 * validated, ready-to-insert wikitext.
3168 *
3169 * @param User $user
3170 * @return string
3171 * @access private
3172 */
3173 function getUserSig( &$user ) {
3174 $name = $user->getName();
3175 $nick = trim( $user->getOption( 'nickname' ) );
3176 if ( '' == $nick ) {
3177 $nick = $name;
3178 }
3179
3180 if( $user->getOption( 'fancysig' ) ) {
3181 // A wikitext signature.
3182 $valid = $this->validateSig( $nick );
3183 if( $valid === false ) {
3184 // Fall back to default sig
3185 $nick = $name;
3186 wfDebug( "Parser::getUserSig: $name has bad XML tags in signature.\n" );
3187 } else {
3188 return $nick;
3189 }
3190 }
3191
3192 // Plain text linking to the user's homepage
3193 global $wgContLang;
3194 $page = $user->getUserPage();
3195 return '[[' .
3196 $page->getPrefixedText() .
3197 "|" .
3198 wfEscapeWikIText( $nick ) .
3199 "]]";
3200 }
3201
3202 /**
3203 * We want to enforce two rules on wikitext sigs here:
3204 * 1) Expand any templates at save time (forced subst:)
3205 * 2) Check for unbalanced XML tags, and reject if so.
3206 *
3207 * @param string $text
3208 * @return mixed An expanded string, or false if invalid.
3209 *
3210 * @todo Run brace substitutions
3211 * @todo ?? Check for unbalanced '' and ''' quotes, etc
3212 */
3213 function validateSig( $text ) {
3214 if( wfIsWellFormedXmlFragment( $text ) ) {
3215 return $text;
3216 } else {
3217 return false;
3218 }
3219 }
3220
3221 /**
3222 * Set up some variables which are usually set up in parse()
3223 * so that an external function can call some class members with confidence
3224 * @access public
3225 */
3226 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3227 $this->mTitle =& $title;
3228 $this->mOptions = $options;
3229 $this->mOutputType = $outputType;
3230 if ( $clearState ) {
3231 $this->clearState();
3232 }
3233 }
3234
3235 /**
3236 * Transform a MediaWiki message by replacing magic variables.
3237 *
3238 * @param string $text the text to transform
3239 * @param ParserOptions $options options
3240 * @return string the text with variables substituted
3241 * @access public
3242 */
3243 function transformMsg( $text, $options ) {
3244 global $wgTitle;
3245 static $executing = false;
3246
3247 # Guard against infinite recursion
3248 if ( $executing ) {
3249 return $text;
3250 }
3251 $executing = true;
3252
3253 $this->mTitle = $wgTitle;
3254 $this->mOptions = $options;
3255 $this->mOutputType = OT_MSG;
3256 $this->clearState();
3257 $text = $this->replaceVariables( $text );
3258
3259 $executing = false;
3260 return $text;
3261 }
3262
3263 /**
3264 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3265 * Callback will be called with the text within
3266 * Transform and return the text within
3267 *
3268 * @access public
3269 *
3270 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3271 * @param mixed $callback The callback function (and object) to use for the tag
3272 *
3273 * @return The old value of the mTagHooks array associated with the hook
3274 */
3275 function setHook( $tag, $callback ) {
3276 $oldVal = @$this->mTagHooks[$tag];
3277 $this->mTagHooks[$tag] = $callback;
3278
3279 return $oldVal;
3280 }
3281
3282 /**
3283 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3284 * Placeholders created in Skin::makeLinkObj()
3285 * Returns an array of links found, indexed by PDBK:
3286 * 0 - broken
3287 * 1 - normal link
3288 * 2 - stub
3289 * $options is a bit field, RLH_FOR_UPDATE to select for update
3290 */
3291 function replaceLinkHolders( &$text, $options = 0 ) {
3292 global $wgUser, $wgLinkCache;
3293 global $wgOutputReplace;
3294
3295 $fname = 'Parser::replaceLinkHolders';
3296 wfProfileIn( $fname );
3297
3298 $pdbks = array();
3299 $colours = array();
3300 $sk = $this->mOptions->getSkin();
3301
3302 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3303 wfProfileIn( $fname.'-check' );
3304 $dbr =& wfGetDB( DB_SLAVE );
3305 $page = $dbr->tableName( 'page' );
3306 $threshold = $wgUser->getOption('stubthreshold');
3307
3308 # Sort by namespace
3309 asort( $this->mLinkHolders['namespaces'] );
3310
3311 # Generate query
3312 $query = false;
3313 foreach ( $this->mLinkHolders['namespaces'] as $key => $val ) {
3314 # Make title object
3315 $title = $this->mLinkHolders['titles'][$key];
3316
3317 # Skip invalid entries.
3318 # Result will be ugly, but prevents crash.
3319 if ( is_null( $title ) ) {
3320 continue;
3321 }
3322 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3323
3324 # Check if it's in the link cache already
3325 if ( $title->isAlwaysKnown() || $wgLinkCache->getGoodLinkID( $pdbk ) ) {
3326 $colours[$pdbk] = 1;
3327 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
3328 $colours[$pdbk] = 0;
3329 } else {
3330 # Not in the link cache, add it to the query
3331 if ( !isset( $current ) ) {
3332 $current = $val;
3333 $query = "SELECT page_id, page_namespace, page_title";
3334 if ( $threshold > 0 ) {
3335 $query .= ', page_len, page_is_redirect';
3336 }
3337 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
3338 } elseif ( $current != $val ) {
3339 $current = $val;
3340 $query .= ")) OR (page_namespace=$val AND page_title IN(";
3341 } else {
3342 $query .= ', ';
3343 }
3344
3345 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3346 }
3347 }
3348 if ( $query ) {
3349 $query .= '))';
3350 if ( $options & RLH_FOR_UPDATE ) {
3351 $query .= ' FOR UPDATE';
3352 }
3353
3354 $res = $dbr->query( $query, $fname );
3355
3356 # Fetch data and form into an associative array
3357 # non-existent = broken
3358 # 1 = known
3359 # 2 = stub
3360 while ( $s = $dbr->fetchObject($res) ) {
3361 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3362 $pdbk = $title->getPrefixedDBkey();
3363 $wgLinkCache->addGoodLinkObj( $s->page_id, $title );
3364
3365 if ( $threshold > 0 ) {
3366 $size = $s->page_len;
3367 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3368 $colours[$pdbk] = 1;
3369 } else {
3370 $colours[$pdbk] = 2;
3371 }
3372 } else {
3373 $colours[$pdbk] = 1;
3374 }
3375 }
3376 }
3377 wfProfileOut( $fname.'-check' );
3378
3379 # Construct search and replace arrays
3380 wfProfileIn( $fname.'-construct' );
3381 $wgOutputReplace = array();
3382 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3383 $pdbk = $pdbks[$key];
3384 $searchkey = "<!--LINK $key-->";
3385 $title = $this->mLinkHolders['titles'][$key];
3386 if ( empty( $colours[$pdbk] ) ) {
3387 $wgLinkCache->addBadLinkObj( $title );
3388 $colours[$pdbk] = 0;
3389 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3390 $this->mLinkHolders['texts'][$key],
3391 $this->mLinkHolders['queries'][$key] );
3392 } elseif ( $colours[$pdbk] == 1 ) {
3393 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3394 $this->mLinkHolders['texts'][$key],
3395 $this->mLinkHolders['queries'][$key] );
3396 } elseif ( $colours[$pdbk] == 2 ) {
3397 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3398 $this->mLinkHolders['texts'][$key],
3399 $this->mLinkHolders['queries'][$key] );
3400 }
3401 }
3402 wfProfileOut( $fname.'-construct' );
3403
3404 # Do the thing
3405 wfProfileIn( $fname.'-replace' );
3406
3407 $text = preg_replace_callback(
3408 '/(<!--LINK .*?-->)/',
3409 "wfOutputReplaceMatches",
3410 $text);
3411
3412 wfProfileOut( $fname.'-replace' );
3413 }
3414
3415 # Now process interwiki link holders
3416 # This is quite a bit simpler than internal links
3417 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3418 wfProfileIn( $fname.'-interwiki' );
3419 # Make interwiki link HTML
3420 $wgOutputReplace = array();
3421 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3422 $title = $this->mInterwikiLinkHolders['titles'][$key];
3423 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3424 }
3425
3426 $text = preg_replace_callback(
3427 '/<!--IWLINK (.*?)-->/',
3428 "wfOutputReplaceMatches",
3429 $text );
3430 wfProfileOut( $fname.'-interwiki' );
3431 }
3432
3433 wfProfileOut( $fname );
3434 return $colours;
3435 }
3436
3437 /**
3438 * Replace <!--LINK--> link placeholders with plain text of links
3439 * (not HTML-formatted).
3440 * @param string $text
3441 * @return string
3442 */
3443 function replaceLinkHoldersText( $text ) {
3444 global $wgUser, $wgLinkCache;
3445 global $wgOutputReplace;
3446
3447 $fname = 'Parser::replaceLinkHoldersText';
3448 wfProfileIn( $fname );
3449
3450 $text = preg_replace_callback(
3451 '/<!--(LINK|IWLINK) (.*?)-->/',
3452 array( &$this, 'replaceLinkHoldersTextCallback' ),
3453 $text );
3454
3455 wfProfileOut( $fname );
3456 return $text;
3457 }
3458
3459 /**
3460 * @param array $matches
3461 * @return string
3462 * @access private
3463 */
3464 function replaceLinkHoldersTextCallback( $matches ) {
3465 $type = $matches[1];
3466 $key = $matches[2];
3467 if( $type == 'LINK' ) {
3468 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3469 return $this->mLinkHolders['texts'][$key];
3470 }
3471 } elseif( $type == 'IWLINK' ) {
3472 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3473 return $this->mInterwikiLinkHolders['texts'][$key];
3474 }
3475 }
3476 return $matches[0];
3477 }
3478
3479 /**
3480 * Renders an image gallery from a text with one line per image.
3481 * text labels may be given by using |-style alternative text. E.g.
3482 * Image:one.jpg|The number "1"
3483 * Image:tree.jpg|A tree
3484 * given as text will return the HTML of a gallery with two images,
3485 * labeled 'The number "1"' and
3486 * 'A tree'.
3487 *
3488 * @static
3489 */
3490 function renderImageGallery( $text ) {
3491 # Setup the parser
3492 global $wgUser, $wgTitle;
3493 $parserOptions = ParserOptions::newFromUser( $wgUser );
3494 $localParser = new Parser();
3495
3496 global $wgLinkCache;
3497 $ig = new ImageGallery();
3498 $ig->setShowBytes( false );
3499 $ig->setShowFilename( false );
3500 $lines = explode( "\n", $text );
3501
3502 foreach ( $lines as $line ) {
3503 # match lines like these:
3504 # Image:someimage.jpg|This is some image
3505 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3506 # Skip empty lines
3507 if ( count( $matches ) == 0 ) {
3508 continue;
3509 }
3510 $nt = Title::newFromURL( $matches[1] );
3511 if( is_null( $nt ) ) {
3512 # Bogus title. Ignore these so we don't bomb out later.
3513 continue;
3514 }
3515 if ( isset( $matches[3] ) ) {
3516 $label = $matches[3];
3517 } else {
3518 $label = '';
3519 }
3520
3521 $html = $localParser->parse( $label , $wgTitle, $parserOptions );
3522 $html = $html->mText;
3523
3524 $ig->add( new Image( $nt ), $html );
3525 $wgLinkCache->addImageLinkObj( $nt );
3526 }
3527 return $ig->toHTML();
3528 }
3529
3530 /**
3531 * Parse image options text and use it to make an image
3532 */
3533 function makeImage( &$nt, $options ) {
3534 global $wgContLang, $wgUseImageResize, $wgUser;
3535
3536 $align = '';
3537
3538 # Check if the options text is of the form "options|alt text"
3539 # Options are:
3540 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3541 # * left no resizing, just left align. label is used for alt= only
3542 # * right same, but right aligned
3543 # * none same, but not aligned
3544 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3545 # * center center the image
3546 # * framed Keep original image size, no magnify-button.
3547
3548 $part = explode( '|', $options);
3549
3550 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3551 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
3552 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3553 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3554 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3555 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3556 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3557 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3558 $caption = '';
3559
3560 $width = $height = $framed = $thumb = false;
3561 $manual_thumb = '' ;
3562
3563 foreach( $part as $key => $val ) {
3564 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3565 $thumb=true;
3566 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3567 # use manually specified thumbnail
3568 $thumb=true;
3569 $manual_thumb = $match;
3570 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3571 # remember to set an alignment, don't render immediately
3572 $align = 'right';
3573 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3574 # remember to set an alignment, don't render immediately
3575 $align = 'left';
3576 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3577 # remember to set an alignment, don't render immediately
3578 $align = 'center';
3579 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3580 # remember to set an alignment, don't render immediately
3581 $align = 'none';
3582 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3583 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3584 # $match is the image width in pixels
3585 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3586 $width = intval( $m[1] );
3587 $height = intval( $m[2] );
3588 } else {
3589 $width = intval($match);
3590 }
3591 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3592 $framed=true;
3593 } else {
3594 $caption = $val;
3595 }
3596 }
3597 # Strip bad stuff out of the alt text
3598 $alt = $this->replaceLinkHoldersText( $caption );
3599 $alt = Sanitizer::stripAllTags( $alt );
3600
3601 # Linker does the rest
3602 $sk =& $this->mOptions->getSkin();
3603 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3604 }
3605
3606 /**
3607 * Set a flag in the output object indicating that the content is dynamic and
3608 * shouldn't be cached.
3609 */
3610 function disableCache() {
3611 $this->mOutput->mCacheTime = -1;
3612 }
3613
3614 /**
3615 * Callback from the Sanitizer for expanding items found in HTML attribute
3616 * values, so they can be safely tested and escaped.
3617 * @param string $text
3618 * @param array $args
3619 * @return string
3620 * @access private
3621 */
3622 function attributeStripCallback( &$text, $args ) {
3623 $text = $this->replaceVariables( $text, $args );
3624 $text = $this->unstripForHTML( $text );
3625 return $text;
3626 }
3627
3628 function unstripForHTML( $text ) {
3629 $text = $this->unstrip( $text, $this->mStripState );
3630 $text = $this->unstripNoWiki( $text, $this->mStripState );
3631 return $text;
3632 }
3633
3634 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
3635 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
3636 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
3637 }
3638
3639 /**
3640 * @todo document
3641 * @package MediaWiki
3642 */
3643 class ParserOutput
3644 {
3645 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
3646 var $mCacheTime; # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3647 var $mVersion; # Compatibility check
3648 var $mTitleText; # title text of the chosen language variant
3649
3650 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3651 $containsOldMagic = false, $titletext = '' )
3652 {
3653 $this->mText = $text;
3654 $this->mLanguageLinks = $languageLinks;
3655 $this->mCategoryLinks = $categoryLinks;
3656 $this->mContainsOldMagic = $containsOldMagic;
3657 $this->mCacheTime = '';
3658 $this->mVersion = MW_PARSER_VERSION;
3659 $this->mTitleText = $titletext;
3660 }
3661
3662 function getText() { return $this->mText; }
3663 function getLanguageLinks() { return $this->mLanguageLinks; }
3664 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
3665 function getCacheTime() { return $this->mCacheTime; }
3666 function getTitleText() { return $this->mTitleText; }
3667 function containsOldMagic() { return $this->mContainsOldMagic; }
3668 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3669 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3670 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
3671 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3672 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3673 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3674
3675 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
3676
3677 function merge( $other ) {
3678 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3679 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
3680 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3681 }
3682
3683 /**
3684 * Return true if this cached output object predates the global or
3685 * per-article cache invalidation timestamps, or if it comes from
3686 * an incompatible older version.
3687 *
3688 * @param string $touched the affected article's last touched timestamp
3689 * @return bool
3690 * @access public
3691 */
3692 function expired( $touched ) {
3693 global $wgCacheEpoch;
3694 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3695 $this->getCacheTime() < $touched ||
3696 $this->getCacheTime() <= $wgCacheEpoch ||
3697 !isset( $this->mVersion ) ||
3698 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3699 }
3700 }
3701
3702 /**
3703 * Set options of the Parser
3704 * @todo document
3705 * @package MediaWiki
3706 */
3707 class ParserOptions
3708 {
3709 # All variables are private
3710 var $mUseTeX; # Use texvc to expand <math> tags
3711 var $mUseDynamicDates; # Use DateFormatter to format dates
3712 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3713 var $mAllowExternalImages; # Allow external images inline
3714 var $mAllowExternalImagesFrom; # If not, any exception?
3715 var $mSkin; # Reference to the preferred skin
3716 var $mDateFormat; # Date format index
3717 var $mEditSection; # Create "edit section" links
3718 var $mNumberHeadings; # Automatically number headings
3719 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3720
3721 function getUseTeX() { return $this->mUseTeX; }
3722 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3723 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3724 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3725 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
3726 function &getSkin() { return $this->mSkin; }
3727 function getDateFormat() { return $this->mDateFormat; }
3728 function getEditSection() { return $this->mEditSection; }
3729 function getNumberHeadings() { return $this->mNumberHeadings; }
3730 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3731
3732
3733 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3734 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3735 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3736 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3737 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
3738 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3739 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3740 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3741 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3742
3743 function setSkin( &$x ) { $this->mSkin =& $x; }
3744
3745 function ParserOptions() {
3746 global $wgUser;
3747 $this->initialiseFromUser( $wgUser );
3748 }
3749
3750 /**
3751 * Get parser options
3752 * @static
3753 */
3754 function newFromUser( &$user ) {
3755 $popts = new ParserOptions;
3756 $popts->initialiseFromUser( $user );
3757 return $popts;
3758 }
3759
3760 /** Get user options */
3761 function initialiseFromUser( &$userInput ) {
3762 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3763 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3764 $fname = 'ParserOptions::initialiseFromUser';
3765 wfProfileIn( $fname );
3766 if ( !$userInput ) {
3767 $user = new User;
3768 $user->setLoaded( true );
3769 } else {
3770 $user =& $userInput;
3771 }
3772
3773 $this->mUseTeX = $wgUseTeX;
3774 $this->mUseDynamicDates = $wgUseDynamicDates;
3775 $this->mInterwikiMagic = $wgInterwikiMagic;
3776 $this->mAllowExternalImages = $wgAllowExternalImages;
3777 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
3778 wfProfileIn( $fname.'-skin' );
3779 $this->mSkin =& $user->getSkin();
3780 wfProfileOut( $fname.'-skin' );
3781 $this->mDateFormat = $user->getOption( 'date' );
3782 $this->mEditSection = true;
3783 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3784 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
3785 wfProfileOut( $fname );
3786 }
3787 }
3788
3789 /**
3790 * Callback function used by Parser::replaceLinkHolders()
3791 * to substitute link placeholders.
3792 */
3793 function &wfOutputReplaceMatches( $matches ) {
3794 global $wgOutputReplace;
3795 return $wgOutputReplace[$matches[1]];
3796 }
3797
3798 /**
3799 * Return the total number of articles
3800 */
3801 function wfNumberOfArticles() {
3802 global $wgNumberOfArticles;
3803
3804 wfLoadSiteStats();
3805 return $wgNumberOfArticles;
3806 }
3807
3808 /**
3809 * Return the number of files
3810 */
3811 function wfNumberOfFiles() {
3812 $fname = 'Parser::wfNumberOfFiles';
3813
3814 wfProfileIn( $fname );
3815 $dbr =& wfGetDB( DB_SLAVE );
3816 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
3817 wfProfileOut( $fname );
3818
3819 return $res;
3820 }
3821
3822 /**
3823 * Get various statistics from the database
3824 * @private
3825 */
3826 function wfLoadSiteStats() {
3827 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3828 $fname = 'wfLoadSiteStats';
3829
3830 if ( -1 != $wgNumberOfArticles ) return;
3831 $dbr =& wfGetDB( DB_SLAVE );
3832 $s = $dbr->selectRow( 'site_stats',
3833 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3834 array( 'ss_row_id' => 1 ), $fname
3835 );
3836
3837 if ( $s === false ) {
3838 return;
3839 } else {
3840 $wgTotalViews = $s->ss_total_views;
3841 $wgTotalEdits = $s->ss_total_edits;
3842 $wgNumberOfArticles = $s->ss_good_articles;
3843 }
3844 }
3845
3846 /**
3847 * Escape html tags
3848 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3849 *
3850 * @param string $in Text that might contain HTML tags
3851 * @return string Escaped string
3852 */
3853 function wfEscapeHTMLTagsOnly( $in ) {
3854 return str_replace(
3855 array( '"', '>', '<' ),
3856 array( '&quot;', '&gt;', '&lt;' ),
3857 $in );
3858 }
3859
3860 ?>