* changed function magicRFC: documented it, and rewrote a small part of the
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2 /**
3 * File for Parser and related classes
4 *
5 * @package MediaWiki
6 */
7
8 /** */
9 require_once( 'Sanitizer.php' );
10
11 /**
12 * Update this version number when the ParserOutput format
13 * changes in an incompatible way, so the parser cache
14 * can automatically discard old data.
15 */
16 define( 'MW_PARSER_VERSION', '1.5.0' );
17
18 /**
19 * Variable substitution O(N^2) attack
20 *
21 * Without countermeasures, it would be possible to attack the parser by saving
22 * a page filled with a large number of inclusions of large pages. The size of
23 * the generated page would be proportional to the square of the input size.
24 * Hence, we limit the number of inclusions of any given page, thus bringing any
25 * attack back to O(N).
26 */
27
28 define( 'MAX_INCLUDE_REPEAT', 100 );
29 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
30
31 define( 'RLH_FOR_UPDATE', 1 );
32
33 # Allowed values for $mOutputType
34 define( 'OT_HTML', 1 );
35 define( 'OT_WIKI', 2 );
36 define( 'OT_MSG' , 3 );
37
38 # string parameter for extractTags which will cause it
39 # to strip HTML comments in addition to regular
40 # <XML>-style tags. This should not be anything we
41 # may want to use in wikisyntax
42 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
43
44 # prefix for escaping, used in two functions at least
45 define( 'UNIQ_PREFIX', 'NaodW29');
46
47 # Constants needed for external link processing
48 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
49 define( 'HTTP_PROTOCOLS', 'http|https' );
50 # Everything except bracket, space, or control characters
51 define( 'EXT_LINK_URL_CLASS', '[^]<>"\\x00-\\x20\\x7F]' );
52 # Including space
53 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
54 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
55 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
56 define( 'EXT_LINK_BRACKETED', '/\[(\b('.URL_PROTOCOLS.'):'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
57 define( 'EXT_IMAGE_REGEX',
58 '/^('.HTTP_PROTOCOLS.':)'. # Protocol
59 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
60 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
61 );
62
63 /**
64 * PHP Parser
65 *
66 * Processes wiki markup
67 *
68 * <pre>
69 * There are three main entry points into the Parser class:
70 * parse()
71 * produces HTML output
72 * preSaveTransform().
73 * produces altered wiki markup.
74 * transformMsg()
75 * performs brace substitution on MediaWiki messages
76 *
77 * Globals used:
78 * objects: $wgLang, $wgDateFormatter, $wgLinkCache
79 *
80 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
81 *
82 * settings:
83 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
84 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
85 * $wgLocaltimezone
86 *
87 * * only within ParserOptions
88 * </pre>
89 *
90 * @package MediaWiki
91 */
92 class Parser
93 {
94 /**#@+
95 * @access private
96 */
97 # Persistent:
98 var $mTagHooks;
99
100 # Cleared with clearState():
101 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
102 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
103
104 # Temporary:
105 var $mOptions, $mTitle, $mOutputType,
106 $mTemplates, // cache of already loaded templates, avoids
107 // multiple SQL queries for the same string
108 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
109 // in this path. Used for loop detection.
110
111 /**#@-*/
112
113 /**
114 * Constructor
115 *
116 * @access public
117 */
118 function Parser() {
119 $this->mTemplates = array();
120 $this->mTemplatePath = array();
121 $this->mTagHooks = array();
122 $this->clearState();
123 }
124
125 /**
126 * Clear Parser state
127 *
128 * @access private
129 */
130 function clearState() {
131 $this->mOutput = new ParserOutput;
132 $this->mAutonumber = 0;
133 $this->mLastSection = '';
134 $this->mDTopen = false;
135 $this->mVariables = false;
136 $this->mIncludeCount = array();
137 $this->mStripState = array();
138 $this->mArgStack = array();
139 $this->mInPre = false;
140 }
141
142 /**
143 * First pass--just handle <nowiki> sections, pass the rest off
144 * to internalParse() which does all the real work.
145 *
146 * @access private
147 * @param string $text Text we want to parse
148 * @param Title &$title A title object
149 * @param array $options
150 * @param boolean $linestart
151 * @param boolean $clearState
152 * @return ParserOutput a ParserOutput
153 */
154 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
155 global $wgUseTidy, $wgContLang;
156 $fname = 'Parser::parse';
157 wfProfileIn( $fname );
158
159 if ( $clearState ) {
160 $this->clearState();
161 }
162
163 $this->mOptions = $options;
164 $this->mTitle =& $title;
165 $this->mOutputType = OT_HTML;
166
167 $stripState = NULL;
168 global $fnord; $fnord = 1;
169 //$text = $this->strip( $text, $this->mStripState );
170 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
171 $x =& $this->mStripState;
172 $text = $this->strip( $text, $x );
173
174 $text = $this->internalParse( $text, $linestart );
175
176 $dashReplace = array(
177 '/ - /' => "&nbsp;&ndash; ", # N dash
178 '/(?<=[0-9])-(?=[0-9])/' => "&ndash;", # N dash between numbers
179 '/ -- /' => "&nbsp;&mdash; " # M dash
180 );
181 $text = preg_replace( array_keys($dashReplace), array_values($dashReplace), $text );
182
183
184 $text = $this->unstrip( $text, $this->mStripState );
185 # Clean up special characters, only run once, next-to-last before doBlockLevels
186 global $wgUseTidy;
187 if(!$wgUseTidy) {
188 $fixtags = array(
189 # french spaces, last one Guillemet-left
190 # only if there is something before the space
191 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
192 # french spaces, Guillemet-right
193 '/(\\302\\253) /' => '\\1&nbsp;',
194 '/<hr *>/i' => '<hr />',
195 '/<br *>/i' => '<br />',
196 '/<center *>/i' => '<div class="center">',
197 '/<\\/center *>/i' => '</div>',
198 );
199 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
200 $text = Sanitizer::normalizeCharReferences( $text );
201 } else {
202 $fixtags = array(
203 # french spaces, last one Guillemet-left
204 '/ (\\?|:|;|!|\\302\\273)/' => '&nbsp;\\1',
205 # french spaces, Guillemet-right
206 '/(\\302\\253) /' => '\\1&nbsp;',
207 '/<center *>/i' => '<div class="center">',
208 '/<\\/center *>/i' => '</div>'
209 );
210 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
211 }
212 # only once and last
213 $text = $this->doBlockLevels( $text, $linestart );
214
215 $this->replaceLinkHolders( $text );
216 $text = $wgContLang->convert($text);
217
218 $text = $this->unstripNoWiki( $text, $this->mStripState );
219 if ($wgUseTidy) {
220 $text = Parser::tidy($text);
221 }
222
223 $this->mOutput->setText( $text );
224 wfProfileOut( $fname );
225 return $this->mOutput;
226 }
227
228 /**
229 * Get a random string
230 *
231 * @access private
232 * @static
233 */
234 function getRandomString() {
235 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
236 }
237
238 /**
239 * Replaces all occurrences of <$tag>content</$tag> in the text
240 * with a random marker and returns the new text. the output parameter
241 * $content will be an associative array filled with data on the form
242 * $unique_marker => content.
243 *
244 * If $content is already set, the additional entries will be appended
245 * If $tag is set to STRIP_COMMENTS, the function will extract
246 * <!-- HTML comments -->
247 *
248 * @access private
249 * @static
250 */
251 function extractTags($tag, $text, &$content, $uniq_prefix = ''){
252 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
253 if ( !$content ) {
254 $content = array( );
255 }
256 $n = 1;
257 $stripped = '';
258
259 while ( '' != $text ) {
260 if($tag==STRIP_COMMENTS) {
261 $p = preg_split( '/<!--/', $text, 2 );
262 } else {
263 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
264 }
265 $stripped .= $p[0];
266 if ( ( count( $p ) < 2 ) || ( '' == $p[1] ) ) {
267 $text = '';
268 } else {
269 if($tag==STRIP_COMMENTS) {
270 $q = preg_split( '/-->/i', $p[1], 2 );
271 } else {
272 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
273 }
274 $marker = $rnd . sprintf('%08X', $n++);
275 $content[$marker] = $q[0];
276 $stripped .= $marker;
277 $text = $q[1];
278 }
279 }
280 return $stripped;
281 }
282
283 /**
284 * Strips and renders nowiki, pre, math, hiero
285 * If $render is set, performs necessary rendering operations on plugins
286 * Returns the text, and fills an array with data needed in unstrip()
287 * If the $state is already a valid strip state, it adds to the state
288 *
289 * @param bool $stripcomments when set, HTML comments <!-- like this -->
290 * will be stripped in addition to other tags. This is important
291 * for section editing, where these comments cause confusion when
292 * counting the sections in the wikisource
293 *
294 * @access private
295 */
296 function strip( $text, &$state, $stripcomments = false ) {
297 $render = ($this->mOutputType == OT_HTML);
298 $html_content = array();
299 $nowiki_content = array();
300 $math_content = array();
301 $pre_content = array();
302 $comment_content = array();
303 $ext_content = array();
304 $gallery_content = array();
305
306 # Replace any instances of the placeholders
307 $uniq_prefix = UNIQ_PREFIX;
308 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
309
310 # html
311 global $wgRawHtml, $wgWhitelistEdit;
312 if( $wgRawHtml && $wgWhitelistEdit ) {
313 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
314 foreach( $html_content as $marker => $content ) {
315 if ($render ) {
316 # Raw and unchecked for validity.
317 $html_content[$marker] = $content;
318 } else {
319 $html_content[$marker] = '<html>'.$content.'</html>';
320 }
321 }
322 }
323
324 # nowiki
325 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
326 foreach( $nowiki_content as $marker => $content ) {
327 if( $render ){
328 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
329 } else {
330 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
331 }
332 }
333
334 # math
335 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
336 foreach( $math_content as $marker => $content ){
337 if( $render ) {
338 if( $this->mOptions->getUseTeX() ) {
339 $math_content[$marker] = renderMath( $content );
340 } else {
341 $math_content[$marker] = '&lt;math&gt;'.$content.'&lt;math&gt;';
342 }
343 } else {
344 $math_content[$marker] = '<math>'.$content.'</math>';
345 }
346 }
347
348 # pre
349 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
350 foreach( $pre_content as $marker => $content ){
351 if( $render ){
352 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
353 } else {
354 $pre_content[$marker] = '<pre>'.$content.'</pre>';
355 }
356 }
357
358 # gallery
359 $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
360 foreach( $gallery_content as $marker => $content ) {
361 require_once( 'ImageGallery.php' );
362 if ( $render ) {
363 $gallery_content[$marker] = Parser::renderImageGallery( $content );
364 } else {
365 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
366 }
367 }
368
369 # Comments
370 if($stripcomments) {
371 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
372 foreach( $comment_content as $marker => $content ){
373 $comment_content[$marker] = '<!--'.$content.'-->';
374 }
375 }
376
377 # Extensions
378 foreach ( $this->mTagHooks as $tag => $callback ) {
379 $ext_contents[$tag] = array();
380 $text = Parser::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
381 foreach( $ext_content[$tag] as $marker => $content ) {
382 if ( $render ) {
383 $ext_content[$tag][$marker] = $callback( $content );
384 } else {
385 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
386 }
387 }
388 }
389
390 # Merge state with the pre-existing state, if there is one
391 if ( $state ) {
392 $state['html'] = $state['html'] + $html_content;
393 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
394 $state['math'] = $state['math'] + $math_content;
395 $state['pre'] = $state['pre'] + $pre_content;
396 $state['comment'] = $state['comment'] + $comment_content;
397 $state['gallery'] = $state['gallery'] + $gallery_content;
398
399 foreach( $ext_content as $tag => $array ) {
400 if ( array_key_exists( $tag, $state ) ) {
401 $state[$tag] = $state[$tag] + $array;
402 }
403 }
404 } else {
405 $state = array(
406 'html' => $html_content,
407 'nowiki' => $nowiki_content,
408 'math' => $math_content,
409 'pre' => $pre_content,
410 'comment' => $comment_content,
411 'gallery' => $gallery_content,
412 ) + $ext_content;
413 }
414 return $text;
415 }
416
417 /**
418 * restores pre, math, and hiero removed by strip()
419 *
420 * always call unstripNoWiki() after this one
421 * @access private
422 */
423 function unstrip( $text, &$state ) {
424 # Must expand in reverse order, otherwise nested tags will be corrupted
425 $contentDict = end( $state );
426 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
427 if( key($state) != 'nowiki' && key($state) != 'html') {
428 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
429 $text = str_replace( key( $contentDict ), $content, $text );
430 }
431 }
432 }
433
434 return $text;
435 }
436
437 /**
438 * always call this after unstrip() to preserve the order
439 *
440 * @access private
441 */
442 function unstripNoWiki( $text, &$state ) {
443 # Must expand in reverse order, otherwise nested tags will be corrupted
444 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
445 $text = str_replace( key( $state['nowiki'] ), $content, $text );
446 }
447
448 global $wgRawHtml;
449 if ($wgRawHtml) {
450 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
451 $text = str_replace( key( $state['html'] ), $content, $text );
452 }
453 }
454
455 return $text;
456 }
457
458 /**
459 * Add an item to the strip state
460 * Returns the unique tag which must be inserted into the stripped text
461 * The tag will be replaced with the original text in unstrip()
462 *
463 * @access private
464 */
465 function insertStripItem( $text, &$state ) {
466 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
467 if ( !$state ) {
468 $state = array(
469 'html' => array(),
470 'nowiki' => array(),
471 'math' => array(),
472 'pre' => array()
473 );
474 }
475 $state['item'][$rnd] = $text;
476 return $rnd;
477 }
478
479 /**
480 * interface with html tidy, used if $wgUseTidy = true
481 *
482 * @access public
483 * @static
484 */
485 function tidy ( $text ) {
486 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
487 $fname = 'Parser::tidy';
488 wfProfileIn( $fname );
489
490 $cleansource = '';
491 $opts = ' -utf8';
492
493 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
494 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
495 '<head><title>test</title></head><body>'.$text.'</body></html>';
496 $descriptorspec = array(
497 0 => array('pipe', 'r'),
498 1 => array('pipe', 'w'),
499 2 => array('file', '/dev/null', 'a')
500 );
501 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
502 if (is_resource($process)) {
503 fwrite($pipes[0], $wrappedtext);
504 fclose($pipes[0]);
505 while (!feof($pipes[1])) {
506 $cleansource .= fgets($pipes[1], 1024);
507 }
508 fclose($pipes[1]);
509 $return_value = proc_close($process);
510 }
511
512 wfProfileOut( $fname );
513
514 if( $cleansource == '' && $text != '') {
515 wfDebug( "Tidy error detected!\n" );
516 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
517 } else {
518 return $cleansource;
519 }
520 }
521
522 /**
523 * parse the wiki syntax used to render tables
524 *
525 * @access private
526 */
527 function doTableStuff ( $t ) {
528 $fname = 'Parser::doTableStuff';
529 wfProfileIn( $fname );
530
531 $t = explode ( "\n" , $t ) ;
532 $td = array () ; # Is currently a td tag open?
533 $ltd = array () ; # Was it TD or TH?
534 $tr = array () ; # Is currently a tr tag open?
535 $ltr = array () ; # tr attributes
536 $indent_level = 0; # indent level of the table
537 foreach ( $t AS $k => $x )
538 {
539 $x = trim ( $x ) ;
540 $fc = substr ( $x , 0 , 1 ) ;
541 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
542 $indent_level = strlen( $matches[1] );
543 $t[$k] = "\n" .
544 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) . "\n";
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 # fix up urlencoded title texts
1155 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1156 $trail = $m[3];
1157 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1158 $might_be_img = true;
1159 $text = $m[2];
1160 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1161 $trail = "";
1162 } else { # Invalid form; output directly
1163 $s .= $prefix . '[[' . $line ;
1164 continue;
1165 }
1166
1167 # Don't allow internal links to pages containing
1168 # PROTO: where PROTO is a valid URL protocol; these
1169 # should be external links.
1170 if (preg_match('/^(\b(?:'.URL_PROTOCOLS.'):)/', $m[1])) {
1171 $s .= $prefix . '[[' . $line ;
1172 continue;
1173 }
1174
1175 # Make subpage if necessary
1176 if( $useSubpages ) {
1177 $link = $this->maybeDoSubpageLink( $m[1], $text );
1178 } else {
1179 $link = $m[1];
1180 }
1181
1182 $noforce = (substr($m[1], 0, 1) != ':');
1183 if (!$noforce) {
1184 # Strip off leading ':'
1185 $link = substr($link, 1);
1186 }
1187
1188 $nt =& Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1189 if( !$nt ) {
1190 $s .= $prefix . '[[' . $line;
1191 continue;
1192 }
1193
1194 #check other language variants of the link
1195 #if the article does not exist
1196 if( $checkVariantLink
1197 && $nt->getArticleID() == 0 ) {
1198 $wgContLang->findVariantLink($link, $nt);
1199 }
1200
1201 $ns = $nt->getNamespace();
1202 $iw = $nt->getInterWiki();
1203
1204 if ($might_be_img) { # if this is actually an invalid link
1205 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1206 $found = false;
1207 while (isset ($a[$k+1]) ) {
1208 #look at the next 'line' to see if we can close it there
1209 $next_line = array_shift(array_splice( $a, $k + 1, 1) );
1210 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1211 # the first ]] closes the inner link, the second the image
1212 $found = true;
1213 $text .= '[[' . $m[1];
1214 $trail = $m[2];
1215 break;
1216 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1217 #if there's exactly one ]] that's fine, we'll keep looking
1218 $text .= '[[' . $m[0];
1219 } else {
1220 #if $next_line is invalid too, we need look no further
1221 $text .= '[[' . $next_line;
1222 break;
1223 }
1224 }
1225 if ( !$found ) {
1226 # we couldn't find the end of this imageLink, so output it raw
1227 #but don't ignore what might be perfectly normal links in the text we've examined
1228 $text = $this->replaceInternalLinks($text);
1229 $s .= $prefix . '[[' . $link . '|' . $text;
1230 # note: no $trail, because without an end, there *is* no trail
1231 continue;
1232 }
1233 } else { #it's not an image, so output it raw
1234 $s .= $prefix . '[[' . $link . '|' . $text;
1235 # note: no $trail, because without an end, there *is* no trail
1236 continue;
1237 }
1238 }
1239
1240 $wasblank = ( '' == $text );
1241 if( $wasblank ) $text = $link;
1242
1243
1244 # Link not escaped by : , create the various objects
1245 if( $noforce ) {
1246
1247 # Interwikis
1248 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1249 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1250 $tmp = $prefix . $trail ;
1251 $s .= (trim($tmp) == '')? '': $tmp;
1252 continue;
1253 }
1254
1255 if ( $ns == NS_IMAGE ) {
1256 wfProfileIn( "$fname-image" );
1257
1258 # recursively parse links inside the image caption
1259 # actually, this will parse them in any other parameters, too,
1260 # but it might be hard to fix that, and it doesn't matter ATM
1261 $text = $this->replaceExternalLinks($text);
1262 $text = $this->replaceInternalLinks($text);
1263
1264 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1265 $s .= $prefix . str_replace('http://', 'http-noparse://', $sk->makeImageLinkObj( $nt, $text ) ) . $trail;
1266 $wgLinkCache->addImageLinkObj( $nt );
1267
1268 wfProfileOut( "$fname-image" );
1269 continue;
1270 }
1271
1272 if ( $ns == NS_CATEGORY ) {
1273 wfProfileIn( "$fname-category" );
1274 $t = $nt->getText();
1275
1276 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1277 $pPLC=$sk->postParseLinkColour();
1278 $sk->postParseLinkColour( false );
1279 $t = $sk->makeLinkObj( $nt, $t, '', '' , $prefix );
1280 $sk->postParseLinkColour( $pPLC );
1281 $wgLinkCache->resume();
1282
1283 if ( $wasblank ) {
1284 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1285 $sortkey = $this->mTitle->getText();
1286 } else {
1287 $sortkey = $this->mTitle->getPrefixedText();
1288 }
1289 } else {
1290 $sortkey = $text;
1291 }
1292 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1293 $this->mOutput->addCategoryLink( $t );
1294 $s .= $prefix . $trail ;
1295
1296 wfProfileOut( "$fname-category" );
1297 continue;
1298 }
1299 }
1300
1301 if( ( $nt->getPrefixedText() === $selflink ) &&
1302 ( $nt->getFragment() === '' ) ) {
1303 # Self-links are handled specially; generally de-link and change to bold.
1304 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1305 continue;
1306 }
1307
1308 # Special and Media are pseudo-namespaces; no pages actually exist in them
1309 if( $ns == NS_MEDIA ) {
1310 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text, true ) . $trail;
1311 $wgLinkCache->addImageLinkObj( $nt );
1312 continue;
1313 } elseif( $ns == NS_SPECIAL ) {
1314 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1315 continue;
1316 }
1317 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1318 }
1319 $sk->postParseLinkColour( $saveParseColour );
1320 wfProfileOut( $fname );
1321 return $s;
1322 }
1323
1324 /**
1325 * Return true if subpage links should be expanded on this page.
1326 * @return bool
1327 */
1328 function areSubpagesAllowed() {
1329 # Some namespaces don't allow subpages
1330 global $wgNamespacesWithSubpages;
1331 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1332 }
1333
1334 /**
1335 * Handle link to subpage if necessary
1336 * @param string $target the source of the link
1337 * @param string &$text the link text, modified as necessary
1338 * @return string the full name of the link
1339 * @access private
1340 */
1341 function maybeDoSubpageLink($target, &$text) {
1342 # Valid link forms:
1343 # Foobar -- normal
1344 # :Foobar -- override special treatment of prefix (images, language links)
1345 # /Foobar -- convert to CurrentPage/Foobar
1346 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1347 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1348 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1349
1350 $fname = 'Parser::maybeDoSubpageLink';
1351 wfProfileIn( $fname );
1352 $ret = $target; # default return value is no change
1353
1354 # Some namespaces don't allow subpages,
1355 # so only perform processing if subpages are allowed
1356 if( $this->areSubpagesAllowed() ) {
1357 # Look at the first character
1358 if( $target != '' && $target{0} == '/' ) {
1359 # / at end means we don't want the slash to be shown
1360 if( substr( $target, -1, 1 ) == '/' ) {
1361 $target = substr( $target, 1, -1 );
1362 $noslash = $target;
1363 } else {
1364 $noslash = substr( $target, 1 );
1365 }
1366
1367 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1368 if( '' === $text ) {
1369 $text = $target;
1370 } # this might be changed for ugliness reasons
1371 } else {
1372 # check for .. subpage backlinks
1373 $dotdotcount = 0;
1374 $nodotdot = $target;
1375 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1376 ++$dotdotcount;
1377 $nodotdot = substr( $nodotdot, 3 );
1378 }
1379 if($dotdotcount > 0) {
1380 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1381 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1382 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1383 # / at the end means don't show full path
1384 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1385 $nodotdot = substr( $nodotdot, 0, -1 );
1386 if( '' === $text ) {
1387 $text = $nodotdot;
1388 }
1389 }
1390 $nodotdot = trim( $nodotdot );
1391 if( $nodotdot != '' ) {
1392 $ret .= '/' . $nodotdot;
1393 }
1394 }
1395 }
1396 }
1397 }
1398
1399 wfProfileOut( $fname );
1400 return $ret;
1401 }
1402
1403 /**#@+
1404 * Used by doBlockLevels()
1405 * @access private
1406 */
1407 /* private */ function closeParagraph() {
1408 $result = '';
1409 if ( '' != $this->mLastSection ) {
1410 $result = '</' . $this->mLastSection . ">\n";
1411 }
1412 $this->mInPre = false;
1413 $this->mLastSection = '';
1414 return $result;
1415 }
1416 # getCommon() returns the length of the longest common substring
1417 # of both arguments, starting at the beginning of both.
1418 #
1419 /* private */ function getCommon( $st1, $st2 ) {
1420 $fl = strlen( $st1 );
1421 $shorter = strlen( $st2 );
1422 if ( $fl < $shorter ) { $shorter = $fl; }
1423
1424 for ( $i = 0; $i < $shorter; ++$i ) {
1425 if ( $st1{$i} != $st2{$i} ) { break; }
1426 }
1427 return $i;
1428 }
1429 # These next three functions open, continue, and close the list
1430 # element appropriate to the prefix character passed into them.
1431 #
1432 /* private */ function openList( $char ) {
1433 $result = $this->closeParagraph();
1434
1435 if ( '*' == $char ) { $result .= '<ul><li>'; }
1436 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1437 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1438 else if ( ';' == $char ) {
1439 $result .= '<dl><dt>';
1440 $this->mDTopen = true;
1441 }
1442 else { $result = '<!-- ERR 1 -->'; }
1443
1444 return $result;
1445 }
1446
1447 /* private */ function nextItem( $char ) {
1448 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1449 else if ( ':' == $char || ';' == $char ) {
1450 $close = '</dd>';
1451 if ( $this->mDTopen ) { $close = '</dt>'; }
1452 if ( ';' == $char ) {
1453 $this->mDTopen = true;
1454 return $close . '<dt>';
1455 } else {
1456 $this->mDTopen = false;
1457 return $close . '<dd>';
1458 }
1459 }
1460 return '<!-- ERR 2 -->';
1461 }
1462
1463 /* private */ function closeList( $char ) {
1464 if ( '*' == $char ) { $text = '</li></ul>'; }
1465 else if ( '#' == $char ) { $text = '</li></ol>'; }
1466 else if ( ':' == $char ) {
1467 if ( $this->mDTopen ) {
1468 $this->mDTopen = false;
1469 $text = '</dt></dl>';
1470 } else {
1471 $text = '</dd></dl>';
1472 }
1473 }
1474 else { return '<!-- ERR 3 -->'; }
1475 return $text."\n";
1476 }
1477 /**#@-*/
1478
1479 /**
1480 * Make lists from lines starting with ':', '*', '#', etc.
1481 *
1482 * @access private
1483 * @return string the lists rendered as HTML
1484 */
1485 function doBlockLevels( $text, $linestart ) {
1486 $fname = 'Parser::doBlockLevels';
1487 wfProfileIn( $fname );
1488
1489 # Parsing through the text line by line. The main thing
1490 # happening here is handling of block-level elements p, pre,
1491 # and making lists from lines starting with * # : etc.
1492 #
1493 $textLines = explode( "\n", $text );
1494
1495 $lastPrefix = $output = $lastLine = '';
1496 $this->mDTopen = $inBlockElem = false;
1497 $prefixLength = 0;
1498 $paragraphStack = false;
1499
1500 if ( !$linestart ) {
1501 $output .= array_shift( $textLines );
1502 }
1503 foreach ( $textLines as $oLine ) {
1504 $lastPrefixLength = strlen( $lastPrefix );
1505 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1506 $preOpenMatch = preg_match('/<pre/i', $oLine );
1507 if ( !$this->mInPre ) {
1508 # Multiple prefixes may abut each other for nested lists.
1509 $prefixLength = strspn( $oLine, '*#:;' );
1510 $pref = substr( $oLine, 0, $prefixLength );
1511
1512 # eh?
1513 $pref2 = str_replace( ';', ':', $pref );
1514 $t = substr( $oLine, $prefixLength );
1515 $this->mInPre = !empty($preOpenMatch);
1516 } else {
1517 # Don't interpret any other prefixes in preformatted text
1518 $prefixLength = 0;
1519 $pref = $pref2 = '';
1520 $t = $oLine;
1521 }
1522
1523 # List generation
1524 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1525 # Same as the last item, so no need to deal with nesting or opening stuff
1526 $output .= $this->nextItem( substr( $pref, -1 ) );
1527 $paragraphStack = false;
1528
1529 if ( substr( $pref, -1 ) == ';') {
1530 # The one nasty exception: definition lists work like this:
1531 # ; title : definition text
1532 # So we check for : in the remainder text to split up the
1533 # title and definition, without b0rking links.
1534 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1535 $t = $t2;
1536 $output .= $term . $this->nextItem( ':' );
1537 }
1538 }
1539 } elseif( $prefixLength || $lastPrefixLength ) {
1540 # Either open or close a level...
1541 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1542 $paragraphStack = false;
1543
1544 while( $commonPrefixLength < $lastPrefixLength ) {
1545 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1546 --$lastPrefixLength;
1547 }
1548 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1549 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1550 }
1551 while ( $prefixLength > $commonPrefixLength ) {
1552 $char = substr( $pref, $commonPrefixLength, 1 );
1553 $output .= $this->openList( $char );
1554
1555 if ( ';' == $char ) {
1556 # FIXME: This is dupe of code above
1557 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1558 $t = $t2;
1559 $output .= $term . $this->nextItem( ':' );
1560 }
1561 }
1562 ++$commonPrefixLength;
1563 }
1564 $lastPrefix = $pref2;
1565 }
1566 if( 0 == $prefixLength ) {
1567 wfProfileIn( "$fname-paragraph" );
1568 # No prefix (not in list)--go to paragraph mode
1569 $uniq_prefix = UNIQ_PREFIX;
1570 // XXX: use a stack for nestable elements like span, table and div
1571 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1572 $closematch = preg_match(
1573 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1574 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1575 if ( $openmatch or $closematch ) {
1576 $paragraphStack = false;
1577 $output .= $this->closeParagraph();
1578 if($preOpenMatch and !$preCloseMatch) {
1579 $this->mInPre = true;
1580 }
1581 if ( $closematch ) {
1582 $inBlockElem = false;
1583 } else {
1584 $inBlockElem = true;
1585 }
1586 } else if ( !$inBlockElem && !$this->mInPre ) {
1587 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1588 // pre
1589 if ($this->mLastSection != 'pre') {
1590 $paragraphStack = false;
1591 $output .= $this->closeParagraph().'<pre>';
1592 $this->mLastSection = 'pre';
1593 }
1594 $t = substr( $t, 1 );
1595 } else {
1596 // paragraph
1597 if ( '' == trim($t) ) {
1598 if ( $paragraphStack ) {
1599 $output .= $paragraphStack.'<br />';
1600 $paragraphStack = false;
1601 $this->mLastSection = 'p';
1602 } else {
1603 if ($this->mLastSection != 'p' ) {
1604 $output .= $this->closeParagraph();
1605 $this->mLastSection = '';
1606 $paragraphStack = '<p>';
1607 } else {
1608 $paragraphStack = '</p><p>';
1609 }
1610 }
1611 } else {
1612 if ( $paragraphStack ) {
1613 $output .= $paragraphStack;
1614 $paragraphStack = false;
1615 $this->mLastSection = 'p';
1616 } else if ($this->mLastSection != 'p') {
1617 $output .= $this->closeParagraph().'<p>';
1618 $this->mLastSection = 'p';
1619 }
1620 }
1621 }
1622 }
1623 wfProfileOut( "$fname-paragraph" );
1624 }
1625 if ($paragraphStack === false) {
1626 $output .= $t."\n";
1627 }
1628 }
1629 while ( $prefixLength ) {
1630 $output .= $this->closeList( $pref2{$prefixLength-1} );
1631 --$prefixLength;
1632 }
1633 if ( '' != $this->mLastSection ) {
1634 $output .= '</' . $this->mLastSection . '>';
1635 $this->mLastSection = '';
1636 }
1637
1638 wfProfileOut( $fname );
1639 return $output;
1640 }
1641
1642 /**
1643 * Split up a string on ':', ignoring any occurences inside
1644 * <a>..</a> or <span>...</span>
1645 * @param string $str the string to split
1646 * @param string &$before set to everything before the ':'
1647 * @param string &$after set to everything after the ':'
1648 * return string the position of the ':', or false if none found
1649 */
1650 function findColonNoLinks($str, &$before, &$after) {
1651 # I wonder if we should make this count all tags, not just <a>
1652 # and <span>. That would prevent us from matching a ':' that
1653 # comes in the middle of italics other such formatting....
1654 # -- Wil
1655 $fname = 'Parser::findColonNoLinks';
1656 wfProfileIn( $fname );
1657 $pos = 0;
1658 do {
1659 $colon = strpos($str, ':', $pos);
1660
1661 if ($colon !== false) {
1662 $before = substr($str, 0, $colon);
1663 $after = substr($str, $colon + 1);
1664
1665 # Skip any ':' within <a> or <span> pairs
1666 $a = substr_count($before, '<a');
1667 $s = substr_count($before, '<span');
1668 $ca = substr_count($before, '</a>');
1669 $cs = substr_count($before, '</span>');
1670
1671 if ($a <= $ca and $s <= $cs) {
1672 # Tags are balanced before ':'; ok
1673 break;
1674 }
1675 $pos = $colon + 1;
1676 }
1677 } while ($colon !== false);
1678 wfProfileOut( $fname );
1679 return $colon;
1680 }
1681
1682 /**
1683 * Return value of a magic variable (like PAGENAME)
1684 *
1685 * @access private
1686 */
1687 function getVariableValue( $index ) {
1688 global $wgContLang, $wgSitename, $wgServer, $wgArticle;
1689
1690 /**
1691 * Some of these require message or data lookups and can be
1692 * expensive to check many times.
1693 */
1694 static $varCache = array();
1695 if( isset( $varCache[$index] ) ) return $varCache[$index];
1696
1697 switch ( $index ) {
1698 case MAG_CURRENTMONTH:
1699 return $varCache[$index] = $wgContLang->formatNum( date( 'm' ) );
1700 case MAG_CURRENTMONTHNAME:
1701 return $varCache[$index] = $wgContLang->getMonthName( date('n') );
1702 case MAG_CURRENTMONTHNAMEGEN:
1703 return $varCache[$index] = $wgContLang->getMonthNameGen( date('n') );
1704 case MAG_CURRENTMONTHABBREV:
1705 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date('n') );
1706 case MAG_CURRENTDAY:
1707 return $varCache[$index] = $wgContLang->formatNum( date('j') );
1708 case MAG_PAGENAME:
1709 return $this->mTitle->getText();
1710 case MAG_PAGENAMEE:
1711 return $this->mTitle->getPartialURL();
1712 case MAG_REVISIONID:
1713 return $wgArticle->getRevIdFetched();
1714 case MAG_NAMESPACE:
1715 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1716 return $wgContLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1717 case MAG_CURRENTDAYNAME:
1718 return $varCache[$index] = $wgContLang->getWeekdayName( date('w')+1 );
1719 case MAG_CURRENTYEAR:
1720 return $varCache[$index] = $wgContLang->formatNum( date( 'Y' ) );
1721 case MAG_CURRENTTIME:
1722 return $varCache[$index] = $wgContLang->time( wfTimestampNow(), false );
1723 case MAG_CURRENTWEEK:
1724 return $varCache[$index] = $wgContLang->formatNum( date('W') );
1725 case MAG_CURRENTDOW:
1726 return $varCache[$index] = $wgContLang->formatNum( date('w') );
1727 case MAG_NUMBEROFARTICLES:
1728 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
1729 case MAG_SITENAME:
1730 return $wgSitename;
1731 case MAG_SERVER:
1732 return $wgServer;
1733 default:
1734 return NULL;
1735 }
1736 }
1737
1738 /**
1739 * initialise the magic variables (like CURRENTMONTHNAME)
1740 *
1741 * @access private
1742 */
1743 function initialiseVariables() {
1744 $fname = 'Parser::initialiseVariables';
1745 wfProfileIn( $fname );
1746 global $wgVariableIDs;
1747 $this->mVariables = array();
1748 foreach ( $wgVariableIDs as $id ) {
1749 $mw =& MagicWord::get( $id );
1750 $mw->addToArray( $this->mVariables, $id );
1751 }
1752 wfProfileOut( $fname );
1753 }
1754
1755 /**
1756 * Replace magic variables, templates, and template arguments
1757 * with the appropriate text. Templates are substituted recursively,
1758 * taking care to avoid infinite loops.
1759 *
1760 * Note that the substitution depends on value of $mOutputType:
1761 * OT_WIKI: only {{subst:}} templates
1762 * OT_MSG: only magic variables
1763 * OT_HTML: all templates and magic variables
1764 *
1765 * @param string $tex The text to transform
1766 * @param array $args Key-value pairs representing template parameters to substitute
1767 * @access private
1768 */
1769 function replaceVariables( $text, $args = array() ) {
1770 global $wgLang, $wgScript, $wgArticlePath;
1771
1772 # Prevent too big inclusions
1773 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
1774 return $text;
1775 }
1776
1777 $fname = 'Parser::replaceVariables';
1778 wfProfileIn( $fname );
1779
1780 $titleChars = Title::legalChars();
1781
1782 # This function is called recursively. To keep track of arguments we need a stack:
1783 array_push( $this->mArgStack, $args );
1784
1785 # Variable substitution
1786 $text = preg_replace_callback( "/{{([$titleChars]*?)}}/", array( &$this, 'variableSubstitution' ), $text );
1787
1788 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
1789 # Argument substitution
1790 $text = preg_replace_callback( "/{{{([$titleChars]*?)}}}/", array( &$this, 'argSubstitution' ), $text );
1791 }
1792 # Template substitution
1793 $regex = '/(\\n|{)?{{(['.$titleChars.']*)(\\|.*?|)}}/s';
1794 $text = preg_replace_callback( $regex, array( &$this, 'braceSubstitution' ), $text );
1795
1796 array_pop( $this->mArgStack );
1797
1798 wfProfileOut( $fname );
1799 return $text;
1800 }
1801
1802 /**
1803 * Replace magic variables
1804 * @access private
1805 */
1806 function variableSubstitution( $matches ) {
1807 $fname = 'parser::variableSubstitution';
1808 $varname = $matches[1];
1809 wfProfileIn( $fname );
1810 if ( !$this->mVariables ) {
1811 $this->initialiseVariables();
1812 }
1813 $skip = false;
1814 if ( $this->mOutputType == OT_WIKI ) {
1815 # Do only magic variables prefixed by SUBST
1816 $mwSubst =& MagicWord::get( MAG_SUBST );
1817 if (!$mwSubst->matchStartAndRemove( $varname ))
1818 $skip = true;
1819 # Note that if we don't substitute the variable below,
1820 # we don't remove the {{subst:}} magic word, in case
1821 # it is a template rather than a magic variable.
1822 }
1823 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
1824 $id = $this->mVariables[$varname];
1825 $text = $this->getVariableValue( $id );
1826 $this->mOutput->mContainsOldMagic = true;
1827 } else {
1828 $text = $matches[0];
1829 }
1830 wfProfileOut( $fname );
1831 return $text;
1832 }
1833
1834 # Split template arguments
1835 function getTemplateArgs( $argsString ) {
1836 if ( $argsString === '' ) {
1837 return array();
1838 }
1839
1840 $args = explode( '|', substr( $argsString, 1 ) );
1841
1842 # If any of the arguments contains a '[[' but no ']]', it needs to be
1843 # merged with the next arg because the '|' character between belongs
1844 # to the link syntax and not the template parameter syntax.
1845 $argc = count($args);
1846 $i = 0;
1847 for ( $i = 0; $i < $argc-1; $i++ ) {
1848 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
1849 $args[$i] .= '|'.$args[$i+1];
1850 array_splice($args, $i+1, 1);
1851 $i--;
1852 $argc--;
1853 }
1854 }
1855
1856 return $args;
1857 }
1858
1859 /**
1860 * Return the text of a template, after recursively
1861 * replacing any variables or templates within the template.
1862 *
1863 * @param array $matches The parts of the template
1864 * $matches[1]: the title, i.e. the part before the |
1865 * $matches[2]: the parameters (including a leading |), if any
1866 * @return string the text of the template
1867 * @access private
1868 */
1869 function braceSubstitution( $matches ) {
1870 global $wgLinkCache, $wgContLang;
1871 $fname = 'Parser::braceSubstitution';
1872 wfProfileIn( $fname );
1873
1874 $found = false;
1875 $nowiki = false;
1876 $noparse = false;
1877
1878 $title = NULL;
1879
1880 # Need to know if the template comes at the start of a line,
1881 # to treat the beginning of the template like the beginning
1882 # of a line for tables and block-level elements.
1883 $linestart = $matches[1];
1884
1885 # $part1 is the bit before the first |, and must contain only title characters
1886 # $args is a list of arguments, starting from index 0, not including $part1
1887
1888 $part1 = $matches[2];
1889 # If the third subpattern matched anything, it will start with |
1890
1891 $args = $this->getTemplateArgs($matches[3]);
1892 $argc = count( $args );
1893
1894 # Don't parse {{{}}} because that's only for template arguments
1895 if ( $linestart === '{' ) {
1896 $text = $matches[0];
1897 $found = true;
1898 $noparse = true;
1899 }
1900
1901 # SUBST
1902 if ( !$found ) {
1903 $mwSubst =& MagicWord::get( MAG_SUBST );
1904 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
1905 # One of two possibilities is true:
1906 # 1) Found SUBST but not in the PST phase
1907 # 2) Didn't find SUBST and in the PST phase
1908 # In either case, return without further processing
1909 $text = $matches[0];
1910 $found = true;
1911 $noparse = true;
1912 }
1913 }
1914
1915 # MSG, MSGNW and INT
1916 if ( !$found ) {
1917 # Check for MSGNW:
1918 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1919 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1920 $nowiki = true;
1921 } else {
1922 # Remove obsolete MSG:
1923 $mwMsg =& MagicWord::get( MAG_MSG );
1924 $mwMsg->matchStartAndRemove( $part1 );
1925 }
1926
1927 # Check if it is an internal message
1928 $mwInt =& MagicWord::get( MAG_INT );
1929 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1930 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1931 $text = $linestart . wfMsgReal( $part1, $args, true );
1932 $found = true;
1933 }
1934 }
1935 }
1936
1937 # NS
1938 if ( !$found ) {
1939 # Check for NS: (namespace expansion)
1940 $mwNs = MagicWord::get( MAG_NS );
1941 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1942 if ( intval( $part1 ) ) {
1943 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
1944 $found = true;
1945 } else {
1946 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1947 if ( !is_null( $index ) ) {
1948 $text = $linestart . $wgContLang->getNsText( $index );
1949 $found = true;
1950 }
1951 }
1952 }
1953 }
1954
1955 # LOCALURL and LOCALURLE
1956 if ( !$found ) {
1957 $mwLocal = MagicWord::get( MAG_LOCALURL );
1958 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1959
1960 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1961 $func = 'getLocalURL';
1962 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1963 $func = 'escapeLocalURL';
1964 } else {
1965 $func = '';
1966 }
1967
1968 if ( $func !== '' ) {
1969 $title = Title::newFromText( $part1 );
1970 if ( !is_null( $title ) ) {
1971 if ( $argc > 0 ) {
1972 $text = $linestart . $title->$func( $args[0] );
1973 } else {
1974 $text = $linestart . $title->$func();
1975 }
1976 $found = true;
1977 }
1978 }
1979 }
1980
1981 # GRAMMAR
1982 if ( !$found && $argc == 1 ) {
1983 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
1984 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
1985 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
1986 $found = true;
1987 }
1988 }
1989
1990 # Template table test
1991
1992 # Did we encounter this template already? If yes, it is in the cache
1993 # and we need to check for loops.
1994 if ( !$found && isset( $this->mTemplates[$part1] ) ) {
1995 $found = true;
1996
1997 # Infinite loop test
1998 if ( isset( $this->mTemplatePath[$part1] ) ) {
1999 $noparse = true;
2000 $found = true;
2001 $text = $linestart .
2002 "\{\{$part1}}" .
2003 '<!-- WARNING: template loop detected -->';
2004 wfDebug( "$fname: template loop broken at '$part1'\n" );
2005 } else {
2006 # set $text to cached message.
2007 $text = $linestart . $this->mTemplates[$part1];
2008 }
2009 }
2010
2011 # Load from database
2012 $itcamefromthedatabase = false;
2013 $lastPathLevel = $this->mTemplatePath;
2014 if ( !$found ) {
2015 $ns = NS_TEMPLATE;
2016 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2017 if ($subpage !== '') {
2018 $ns = $this->mTitle->getNamespace();
2019 }
2020 $title = Title::newFromText( $part1, $ns );
2021 if ( !is_null( $title ) && !$title->isExternal() ) {
2022 # Check for excessive inclusion
2023 $dbk = $title->getPrefixedDBkey();
2024 if ( $this->incrementIncludeCount( $dbk ) ) {
2025 # This should never be reached.
2026 $article = new Article( $title );
2027 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
2028 if ( $articleContent !== false ) {
2029 $found = true;
2030 $text = $linestart . $articleContent;
2031 $itcamefromthedatabase = true;
2032 }
2033 }
2034
2035 # If the title is valid but undisplayable, make a link to it
2036 if ( $this->mOutputType == OT_HTML && !$found ) {
2037 $text = $linestart . '[['.$title->getPrefixedText().']]';
2038 $found = true;
2039 }
2040
2041 # Template cache array insertion
2042 if( $found ) {
2043 $this->mTemplates[$part1] = $text;
2044 }
2045 }
2046 }
2047
2048 # Recursive parsing, escaping and link table handling
2049 # Only for HTML output
2050 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2051 $text = wfEscapeWikiText( $text );
2052 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found && !$noparse) {
2053 # Clean up argument array
2054 $assocArgs = array();
2055 $index = 1;
2056 foreach( $args as $arg ) {
2057 $eqpos = strpos( $arg, '=' );
2058 if ( $eqpos === false ) {
2059 $assocArgs[$index++] = $arg;
2060 } else {
2061 $name = trim( substr( $arg, 0, $eqpos ) );
2062 $value = trim( substr( $arg, $eqpos+1 ) );
2063 if ( $value === false ) {
2064 $value = '';
2065 }
2066 if ( $name !== false ) {
2067 $assocArgs[$name] = $value;
2068 }
2069 }
2070 }
2071
2072 # Add a new element to the templace recursion path
2073 $this->mTemplatePath[$part1] = 1;
2074
2075 $text = $this->strip( $text, $this->mStripState );
2076 $text = Sanitizer::removeHTMLtags( $text );
2077 $text = $this->replaceVariables( $text, $assocArgs );
2078
2079 # Resume the link cache and register the inclusion as a link
2080 if ( $this->mOutputType == OT_HTML && !is_null( $title ) ) {
2081 $wgLinkCache->addLinkObj( $title );
2082 }
2083
2084 # If the template begins with a table or block-level
2085 # element, it should be treated as beginning a new line.
2086 if ($linestart !== '\n' && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2087 $text = "\n" . $text;
2088 }
2089 }
2090 # Prune lower levels off the recursion check path
2091 $this->mTemplatePath = $lastPathLevel;
2092
2093 if ( !$found ) {
2094 wfProfileOut( $fname );
2095 return $matches[0];
2096 } else {
2097 # replace ==section headers==
2098 # XXX this needs to go away once we have a better parser.
2099 if ( $this->mOutputType != OT_WIKI && $itcamefromthedatabase ) {
2100 if( !is_null( $title ) )
2101 $encodedname = base64_encode($title->getPrefixedDBkey());
2102 else
2103 $encodedname = base64_encode("");
2104 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2105 PREG_SPLIT_DELIM_CAPTURE);
2106 $text = '';
2107 $nsec = 0;
2108 for( $i = 0; $i < count($m); $i += 2 ) {
2109 $text .= $m[$i];
2110 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2111 $hl = $m[$i + 1];
2112 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2113 $text .= $hl;
2114 continue;
2115 }
2116 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2117 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2118 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2119
2120 $nsec++;
2121 }
2122 }
2123 }
2124 # Prune lower levels off the recursion check path
2125 $this->mTemplatePath = $lastPathLevel;
2126
2127 if ( !$found ) {
2128 wfProfileOut( $fname );
2129 return $matches[0];
2130 } else {
2131 wfProfileOut( $fname );
2132 return $text;
2133 }
2134 }
2135
2136 /**
2137 * Triple brace replacement -- used for template arguments
2138 * @access private
2139 */
2140 function argSubstitution( $matches ) {
2141 $arg = trim( $matches[1] );
2142 $text = $matches[0];
2143 $inputArgs = end( $this->mArgStack );
2144
2145 if ( array_key_exists( $arg, $inputArgs ) ) {
2146 $text = $inputArgs[$arg];
2147 }
2148
2149 return $text;
2150 }
2151
2152 /**
2153 * Returns true if the function is allowed to include this entity
2154 * @access private
2155 */
2156 function incrementIncludeCount( $dbk ) {
2157 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2158 $this->mIncludeCount[$dbk] = 0;
2159 }
2160 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2161 return true;
2162 } else {
2163 return false;
2164 }
2165 }
2166
2167 /**
2168 * This function accomplishes several tasks:
2169 * 1) Auto-number headings if that option is enabled
2170 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2171 * 3) Add a Table of contents on the top for users who have enabled the option
2172 * 4) Auto-anchor headings
2173 *
2174 * It loops through all headlines, collects the necessary data, then splits up the
2175 * string and re-inserts the newly formatted headlines.
2176 *
2177 * @param string $text
2178 * @param boolean $isMain
2179 * @access private
2180 */
2181 function formatHeadings( $text, $isMain=true ) {
2182 global $wgInputEncoding, $wgMaxTocLevel, $wgContLang, $wgLinkHolders, $wgInterwikiLinkHolders;
2183
2184 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2185 $doShowToc = true;
2186 $forceTocHere = false;
2187 if( !$this->mTitle->userCanEdit() ) {
2188 $showEditLink = 0;
2189 } else {
2190 $showEditLink = $this->mOptions->getEditSection();
2191 }
2192
2193 # Inhibit editsection links if requested in the page
2194 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2195 if( $esw->matchAndRemove( $text ) ) {
2196 $showEditLink = 0;
2197 }
2198 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2199 # do not add TOC
2200 $mw =& MagicWord::get( MAG_NOTOC );
2201 if( $mw->matchAndRemove( $text ) ) {
2202 $doShowToc = false;
2203 }
2204
2205 # Get all headlines for numbering them and adding funky stuff like [edit]
2206 # links - this is for later, but we need the number of headlines right now
2207 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2208
2209 # if there are fewer than 4 headlines in the article, do not show TOC
2210 if( $numMatches < 4 ) {
2211 $doShowToc = false;
2212 }
2213
2214 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2215 # override above conditions and always show TOC at that place
2216
2217 $mw =& MagicWord::get( MAG_TOC );
2218 if($mw->match( $text ) ) {
2219 $doShowToc = true;
2220 $forceTocHere = true;
2221 } else {
2222 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2223 # override above conditions and always show TOC above first header
2224 $mw =& MagicWord::get( MAG_FORCETOC );
2225 if ($mw->matchAndRemove( $text ) ) {
2226 $doShowToc = true;
2227 }
2228 }
2229
2230 # Never ever show TOC if no headers
2231 if( $numMatches < 1 ) {
2232 $doShowToc = false;
2233 }
2234
2235 # We need this to perform operations on the HTML
2236 $sk =& $this->mOptions->getSkin();
2237
2238 # headline counter
2239 $headlineCount = 0;
2240 $sectionCount = 0; # headlineCount excluding template sections
2241
2242 # Ugh .. the TOC should have neat indentation levels which can be
2243 # passed to the skin functions. These are determined here
2244 $toc = '';
2245 $full = '';
2246 $head = array();
2247 $sublevelCount = array();
2248 $levelCount = array();
2249 $toclevel = 0;
2250 $level = 0;
2251 $prevlevel = 0;
2252 $toclevel = 0;
2253 $prevtoclevel = 0;
2254
2255 foreach( $matches[3] as $headline ) {
2256 $istemplate = 0;
2257 $templatetitle = '';
2258 $templatesection = 0;
2259 $numbering = '';
2260
2261 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2262 $istemplate = 1;
2263 $templatetitle = base64_decode($mat[1]);
2264 $templatesection = 1 + (int)base64_decode($mat[2]);
2265 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2266 }
2267
2268 if( $toclevel ) {
2269 $prevlevel = $level;
2270 $prevtoclevel = $toclevel;
2271 }
2272 $level = $matches[1][$headlineCount];
2273
2274 if( $doNumberHeadings || $doShowToc ) {
2275
2276 if ( $level > $prevlevel ) {
2277 # Increase TOC level
2278 $toclevel++;
2279 $sublevelCount[$toclevel] = 0;
2280 $toc .= $sk->tocIndent();
2281 }
2282 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2283 # Decrease TOC level, find level to jump to
2284
2285 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2286 # Can only go down to level 1
2287 $toclevel = 1;
2288 } else {
2289 for ($i = $toclevel; $i > 0; $i--) {
2290 if ( $levelCount[$i] == $level ) {
2291 # Found last matching level
2292 $toclevel = $i;
2293 break;
2294 }
2295 elseif ( $levelCount[$i] < $level ) {
2296 # Found first matching level below current level
2297 $toclevel = $i + 1;
2298 break;
2299 }
2300 }
2301 }
2302
2303 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2304 }
2305 else {
2306 # No change in level, end TOC line
2307 $toc .= $sk->tocLineEnd();
2308 }
2309
2310 $levelCount[$toclevel] = $level;
2311
2312 # count number of headlines for each level
2313 @$sublevelCount[$toclevel]++;
2314 $dot = 0;
2315 for( $i = 1; $i <= $toclevel; $i++ ) {
2316 if( !empty( $sublevelCount[$i] ) ) {
2317 if( $dot ) {
2318 $numbering .= '.';
2319 }
2320 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2321 $dot = 1;
2322 }
2323 }
2324 }
2325
2326 # The canonized header is a version of the header text safe to use for links
2327 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2328 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2329 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2330
2331 # Remove link placeholders by the link text.
2332 # <!--LINK number-->
2333 # turns into
2334 # link text with suffix
2335 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2336 "\$wgLinkHolders['texts'][\$1]",
2337 $canonized_headline );
2338 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
2339 "\$wgInterwikiLinkHolders[\$1]",
2340 $canonized_headline );
2341
2342 # strip out HTML
2343 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2344 $tocline = trim( $canonized_headline );
2345 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
2346 $replacearray = array(
2347 '%3A' => ':',
2348 '%' => '.'
2349 );
2350 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2351 $refer[$headlineCount] = $canonized_headline;
2352
2353 # count how many in assoc. array so we can track dupes in anchors
2354 @$refers[$canonized_headline]++;
2355 $refcount[$headlineCount]=$refers[$canonized_headline];
2356
2357 # Don't number the heading if it is the only one (looks silly)
2358 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2359 # the two are different if the line contains a link
2360 $headline=$numbering . ' ' . $headline;
2361 }
2362
2363 # Create the anchor for linking from the TOC to the section
2364 $anchor = $canonized_headline;
2365 if($refcount[$headlineCount] > 1 ) {
2366 $anchor .= '_' . $refcount[$headlineCount];
2367 }
2368 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2369 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
2370 }
2371 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
2372 if ( empty( $head[$headlineCount] ) ) {
2373 $head[$headlineCount] = '';
2374 }
2375 if( $istemplate )
2376 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
2377 else
2378 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
2379 }
2380
2381 # give headline the correct <h#> tag
2382 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
2383
2384 $headlineCount++;
2385 if( !$istemplate )
2386 $sectionCount++;
2387 }
2388
2389 if( $doShowToc ) {
2390 $toclines = $headlineCount;
2391 $toc .= $sk->tocUnindent( $toclevel - 1 );
2392 $toc = $sk->tocList( $toc );
2393 }
2394
2395 # split up and insert constructed headlines
2396
2397 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2398 $i = 0;
2399
2400 foreach( $blocks as $block ) {
2401 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2402 # This is the [edit] link that appears for the top block of text when
2403 # section editing is enabled
2404
2405 # Disabled because it broke block formatting
2406 # For example, a bullet point in the top line
2407 # $full .= $sk->editSectionLink(0);
2408 }
2409 $full .= $block;
2410 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2411 # Top anchor now in skin
2412 $full = $full.$toc;
2413 }
2414
2415 if( !empty( $head[$i] ) ) {
2416 $full .= $head[$i];
2417 }
2418 $i++;
2419 }
2420 if($forceTocHere) {
2421 $mw =& MagicWord::get( MAG_TOC );
2422 return $mw->replace( $toc, $full );
2423 } else {
2424 return $full;
2425 }
2426 }
2427
2428 /**
2429 * Return an HTML link for the "ISBN 123456" text
2430 * @access private
2431 */
2432 function magicISBN( $text ) {
2433 global $wgLang;
2434 $fname = 'Parser::magicISBN';
2435 wfProfileIn( $fname );
2436
2437 $a = split( 'ISBN ', ' '.$text );
2438 if ( count ( $a ) < 2 ) {
2439 wfProfileOut( $fname );
2440 return $text;
2441 }
2442 $text = substr( array_shift( $a ), 1);
2443 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2444
2445 foreach ( $a as $x ) {
2446 $isbn = $blank = '' ;
2447 while ( ' ' == $x{0} ) {
2448 $blank .= ' ';
2449 $x = substr( $x, 1 );
2450 }
2451 if ( $x == '' ) { # blank isbn
2452 $text .= "ISBN $blank";
2453 continue;
2454 }
2455 while ( strstr( $valid, $x{0} ) != false ) {
2456 $isbn .= $x{0};
2457 $x = substr( $x, 1 );
2458 }
2459 $num = str_replace( '-', '', $isbn );
2460 $num = str_replace( ' ', '', $num );
2461
2462 if ( '' == $num ) {
2463 $text .= "ISBN $blank$x";
2464 } else {
2465 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2466 $text .= '<a href="' .
2467 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
2468 "\" class=\"internal\">ISBN $isbn</a>";
2469 $text .= $x;
2470 }
2471 }
2472 wfProfileOut( $fname );
2473 return $text;
2474 }
2475
2476 /**
2477 * Return an HTML link for the "RFC 1234" text
2478 *
2479 * @access private
2480 * @param string $text Text to be processed
2481 * @param string $keyword Magic keyword to use (default RFC)
2482 * @param string $urlmsg Interface message to use (default rfcurl)
2483 * @return string
2484 */
2485 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
2486 global $wgLang;
2487
2488 $valid = '0123456789';
2489 $internal = false;
2490
2491 $a = split( $keyword, ' '.$text );
2492 if ( count ( $a ) < 2 ) {
2493 return $text;
2494 }
2495 $text = substr( array_shift( $a ), 1);
2496
2497 /* Check if keyword is preceed by [[.
2498 * This test is made here cause of the array_shift above
2499 * that prevent the test to be done in the foreach.
2500 */
2501 if ( substr( $text, -2 ) == '[[' ) {
2502 $internal = true;
2503 }
2504
2505 foreach ( $a as $x ) {
2506 /* token might be empty if we have RFC RFC 1234 */
2507 if ( $x=='' ) {
2508 $text.=$keyword;
2509 continue;
2510 }
2511
2512 $id = $blank = '' ;
2513
2514 /** remove and save whitespaces in $blank */
2515 while ( $x{0} == ' ' ) {
2516 $blank .= ' ';
2517 $x = substr( $x, 1 );
2518 }
2519
2520 /** remove and save the rfc number in $id */
2521 while ( strstr( $valid, $x{0} ) != false ) {
2522 $id .= $x{0};
2523 $x = substr( $x, 1 );
2524 }
2525
2526 if ( $id == '' ) {
2527 /* call back stripped spaces*/
2528 $text .= $keyword.$blank.$x;
2529 } elseif( $internal ) {
2530 /* normal link */
2531 $text .= $keyword.$id.$x;
2532 } else {
2533 /* build the external link*/
2534 $url = wfMsg( $urlmsg, $id);
2535 $sk =& $this->mOptions->getSkin();
2536 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
2537 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
2538 }
2539
2540 /* Check if the next RFC keyword is preceed by [[ */
2541 $internal = ( substr($x,-2) == '[[' );
2542 }
2543 return $text;
2544 }
2545
2546 /**
2547 * Transform wiki markup when saving a page by doing \r\n -> \n
2548 * conversion, substitting signatures, {{subst:}} templates, etc.
2549 *
2550 * @param string $text the text to transform
2551 * @param Title &$title the Title object for the current article
2552 * @param User &$user the User object describing the current user
2553 * @param ParserOptions $options parsing options
2554 * @param bool $clearState whether to clear the parser state first
2555 * @return string the altered wiki markup
2556 * @access public
2557 */
2558 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2559 $this->mOptions = $options;
2560 $this->mTitle =& $title;
2561 $this->mOutputType = OT_WIKI;
2562
2563 if ( $clearState ) {
2564 $this->clearState();
2565 }
2566
2567 $stripState = false;
2568 $pairs = array(
2569 "\r\n" => "\n",
2570 );
2571 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
2572 $text = $this->strip( $text, $stripState, false );
2573 $text = $this->pstPass2( $text, $user );
2574 $text = $this->unstrip( $text, $stripState );
2575 $text = $this->unstripNoWiki( $text, $stripState );
2576 return $text;
2577 }
2578
2579 /**
2580 * Pre-save transform helper function
2581 * @access private
2582 */
2583 function pstPass2( $text, &$user ) {
2584 global $wgLang, $wgContLang, $wgLocaltimezone;
2585
2586 # Variable replacement
2587 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2588 $text = $this->replaceVariables( $text );
2589
2590 # Signatures
2591 #
2592 $n = $user->getName();
2593 $k = $user->getOption( 'nickname' );
2594 if ( '' == $k ) { $k = $n; }
2595 if ( isset( $wgLocaltimezone ) ) {
2596 $oldtz = getenv( 'TZ' );
2597 putenv( 'TZ='.$wgLocaltimezone );
2598 }
2599 /* Note: this is an ugly timezone hack for the European wikis */
2600 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false ) .
2601 ' (' . date( 'T' ) . ')';
2602 if ( isset( $wgLocaltimezone ) ) {
2603 putenv( 'TZ='.$oldtzs );
2604 }
2605
2606 if( $user->getOption( 'fancysig' ) ) {
2607 $sigText = $k;
2608 } else {
2609 $sigText = '[[' . $wgContLang->getNsText( NS_USER ) . ":$n|$k]]";
2610 }
2611 $text = preg_replace( '/~~~~~/', $d, $text );
2612 $text = preg_replace( '/~~~~/', "$sigText $d", $text );
2613 $text = preg_replace( '/~~~/', $sigText, $text );
2614
2615 # Context links: [[|name]] and [[name (context)|]]
2616 #
2617 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2618 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2619 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2620 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2621
2622 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2623 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2624 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
2625 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
2626 $context = '';
2627 $t = $this->mTitle->getText();
2628 if ( preg_match( $conpat, $t, $m ) ) {
2629 $context = $m[2];
2630 }
2631 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2632 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2633 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2634
2635 if ( '' == $context ) {
2636 $text = preg_replace( $p2, '[[\\1]]', $text );
2637 } else {
2638 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2639 }
2640
2641 # Trim trailing whitespace
2642 # MAG_END (__END__) tag allows for trailing
2643 # whitespace to be deliberately included
2644 $text = rtrim( $text );
2645 $mw =& MagicWord::get( MAG_END );
2646 $mw->matchAndRemove( $text );
2647
2648 return $text;
2649 }
2650
2651 /**
2652 * Set up some variables which are usually set up in parse()
2653 * so that an external function can call some class members with confidence
2654 * @access public
2655 */
2656 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2657 $this->mTitle =& $title;
2658 $this->mOptions = $options;
2659 $this->mOutputType = $outputType;
2660 if ( $clearState ) {
2661 $this->clearState();
2662 }
2663 }
2664
2665 /**
2666 * Transform a MediaWiki message by replacing magic variables.
2667 *
2668 * @param string $text the text to transform
2669 * @param ParserOptions $options options
2670 * @return string the text with variables substituted
2671 * @access public
2672 */
2673 function transformMsg( $text, $options ) {
2674 global $wgTitle;
2675 static $executing = false;
2676
2677 # Guard against infinite recursion
2678 if ( $executing ) {
2679 return $text;
2680 }
2681 $executing = true;
2682
2683 $this->mTitle = $wgTitle;
2684 $this->mOptions = $options;
2685 $this->mOutputType = OT_MSG;
2686 $this->clearState();
2687 $text = $this->replaceVariables( $text );
2688
2689 $executing = false;
2690 return $text;
2691 }
2692
2693 /**
2694 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2695 * Callback will be called with the text within
2696 * Transform and return the text within
2697 * @access public
2698 */
2699 function setHook( $tag, $callback ) {
2700 $oldVal = @$this->mTagHooks[$tag];
2701 $this->mTagHooks[$tag] = $callback;
2702 return $oldVal;
2703 }
2704
2705 /**
2706 * Replace <!--LINK--> link placeholders with actual links, in the buffer
2707 * Placeholders created in Skin::makeLinkObj()
2708 * Returns an array of links found, indexed by PDBK:
2709 * 0 - broken
2710 * 1 - normal link
2711 * 2 - stub
2712 * $options is a bit field, RLH_FOR_UPDATE to select for update
2713 */
2714 function replaceLinkHolders( &$text, $options = 0 ) {
2715 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
2716 global $wgInterwikiLinkHolders;
2717 global $outputReplace;
2718
2719 if ( $wgUseOldExistenceCheck ) {
2720 return array();
2721 }
2722
2723 $fname = 'Parser::replaceLinkHolders';
2724 wfProfileIn( $fname );
2725
2726 $pdbks = array();
2727 $colours = array();
2728
2729 #if ( !empty( $tmpLinks[0] ) ) { #TODO
2730 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
2731 wfProfileIn( $fname.'-check' );
2732 $dbr =& wfGetDB( DB_SLAVE );
2733 $page = $dbr->tableName( 'page' );
2734 $sk = $wgUser->getSkin();
2735 $threshold = $wgUser->getOption('stubthreshold');
2736
2737 # Sort by namespace
2738 asort( $wgLinkHolders['namespaces'] );
2739
2740 # Generate query
2741 $query = false;
2742 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
2743 # Make title object
2744 $title = $wgLinkHolders['titles'][$key];
2745
2746 # Skip invalid entries.
2747 # Result will be ugly, but prevents crash.
2748 if ( is_null( $title ) ) {
2749 continue;
2750 }
2751 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
2752
2753 # Check if it's in the link cache already
2754 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
2755 $colours[$pdbk] = 1;
2756 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
2757 $colours[$pdbk] = 0;
2758 } else {
2759 # Not in the link cache, add it to the query
2760 if ( !isset( $current ) ) {
2761 $current = $val;
2762 $query = "SELECT page_id, page_namespace, page_title";
2763 if ( $threshold > 0 ) {
2764 $query .= ', page_len, page_is_redirect';
2765 }
2766 $query .= " FROM $page WHERE (page_namespace=$val AND page_title IN(";
2767 } elseif ( $current != $val ) {
2768 $current = $val;
2769 $query .= ")) OR (page_namespace=$val AND page_title IN(";
2770 } else {
2771 $query .= ', ';
2772 }
2773
2774 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
2775 }
2776 }
2777 if ( $query ) {
2778 $query .= '))';
2779 if ( $options & RLH_FOR_UPDATE ) {
2780 $query .= ' FOR UPDATE';
2781 }
2782
2783 $res = $dbr->query( $query, $fname );
2784
2785 # Fetch data and form into an associative array
2786 # non-existent = broken
2787 # 1 = known
2788 # 2 = stub
2789 while ( $s = $dbr->fetchObject($res) ) {
2790 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
2791 $pdbk = $title->getPrefixedDBkey();
2792 $wgLinkCache->addGoodLink( $s->page_id, $pdbk );
2793
2794 if ( $threshold > 0 ) {
2795 $size = $s->page_len;
2796 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
2797 $colours[$pdbk] = 1;
2798 } else {
2799 $colours[$pdbk] = 2;
2800 }
2801 } else {
2802 $colours[$pdbk] = 1;
2803 }
2804 }
2805 }
2806 wfProfileOut( $fname.'-check' );
2807
2808 # Construct search and replace arrays
2809 wfProfileIn( $fname.'-construct' );
2810 $outputReplace = array();
2811 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
2812 $pdbk = $pdbks[$key];
2813 $searchkey = '<!--LINK '.$key.'-->';
2814 $title = $wgLinkHolders['titles'][$key];
2815 if ( empty( $colours[$pdbk] ) ) {
2816 $wgLinkCache->addBadLink( $pdbk );
2817 $colours[$pdbk] = 0;
2818 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
2819 $wgLinkHolders['texts'][$key],
2820 $wgLinkHolders['queries'][$key] );
2821 } elseif ( $colours[$pdbk] == 1 ) {
2822 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
2823 $wgLinkHolders['texts'][$key],
2824 $wgLinkHolders['queries'][$key] );
2825 } elseif ( $colours[$pdbk] == 2 ) {
2826 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
2827 $wgLinkHolders['texts'][$key],
2828 $wgLinkHolders['queries'][$key] );
2829 }
2830 }
2831 wfProfileOut( $fname.'-construct' );
2832
2833 # Do the thing
2834 wfProfileIn( $fname.'-replace' );
2835
2836 $text = preg_replace_callback(
2837 '/(<!--LINK .*?-->)/',
2838 "outputReplaceMatches",
2839 $text);
2840 wfProfileOut( $fname.'-replace' );
2841 }
2842
2843 if ( !empty( $wgInterwikiLinkHolders ) ) {
2844 wfProfileIn( $fname.'-interwiki' );
2845 $outputReplace = $wgInterwikiLinkHolders;
2846 $text = preg_replace_callback(
2847 '/<!--IWLINK (.*?)-->/',
2848 "outputReplaceMatches",
2849 $text );
2850 wfProfileOut( $fname.'-interwiki' );
2851 }
2852
2853 wfProfileOut( $fname );
2854 return $colours;
2855 }
2856
2857 /**
2858 * Renders an image gallery from a text with one line per image.
2859 * text labels may be given by using |-style alternative text. E.g.
2860 * Image:one.jpg|The number "1"
2861 * Image:tree.jpg|A tree
2862 * given as text will return the HTML of a gallery with two images,
2863 * labeled 'The number "1"' and
2864 * 'A tree'.
2865 */
2866 function renderImageGallery( $text ) {
2867 # Setup the parser
2868 global $wgUser, $wgParser, $wgTitle;
2869 $parserOptions = ParserOptions::newFromUser( $wgUser );
2870
2871 global $wgLinkCache;
2872 $ig = new ImageGallery();
2873 $ig->setShowBytes( false );
2874 $ig->setShowFilename( false );
2875 $lines = explode( "\n", $text );
2876
2877 foreach ( $lines as $line ) {
2878 # match lines like these:
2879 # Image:someimage.jpg|This is some image
2880 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
2881 # Skip empty lines
2882 if ( count( $matches ) == 0 ) {
2883 continue;
2884 }
2885 $nt = Title::newFromURL( $matches[1] );
2886 if( is_null( $nt ) ) {
2887 # Bogus title. Ignore these so we don't bomb out later.
2888 continue;
2889 }
2890 if ( isset( $matches[3] ) ) {
2891 $label = $matches[3];
2892 } else {
2893 $label = '';
2894 }
2895
2896 $html = $wgParser->parse( $label , $wgTitle, $parserOptions );
2897 $html = $html->mText;
2898
2899 $ig->add( Image::newFromTitle( $nt ), $html );
2900 $wgLinkCache->addImageLinkObj( $nt );
2901 }
2902 return $ig->toHTML();
2903 }
2904 }
2905
2906 /**
2907 * @todo document
2908 * @package MediaWiki
2909 */
2910 class ParserOutput
2911 {
2912 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2913 var $mCacheTime; # Used in ParserCache
2914 var $mVersion; # Compatibility check
2915
2916 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
2917 $containsOldMagic = false )
2918 {
2919 $this->mText = $text;
2920 $this->mLanguageLinks = $languageLinks;
2921 $this->mCategoryLinks = $categoryLinks;
2922 $this->mContainsOldMagic = $containsOldMagic;
2923 $this->mCacheTime = '';
2924 $this->mVersion = MW_PARSER_VERSION;
2925 }
2926
2927 function getText() { return $this->mText; }
2928 function getLanguageLinks() { return $this->mLanguageLinks; }
2929 function getCategoryLinks() { return array_keys( $this->mCategoryLinks ); }
2930 function getCacheTime() { return $this->mCacheTime; }
2931 function containsOldMagic() { return $this->mContainsOldMagic; }
2932 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2933 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2934 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2935 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2936 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2937 function addCategoryLink( $c ) { $this->mCategoryLinks[$c] = 1; }
2938
2939 function merge( $other ) {
2940 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2941 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2942 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2943 }
2944
2945 /**
2946 * Return true if this cached output object predates the global or
2947 * per-article cache invalidation timestamps, or if it comes from
2948 * an incompatible older version.
2949 *
2950 * @param string $touched the affected article's last touched timestamp
2951 * @return bool
2952 * @access public
2953 */
2954 function expired( $touched ) {
2955 global $wgCacheEpoch;
2956 return $this->getCacheTime() <= $touched ||
2957 $this->getCacheTime() <= $wgCacheEpoch ||
2958 !isset( $this->mVersion ) ||
2959 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
2960 }
2961 }
2962
2963 /**
2964 * Set options of the Parser
2965 * @todo document
2966 * @package MediaWiki
2967 */
2968 class ParserOptions
2969 {
2970 # All variables are private
2971 var $mUseTeX; # Use texvc to expand <math> tags
2972 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2973 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2974 var $mAllowExternalImages; # Allow external images inline
2975 var $mSkin; # Reference to the preferred skin
2976 var $mDateFormat; # Date format index
2977 var $mEditSection; # Create "edit section" links
2978 var $mNumberHeadings; # Automatically number headings
2979
2980 function getUseTeX() { return $this->mUseTeX; }
2981 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2982 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2983 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2984 function getSkin() { return $this->mSkin; }
2985 function getDateFormat() { return $this->mDateFormat; }
2986 function getEditSection() { return $this->mEditSection; }
2987 function getNumberHeadings() { return $this->mNumberHeadings; }
2988
2989 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
2990 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
2991 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
2992 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
2993 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
2994 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
2995 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
2996
2997 function setSkin( &$x ) { $this->mSkin =& $x; }
2998
2999 /**
3000 * Get parser options
3001 * @static
3002 */
3003 function newFromUser( &$user ) {
3004 $popts = new ParserOptions;
3005 $popts->initialiseFromUser( $user );
3006 return $popts;
3007 }
3008
3009 /** Get user options */
3010 function initialiseFromUser( &$userInput ) {
3011 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
3012 $fname = 'ParserOptions::initialiseFromUser';
3013 wfProfileIn( $fname );
3014 if ( !$userInput ) {
3015 $user = new User;
3016 $user->setLoaded( true );
3017 } else {
3018 $user =& $userInput;
3019 }
3020
3021 $this->mUseTeX = $wgUseTeX;
3022 $this->mUseDynamicDates = $wgUseDynamicDates;
3023 $this->mInterwikiMagic = $wgInterwikiMagic;
3024 $this->mAllowExternalImages = $wgAllowExternalImages;
3025 wfProfileIn( $fname.'-skin' );
3026 $this->mSkin =& $user->getSkin();
3027 wfProfileOut( $fname.'-skin' );
3028 $this->mDateFormat = $user->getOption( 'date' );
3029 $this->mEditSection = $user->getOption( 'editsection' );
3030 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3031 wfProfileOut( $fname );
3032 }
3033 }
3034
3035 /**
3036 * Callback function used by Parser::replaceLinkHolders()
3037 * to substitute link placeholders.
3038 */
3039 function &outputReplaceMatches( $matches ) {
3040 global $outputReplace;
3041 return $outputReplace[$matches[1]];
3042 }
3043
3044 /**
3045 * Return the total number of articles
3046 */
3047 function wfNumberOfArticles() {
3048 global $wgNumberOfArticles;
3049
3050 wfLoadSiteStats();
3051 return $wgNumberOfArticles;
3052 }
3053
3054 /**
3055 * Get various statistics from the database
3056 * @private
3057 */
3058 function wfLoadSiteStats() {
3059 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
3060 $fname = 'wfLoadSiteStats';
3061
3062 if ( -1 != $wgNumberOfArticles ) return;
3063 $dbr =& wfGetDB( DB_SLAVE );
3064 $s = $dbr->selectRow( 'site_stats',
3065 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
3066 array( 'ss_row_id' => 1 ), $fname
3067 );
3068
3069 if ( $s === false ) {
3070 return;
3071 } else {
3072 $wgTotalViews = $s->ss_total_views;
3073 $wgTotalEdits = $s->ss_total_edits;
3074 $wgNumberOfArticles = $s->ss_good_articles;
3075 }
3076 }
3077
3078 /**
3079 * Escape html tags
3080 * Basicly replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
3081 *
3082 * @param string $in Text that might contain HTML tags
3083 * @return string Escaped string
3084 */
3085 function wfEscapeHTMLTagsOnly( $in ) {
3086 return str_replace(
3087 array( '"', '>', '<' ),
3088 array( '&quot;', '&gt;', '&lt;' ),
3089 $in );
3090 }
3091
3092 ?>