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