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