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