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