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