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