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