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