Fixing parser errors "no data" and "nothing but a caption".
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2 /**
3 * File for Parser and related classes
4 *
5 * @package MediaWiki
6 * @subpackage Parser
7 */
8
9 /** */
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
12
13 /**
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
17 */
18 define( 'MW_PARSER_VERSION', '1.6.0' );
19
20 /**
21 * Variable substitution O(N^2) attack
22 *
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
28 */
29
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32
33 define( 'RLH_FOR_UPDATE', 1 );
34
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
39
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
50 # Including space
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
59 );
60
61 /**
62 * PHP Parser
63 *
64 * Processes wiki markup
65 *
66 * <pre>
67 * There are three main entry points into the Parser class:
68 * parse()
69 * produces HTML output
70 * preSaveTransform().
71 * produces altered wiki markup.
72 * transformMsg()
73 * performs brace substitution on MediaWiki messages
74 *
75 * Globals used:
76 * objects: $wgLang
77 *
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
79 *
80 * settings:
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
84 *
85 * * only within ParserOptions
86 * </pre>
87 *
88 * @package MediaWiki
89 */
90 class Parser
91 {
92 /**#@+
93 * @access private
94 */
95 # Persistent:
96 var $mTagHooks;
97
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
106
107 # Temporary
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
113
114 /**#@-*/
115
116 /**
117 * Constructor
118 *
119 * @access public
120 */
121 function Parser() {
122 $this->mTagHooks = array();
123 $this->clearState();
124 }
125
126 /**
127 * Clear Parser state
128 *
129 * @access private
130 */
131 function clearState() {
132 $this->mOutput = new ParserOutput;
133 $this->mAutonumber = 0;
134 $this->mLastSection = '';
135 $this->mDTopen = false;
136 $this->mVariables = false;
137 $this->mIncludeCount = array();
138 $this->mStripState = array();
139 $this->mArgStack = array();
140 $this->mInPre = false;
141 $this->mInterwikiLinkHolders = array(
142 'texts' => array(),
143 'titles' => array()
144 );
145 $this->mLinkHolders = array(
146 'namespaces' => array(),
147 'dbkeys' => array(),
148 'queries' => array(),
149 'texts' => array(),
150 'titles' => array()
151 );
152 $this->mRevisionId = null;
153 $this->mUniqPrefix = 'UNIQ' . Parser::getRandomString();
154
155 # Clear these on every parse, bug 4549
156 $this->mTemplates = array();
157 $this->mTemplatePath = array();
158
159 wfRunHooks( 'ParserClearState', array( &$this ) );
160 }
161
162 /**
163 * Accessor for mUniqPrefix.
164 *
165 * @access public
166 */
167 function UniqPrefix() {
168 return $this->mUniqPrefix;
169 }
170
171 /**
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
174 *
175 * @access private
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
183 */
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
185 /**
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
188 */
189
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
193
194 if ( $clearState ) {
195 $this->clearState();
196 }
197
198 $this->mOptions = $options;
199 $this->mTitle =& $title;
200 $this->mRevisionId = $revid;
201 $this->mOutputType = OT_HTML;
202
203 $this->mStripState = NULL;
204
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState;
208
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
212
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
216 return $text ;
217 }
218
219 $text = $this->internalParse( $text );
220
221 $text = $this->unstrip( $text, $this->mStripState );
222
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
224 $fixtags = array(
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1&nbsp;',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
231 );
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
233
234 # only once and last
235 $text = $this->doBlockLevels( $text, $linestart );
236
237 $this->replaceLinkHolders( $text );
238
239 # the position of the convert() call should not be changed. it
240 # assumes that the links are all replaces and the only thing left
241 # is the <nowiki> mark.
242 $text = $wgContLang->convert($text);
243 $this->mOutput->setTitleText($wgContLang->getParsedTitle());
244
245 $text = $this->unstripNoWiki( $text, $this->mStripState );
246
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
248
249 $text = Sanitizer::normalizeCharReferences( $text );
250
251 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
252 $text = Parser::tidy($text);
253 }
254
255 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
256
257 $this->mOutput->setText( $text );
258 wfProfileOut( $fname );
259
260 return $this->mOutput;
261 }
262
263 /**
264 * Get a random string
265 *
266 * @access private
267 * @static
268 */
269 function getRandomString() {
270 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
271 }
272
273 /**
274 * Replaces all occurrences of <$tag>content</$tag> in the text
275 * with a random marker and returns the new text. the output parameter
276 * $content will be an associative array filled with data on the form
277 * $unique_marker => content.
278 *
279 * If $content is already set, the additional entries will be appended
280 * If $tag is set to STRIP_COMMENTS, the function will extract
281 * <!-- HTML comments -->
282 *
283 * @access private
284 * @static
285 */
286 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
287 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
288 if ( !$content ) {
289 $content = array( );
290 }
291 $n = 1;
292 $stripped = '';
293
294 if ( !$tags ) {
295 $tags = array( );
296 }
297
298 if ( !$params ) {
299 $params = array( );
300 }
301
302 if( $tag == STRIP_COMMENTS ) {
303 $start = '/<!--()()/';
304 $end = '/-->/';
305 } else {
306 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
307 $end = "/<\\/$tag\\s*>/i";
308 }
309
310 while ( '' != $text ) {
311 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
312 $stripped .= $p[0];
313 if( count( $p ) < 4 ) {
314 break;
315 }
316 $attributes = $p[1];
317 $empty = $p[2];
318 $inside = $p[3];
319
320 $marker = $rnd . sprintf('%08X', $n++);
321 $stripped .= $marker;
322
323 $tags[$marker] = "<$tag$attributes$empty>";
324 $params[$marker] = Sanitizer::decodeTagAttributes( $attributes );
325
326 if ( $empty === '/' ) {
327 // Empty element tag, <tag />
328 $content[$marker] = null;
329 $text = $inside;
330 } else {
331 $q = preg_split( $end, $inside, 2 );
332 $content[$marker] = $q[0];
333 if( count( $q ) < 2 ) {
334 # No end tag -- let it run out to the end of the text.
335 break;
336 } else {
337 $text = $q[1];
338 }
339 }
340 }
341 return $stripped;
342 }
343
344 /**
345 * Wrapper function for extractTagsAndParams
346 * for cases where $tags and $params isn't needed
347 * i.e. where tags will never have params, like <nowiki>
348 *
349 * @access private
350 * @static
351 */
352 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
353 $dummy_tags = array();
354 $dummy_params = array();
355
356 return Parser::extractTagsAndParams( $tag, $text, $content,
357 $dummy_tags, $dummy_params, $uniq_prefix );
358 }
359
360 /**
361 * Strips and renders nowiki, pre, math, hiero
362 * If $render is set, performs necessary rendering operations on plugins
363 * Returns the text, and fills an array with data needed in unstrip()
364 * If the $state is already a valid strip state, it adds to the state
365 *
366 * @param bool $stripcomments when set, HTML comments <!-- like this -->
367 * will be stripped in addition to other tags. This is important
368 * for section editing, where these comments cause confusion when
369 * counting the sections in the wikisource
370 *
371 * @access private
372 */
373 function strip( $text, &$state, $stripcomments = false ) {
374 $render = ($this->mOutputType == OT_HTML);
375 $html_content = array();
376 $nowiki_content = array();
377 $math_content = array();
378 $pre_content = array();
379 $comment_content = array();
380 $ext_content = array();
381 $ext_tags = array();
382 $ext_params = array();
383 $gallery_content = array();
384
385 # Replace any instances of the placeholders
386 $uniq_prefix = $this->mUniqPrefix;
387 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
388
389 # html
390 global $wgRawHtml;
391 if( $wgRawHtml ) {
392 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
393 foreach( $html_content as $marker => $content ) {
394 if ($render ) {
395 # Raw and unchecked for validity.
396 $html_content[$marker] = $content;
397 } else {
398 $html_content[$marker] = '<html>'.$content.'</html>';
399 }
400 }
401 }
402
403 # nowiki
404 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
405 foreach( $nowiki_content as $marker => $content ) {
406 if( $render ){
407 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
408 } else {
409 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
410 }
411 }
412
413 # math
414 if( $this->mOptions->getUseTeX() ) {
415 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
416 foreach( $math_content as $marker => $content ){
417 if( $render ) {
418 $math_content[$marker] = renderMath( $content );
419 } else {
420 $math_content[$marker] = '<math>'.$content.'</math>';
421 }
422 }
423 }
424
425 # pre
426 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
427 foreach( $pre_content as $marker => $content ){
428 if( $render ){
429 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
430 } else {
431 $pre_content[$marker] = '<pre>'.$content.'</pre>';
432 }
433 }
434
435 # gallery
436 $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
437 foreach( $gallery_content as $marker => $content ) {
438 require_once( 'ImageGallery.php' );
439 if ( $render ) {
440 $gallery_content[$marker] = $this->renderImageGallery( $content );
441 } else {
442 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
443 }
444 }
445
446 # Comments
447 if($stripcomments) {
448 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
449 foreach( $comment_content as $marker => $content ){
450 $comment_content[$marker] = '<!--'.$content.'-->';
451 }
452 }
453
454 # Extensions
455 foreach ( $this->mTagHooks as $tag => $callback ) {
456 $ext_content[$tag] = array();
457 $text = Parser::extractTagsAndParams( $tag, $text, $ext_content[$tag],
458 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
459 foreach( $ext_content[$tag] as $marker => $content ) {
460 $full_tag = $ext_tags[$tag][$marker];
461 $params = $ext_params[$tag][$marker];
462 if ( $render )
463 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
464 else {
465 if ( is_null( $content ) ) {
466 // Empty element tag
467 $ext_content[$tag][$marker] = $full_tag;
468 } else {
469 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
470 }
471 }
472 }
473 }
474
475 # Merge state with the pre-existing state, if there is one
476 if ( $state ) {
477 $state['html'] = $state['html'] + $html_content;
478 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
479 $state['math'] = $state['math'] + $math_content;
480 $state['pre'] = $state['pre'] + $pre_content;
481 $state['comment'] = $state['comment'] + $comment_content;
482 $state['gallery'] = $state['gallery'] + $gallery_content;
483
484 foreach( $ext_content as $tag => $array ) {
485 if ( array_key_exists( $tag, $state ) ) {
486 $state[$tag] = $state[$tag] + $array;
487 }
488 }
489 } else {
490 $state = array(
491 'html' => $html_content,
492 'nowiki' => $nowiki_content,
493 'math' => $math_content,
494 'pre' => $pre_content,
495 'comment' => $comment_content,
496 'gallery' => $gallery_content,
497 ) + $ext_content;
498 }
499 return $text;
500 }
501
502 /**
503 * restores pre, math, and hiero removed by strip()
504 *
505 * always call unstripNoWiki() after this one
506 * @access private
507 */
508 function unstrip( $text, &$state ) {
509 if ( !is_array( $state ) ) {
510 return $text;
511 }
512
513 # Must expand in reverse order, otherwise nested tags will be corrupted
514 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
515 if( $tag != 'nowiki' && $tag != 'html' ) {
516 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
517 $text = str_replace( $uniq, $content, $text );
518 }
519 }
520 }
521
522 return $text;
523 }
524
525 /**
526 * always call this after unstrip() to preserve the order
527 *
528 * @access private
529 */
530 function unstripNoWiki( $text, &$state ) {
531 if ( !is_array( $state ) ) {
532 return $text;
533 }
534
535 # Must expand in reverse order, otherwise nested tags will be corrupted
536 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
537 $text = str_replace( key( $state['nowiki'] ), $content, $text );
538 }
539
540 global $wgRawHtml;
541 if ($wgRawHtml) {
542 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
543 $text = str_replace( key( $state['html'] ), $content, $text );
544 }
545 }
546
547 return $text;
548 }
549
550 /**
551 * Add an item to the strip state
552 * Returns the unique tag which must be inserted into the stripped text
553 * The tag will be replaced with the original text in unstrip()
554 *
555 * @access private
556 */
557 function insertStripItem( $text, &$state ) {
558 $rnd = $this->mUniqPrefix . '-item' . Parser::getRandomString();
559 if ( !$state ) {
560 $state = array(
561 'html' => array(),
562 'nowiki' => array(),
563 'math' => array(),
564 'pre' => array(),
565 'comment' => array(),
566 'gallery' => array(),
567 );
568 }
569 $state['item'][$rnd] = $text;
570 return $rnd;
571 }
572
573 /**
574 * Interface with html tidy, used if $wgUseTidy = true.
575 * If tidy isn't able to correct the markup, the original will be
576 * returned in all its glory with a warning comment appended.
577 *
578 * Either the external tidy program or the in-process tidy extension
579 * will be used depending on availability. Override the default
580 * $wgTidyInternal setting to disable the internal if it's not working.
581 *
582 * @param string $text Hideous HTML input
583 * @return string Corrected HTML output
584 * @access public
585 * @static
586 */
587 function tidy( $text ) {
588 global $wgTidyInternal;
589 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
590 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
591 '<head><title>test</title></head><body>'.$text.'</body></html>';
592 if( $wgTidyInternal ) {
593 $correctedtext = Parser::internalTidy( $wrappedtext );
594 } else {
595 $correctedtext = Parser::externalTidy( $wrappedtext );
596 }
597 if( is_null( $correctedtext ) ) {
598 wfDebug( "Tidy error detected!\n" );
599 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
600 }
601 return $correctedtext;
602 }
603
604 /**
605 * Spawn an external HTML tidy process and get corrected markup back from it.
606 *
607 * @access private
608 * @static
609 */
610 function externalTidy( $text ) {
611 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
612 $fname = 'Parser::externalTidy';
613 wfProfileIn( $fname );
614
615 $cleansource = '';
616 $opts = ' -utf8';
617
618 $descriptorspec = array(
619 0 => array('pipe', 'r'),
620 1 => array('pipe', 'w'),
621 2 => array('file', '/dev/null', 'a')
622 );
623 $pipes = array();
624 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
625 if (is_resource($process)) {
626 fwrite($pipes[0], $text);
627 fclose($pipes[0]);
628 while (!feof($pipes[1])) {
629 $cleansource .= fgets($pipes[1], 1024);
630 }
631 fclose($pipes[1]);
632 proc_close($process);
633 }
634
635 wfProfileOut( $fname );
636
637 if( $cleansource == '' && $text != '') {
638 // Some kind of error happened, so we couldn't get the corrected text.
639 // Just give up; we'll use the source text and append a warning.
640 return null;
641 } else {
642 return $cleansource;
643 }
644 }
645
646 /**
647 * Use the HTML tidy PECL extension to use the tidy library in-process,
648 * saving the overhead of spawning a new process. Currently written to
649 * the PHP 4.3.x version of the extension, may not work on PHP 5.
650 *
651 * 'pear install tidy' should be able to compile the extension module.
652 *
653 * @access private
654 * @static
655 */
656 function internalTidy( $text ) {
657 global $wgTidyConf;
658 $fname = 'Parser::internalTidy';
659 wfProfileIn( $fname );
660
661 tidy_load_config( $wgTidyConf );
662 tidy_set_encoding( 'utf8' );
663 tidy_parse_string( $text );
664 tidy_clean_repair();
665 if( tidy_get_status() == 2 ) {
666 // 2 is magic number for fatal error
667 // http://www.php.net/manual/en/function.tidy-get-status.php
668 $cleansource = null;
669 } else {
670 $cleansource = tidy_get_output();
671 }
672 wfProfileOut( $fname );
673 return $cleansource;
674 }
675
676 /**
677 * parse the wiki syntax used to render tables
678 *
679 * @access private
680 */
681 function doTableStuff ( $t ) {
682 $fname = 'Parser::doTableStuff';
683 wfProfileIn( $fname );
684
685 $t = explode ( "\n" , $t ) ;
686 $td = array () ; # Is currently a td tag open?
687 $ltd = array () ; # Was it TD or TH?
688 $tr = array () ; # Is currently a tr tag open?
689 $ltr = array () ; # tr attributes
690 $has_opened_tr = array(); # Did this table open a <tr> element?
691 $indent_level = 0; # indent level of the table
692 foreach ( $t AS $k => $x )
693 {
694 $x = trim ( $x ) ;
695 $fc = substr ( $x , 0 , 1 ) ;
696 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
697 $indent_level = strlen( $matches[1] );
698
699 $attributes = $this->unstripForHTML( $matches[2] );
700
701 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
702 '<table' . Sanitizer::fixTagAttributes ( $attributes, 'table' ) . '>' ;
703 array_push ( $td , false ) ;
704 array_push ( $ltd , '' ) ;
705 array_push ( $tr , false ) ;
706 array_push ( $ltr , '' ) ;
707 array_push ( $has_opened_tr, false );
708 }
709 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
710 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
711 $z = "</table>" . substr ( $x , 2);
712 $l = array_pop ( $ltd ) ;
713 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
714 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
715 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
716 array_pop ( $ltr ) ;
717 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
718 }
719 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
720 $x = substr ( $x , 1 ) ;
721 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
722 $z = '' ;
723 $l = array_pop ( $ltd ) ;
724 array_pop ( $has_opened_tr );
725 array_push ( $has_opened_tr , true ) ;
726 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
727 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
728 array_pop ( $ltr ) ;
729 $t[$k] = $z ;
730 array_push ( $tr , false ) ;
731 array_push ( $td , false ) ;
732 array_push ( $ltd , '' ) ;
733 $attributes = $this->unstripForHTML( $x );
734 array_push ( $ltr , Sanitizer::fixTagAttributes ( $attributes, 'tr' ) ) ;
735 }
736 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
737 # $x is a table row
738 if ( '|+' == substr ( $x , 0 , 2 ) ) {
739 $fc = '+' ;
740 $x = substr ( $x , 1 ) ;
741 }
742 $after = substr ( $x , 1 ) ;
743 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
744 $after = explode ( '||' , $after ) ;
745 $t[$k] = '' ;
746
747 # Loop through each table cell
748 foreach ( $after AS $theline )
749 {
750 $z = '' ;
751 if ( $fc != '+' )
752 {
753 $tra = array_pop ( $ltr ) ;
754 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
755 array_push ( $tr , true ) ;
756 array_push ( $ltr , '' ) ;
757 array_pop ( $has_opened_tr );
758 array_push ( $has_opened_tr , true ) ;
759 }
760
761 $l = array_pop ( $ltd ) ;
762 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
763 if ( $fc == '|' ) $l = 'td' ;
764 else if ( $fc == '!' ) $l = 'th' ;
765 else if ( $fc == '+' ) $l = 'caption' ;
766 else $l = '' ;
767 array_push ( $ltd , $l ) ;
768
769 # Cell parameters
770 $y = explode ( '|' , $theline , 2 ) ;
771 # Note that a '|' inside an invalid link should not
772 # be mistaken as delimiting cell parameters
773 if ( strpos( $y[0], '[[' ) !== false ) {
774 $y = array ($theline);
775 }
776 if ( count ( $y ) == 1 )
777 $y = "{$z}<{$l}>{$y[0]}" ;
778 else {
779 $attributes = $this->unstripForHTML( $y[0] );
780 $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($attributes, $l).">{$y[1]}" ;
781 }
782 $t[$k] .= $y ;
783 array_push ( $td , true ) ;
784 }
785 }
786 }
787
788 # Closing open td, tr && table
789 while ( count ( $td ) > 0 )
790 {
791 $l = array_pop ( $ltd ) ;
792 if ( array_pop ( $td ) ) $t[] = '</td>' ;
793 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
794 if ( array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
795 $t[] = '</table>' ;
796 }
797
798 $t = implode ( "\n" , $t ) ;
799 wfProfileOut( $fname );
800 return $t ;
801 }
802
803 /**
804 * Helper function for parse() that transforms wiki markup into
805 * HTML. Only called for $mOutputType == OT_HTML.
806 *
807 * @access private
808 */
809 function internalParse( $text ) {
810 global $wgContLang;
811 $args = array();
812 $isMain = true;
813 $fname = 'Parser::internalParse';
814 wfProfileIn( $fname );
815
816 # Remove <noinclude> tags and <includeonly> sections
817 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
818 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
819 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
820
821 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
822 $text = $this->replaceVariables( $text, $args );
823
824 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
825
826 $text = $this->doHeadings( $text );
827 if($this->mOptions->getUseDynamicDates()) {
828 $df =& DateFormatter::getInstance();
829 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
830 }
831 $text = $this->doAllQuotes( $text );
832 $text = $this->replaceInternalLinks( $text );
833 $text = $this->replaceExternalLinks( $text );
834
835 # replaceInternalLinks may sometimes leave behind
836 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
837 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
838
839 $text = $this->doMagicLinks( $text );
840 $text = $this->doTableStuff( $text );
841 $text = $this->formatHeadings( $text, $isMain );
842
843 wfProfileOut( $fname );
844 return $text;
845 }
846
847 /**
848 * Replace special strings like "ISBN xxx" and "RFC xxx" with
849 * magic external links.
850 *
851 * @access private
852 */
853 function &doMagicLinks( &$text ) {
854 $text = $this->magicISBN( $text );
855 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
856 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
857 return $text;
858 }
859
860 /**
861 * Parse headers and return html
862 *
863 * @access private
864 */
865 function doHeadings( $text ) {
866 $fname = 'Parser::doHeadings';
867 wfProfileIn( $fname );
868 for ( $i = 6; $i >= 1; --$i ) {
869 $h = str_repeat( '=', $i );
870 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
871 "<h{$i}>\\1</h{$i}>\\2", $text );
872 }
873 wfProfileOut( $fname );
874 return $text;
875 }
876
877 /**
878 * Replace single quotes with HTML markup
879 * @access private
880 * @return string the altered text
881 */
882 function doAllQuotes( $text ) {
883 $fname = 'Parser::doAllQuotes';
884 wfProfileIn( $fname );
885 $outtext = '';
886 $lines = explode( "\n", $text );
887 foreach ( $lines as $line ) {
888 $outtext .= $this->doQuotes ( $line ) . "\n";
889 }
890 $outtext = substr($outtext, 0,-1);
891 wfProfileOut( $fname );
892 return $outtext;
893 }
894
895 /**
896 * Helper function for doAllQuotes()
897 * @access private
898 */
899 function doQuotes( $text ) {
900 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
901 if ( count( $arr ) == 1 )
902 return $text;
903 else
904 {
905 # First, do some preliminary work. This may shift some apostrophes from
906 # being mark-up to being text. It also counts the number of occurrences
907 # of bold and italics mark-ups.
908 $i = 0;
909 $numbold = 0;
910 $numitalics = 0;
911 foreach ( $arr as $r )
912 {
913 if ( ( $i % 2 ) == 1 )
914 {
915 # If there are ever four apostrophes, assume the first is supposed to
916 # be text, and the remaining three constitute mark-up for bold text.
917 if ( strlen( $arr[$i] ) == 4 )
918 {
919 $arr[$i-1] .= "'";
920 $arr[$i] = "'''";
921 }
922 # If there are more than 5 apostrophes in a row, assume they're all
923 # text except for the last 5.
924 else if ( strlen( $arr[$i] ) > 5 )
925 {
926 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
927 $arr[$i] = "'''''";
928 }
929 # Count the number of occurrences of bold and italics mark-ups.
930 # We are not counting sequences of five apostrophes.
931 if ( strlen( $arr[$i] ) == 2 ) $numitalics++; else
932 if ( strlen( $arr[$i] ) == 3 ) $numbold++; else
933 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
934 }
935 $i++;
936 }
937
938 # If there is an odd number of both bold and italics, it is likely
939 # that one of the bold ones was meant to be an apostrophe followed
940 # by italics. Which one we cannot know for certain, but it is more
941 # likely to be one that has a single-letter word before it.
942 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
943 {
944 $i = 0;
945 $firstsingleletterword = -1;
946 $firstmultiletterword = -1;
947 $firstspace = -1;
948 foreach ( $arr as $r )
949 {
950 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
951 {
952 $x1 = substr ($arr[$i-1], -1);
953 $x2 = substr ($arr[$i-1], -2, 1);
954 if ($x1 == ' ') {
955 if ($firstspace == -1) $firstspace = $i;
956 } else if ($x2 == ' ') {
957 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
958 } else {
959 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
960 }
961 }
962 $i++;
963 }
964
965 # If there is a single-letter word, use it!
966 if ($firstsingleletterword > -1)
967 {
968 $arr [ $firstsingleletterword ] = "''";
969 $arr [ $firstsingleletterword-1 ] .= "'";
970 }
971 # If not, but there's a multi-letter word, use that one.
972 else if ($firstmultiletterword > -1)
973 {
974 $arr [ $firstmultiletterword ] = "''";
975 $arr [ $firstmultiletterword-1 ] .= "'";
976 }
977 # ... otherwise use the first one that has neither.
978 # (notice that it is possible for all three to be -1 if, for example,
979 # there is only one pentuple-apostrophe in the line)
980 else if ($firstspace > -1)
981 {
982 $arr [ $firstspace ] = "''";
983 $arr [ $firstspace-1 ] .= "'";
984 }
985 }
986
987 # Now let's actually convert our apostrophic mush to HTML!
988 $output = '';
989 $buffer = '';
990 $state = '';
991 $i = 0;
992 foreach ($arr as $r)
993 {
994 if (($i % 2) == 0)
995 {
996 if ($state == 'both')
997 $buffer .= $r;
998 else
999 $output .= $r;
1000 }
1001 else
1002 {
1003 if (strlen ($r) == 2)
1004 {
1005 if ($state == 'i')
1006 { $output .= '</i>'; $state = ''; }
1007 else if ($state == 'bi')
1008 { $output .= '</i>'; $state = 'b'; }
1009 else if ($state == 'ib')
1010 { $output .= '</b></i><b>'; $state = 'b'; }
1011 else if ($state == 'both')
1012 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1013 else # $state can be 'b' or ''
1014 { $output .= '<i>'; $state .= 'i'; }
1015 }
1016 else if (strlen ($r) == 3)
1017 {
1018 if ($state == 'b')
1019 { $output .= '</b>'; $state = ''; }
1020 else if ($state == 'bi')
1021 { $output .= '</i></b><i>'; $state = 'i'; }
1022 else if ($state == 'ib')
1023 { $output .= '</b>'; $state = 'i'; }
1024 else if ($state == 'both')
1025 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1026 else # $state can be 'i' or ''
1027 { $output .= '<b>'; $state .= 'b'; }
1028 }
1029 else if (strlen ($r) == 5)
1030 {
1031 if ($state == 'b')
1032 { $output .= '</b><i>'; $state = 'i'; }
1033 else if ($state == 'i')
1034 { $output .= '</i><b>'; $state = 'b'; }
1035 else if ($state == 'bi')
1036 { $output .= '</i></b>'; $state = ''; }
1037 else if ($state == 'ib')
1038 { $output .= '</b></i>'; $state = ''; }
1039 else if ($state == 'both')
1040 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1041 else # ($state == '')
1042 { $buffer = ''; $state = 'both'; }
1043 }
1044 }
1045 $i++;
1046 }
1047 # Now close all remaining tags. Notice that the order is important.
1048 if ($state == 'b' || $state == 'ib')
1049 $output .= '</b>';
1050 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1051 $output .= '</i>';
1052 if ($state == 'bi')
1053 $output .= '</b>';
1054 if ($state == 'both')
1055 $output .= '<b><i>'.$buffer.'</i></b>';
1056 return $output;
1057 }
1058 }
1059
1060 /**
1061 * Replace external links
1062 *
1063 * Note: this is all very hackish and the order of execution matters a lot.
1064 * Make sure to run maintenance/parserTests.php if you change this code.
1065 *
1066 * @access private
1067 */
1068 function replaceExternalLinks( $text ) {
1069 global $wgContLang;
1070 $fname = 'Parser::replaceExternalLinks';
1071 wfProfileIn( $fname );
1072
1073 $sk =& $this->mOptions->getSkin();
1074
1075 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1076
1077 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1078
1079 $i = 0;
1080 while ( $i<count( $bits ) ) {
1081 $url = $bits[$i++];
1082 $protocol = $bits[$i++];
1083 $text = $bits[$i++];
1084 $trail = $bits[$i++];
1085
1086 # The characters '<' and '>' (which were escaped by
1087 # removeHTMLtags()) should not be included in
1088 # URLs, per RFC 2396.
1089 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1090 $text = substr($url, $m2[0][1]) . ' ' . $text;
1091 $url = substr($url, 0, $m2[0][1]);
1092 }
1093
1094 # If the link text is an image URL, replace it with an <img> tag
1095 # This happened by accident in the original parser, but some people used it extensively
1096 $img = $this->maybeMakeExternalImage( $text );
1097 if ( $img !== false ) {
1098 $text = $img;
1099 }
1100
1101 $dtrail = '';
1102
1103 # Set linktype for CSS - if URL==text, link is essentially free
1104 $linktype = ($text == $url) ? 'free' : 'text';
1105
1106 # No link text, e.g. [http://domain.tld/some.link]
1107 if ( $text == '' ) {
1108 # Autonumber if allowed
1109 if ( strpos( HTTP_PROTOCOLS, str_replace('/','\/', $protocol) ) !== false ) {
1110 $text = '[' . ++$this->mAutonumber . ']';
1111 $linktype = 'autonumber';
1112 } else {
1113 # Otherwise just use the URL
1114 $text = htmlspecialchars( $url );
1115 $linktype = 'free';
1116 }
1117 } else {
1118 # Have link text, e.g. [http://domain.tld/some.link text]s
1119 # Check for trail
1120 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1121 }
1122
1123 $text = $wgContLang->markNoConversion($text);
1124
1125 # Replace &amp; from obsolete syntax with &.
1126 # All HTML entities will be escaped by makeExternalLink()
1127 $url = str_replace( '&amp;', '&', $url );
1128 # Replace unnecessary URL escape codes with the referenced character
1129 # This prevents spammers from hiding links from the filters
1130 $url = Parser::replaceUnusualEscapes( $url );
1131
1132 # Process the trail (i.e. everything after this link up until start of the next link),
1133 # replacing any non-bracketed links
1134 $trail = $this->replaceFreeExternalLinks( $trail );
1135
1136 # Use the encoded URL
1137 # This means that users can paste URLs directly into the text
1138 # Funny characters like &ouml; aren't valid in URLs anyway
1139 # This was changed in August 2004
1140 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1141
1142 # Register link in the output object
1143 $this->mOutput->addExternalLink( $url );
1144 }
1145
1146 wfProfileOut( $fname );
1147 return $s;
1148 }
1149
1150 /**
1151 * Replace anything that looks like a URL with a link
1152 * @access private
1153 */
1154 function replaceFreeExternalLinks( $text ) {
1155 global $wgContLang;
1156 $fname = 'Parser::replaceFreeExternalLinks';
1157 wfProfileIn( $fname );
1158
1159 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1160 $s = array_shift( $bits );
1161 $i = 0;
1162
1163 $sk =& $this->mOptions->getSkin();
1164
1165 while ( $i < count( $bits ) ){
1166 $protocol = $bits[$i++];
1167 $remainder = $bits[$i++];
1168
1169 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1170 # Found some characters after the protocol that look promising
1171 $url = $protocol . $m[1];
1172 $trail = $m[2];
1173
1174 # The characters '<' and '>' (which were escaped by
1175 # removeHTMLtags()) should not be included in
1176 # URLs, per RFC 2396.
1177 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1178 $trail = substr($url, $m2[0][1]) . $trail;
1179 $url = substr($url, 0, $m2[0][1]);
1180 }
1181
1182 # Move trailing punctuation to $trail
1183 $sep = ',;\.:!?';
1184 # If there is no left bracket, then consider right brackets fair game too
1185 if ( strpos( $url, '(' ) === false ) {
1186 $sep .= ')';
1187 }
1188
1189 $numSepChars = strspn( strrev( $url ), $sep );
1190 if ( $numSepChars ) {
1191 $trail = substr( $url, -$numSepChars ) . $trail;
1192 $url = substr( $url, 0, -$numSepChars );
1193 }
1194
1195 # Replace &amp; from obsolete syntax with &.
1196 # All HTML entities will be escaped by makeExternalLink()
1197 # or maybeMakeExternalImage()
1198 $url = str_replace( '&amp;', '&', $url );
1199 # Replace unnecessary URL escape codes with their equivalent characters
1200 $url = Parser::replaceUnusualEscapes( $url );
1201
1202 # Is this an external image?
1203 $text = $this->maybeMakeExternalImage( $url );
1204 if ( $text === false ) {
1205 # Not an image, make a link
1206 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1207 # Register it in the output object
1208 $this->mOutput->addExternalLink( $url );
1209 }
1210 $s .= $text . $trail;
1211 } else {
1212 $s .= $protocol . $remainder;
1213 }
1214 }
1215 wfProfileOut( $fname );
1216 return $s;
1217 }
1218
1219 /**
1220 * Replace unusual URL escape codes with their equivalent characters
1221 * @param string
1222 * @return string
1223 * @static
1224 */
1225 function replaceUnusualEscapes( $url ) {
1226 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1227 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1228 }
1229
1230 /**
1231 * Callback function used in replaceUnusualEscapes().
1232 * Replaces unusual URL escape codes with their equivalent character
1233 * @static
1234 * @access private
1235 */
1236 function replaceUnusualEscapesCallback( $matches ) {
1237 $char = urldecode( $matches[0] );
1238 $ord = ord( $char );
1239 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1240 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1241 // No, shouldn't be escaped
1242 return $char;
1243 } else {
1244 // Yes, leave it escaped
1245 return $matches[0];
1246 }
1247 }
1248
1249 /**
1250 * make an image if it's allowed, either through the global
1251 * option or through the exception
1252 * @access private
1253 */
1254 function maybeMakeExternalImage( $url ) {
1255 $sk =& $this->mOptions->getSkin();
1256 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1257 $imagesexception = !empty($imagesfrom);
1258 $text = false;
1259 if ( $this->mOptions->getAllowExternalImages()
1260 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1261 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1262 # Image found
1263 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1264 }
1265 }
1266 return $text;
1267 }
1268
1269 /**
1270 * Process [[ ]] wikilinks
1271 *
1272 * @access private
1273 */
1274 function replaceInternalLinks( $s ) {
1275 global $wgContLang;
1276 static $fname = 'Parser::replaceInternalLinks' ;
1277
1278 wfProfileIn( $fname );
1279
1280 wfProfileIn( $fname.'-setup' );
1281 static $tc = FALSE;
1282 # the % is needed to support urlencoded titles as well
1283 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1284
1285 $sk =& $this->mOptions->getSkin();
1286
1287 #split the entire text string on occurences of [[
1288 $a = explode( '[[', ' ' . $s );
1289 #get the first element (all text up to first [[), and remove the space we added
1290 $s = array_shift( $a );
1291 $s = substr( $s, 1 );
1292
1293 # Match a link having the form [[namespace:link|alternate]]trail
1294 static $e1 = FALSE;
1295 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1296 # Match cases where there is no "]]", which might still be images
1297 static $e1_img = FALSE;
1298 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1299 # Match the end of a line for a word that's not followed by whitespace,
1300 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1301 $e2 = wfMsgForContent( 'linkprefix' );
1302
1303 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1304
1305 if( is_null( $this->mTitle ) ) {
1306 wfDebugDieBacktrace( 'nooo' );
1307 }
1308 $nottalk = !$this->mTitle->isTalkPage();
1309
1310 if ( $useLinkPrefixExtension ) {
1311 if ( preg_match( $e2, $s, $m ) ) {
1312 $first_prefix = $m[2];
1313 } else {
1314 $first_prefix = false;
1315 }
1316 } else {
1317 $prefix = '';
1318 }
1319
1320 $selflink = $this->mTitle->getPrefixedText();
1321 wfProfileOut( $fname.'-setup' );
1322
1323 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1324 $useSubpages = $this->areSubpagesAllowed();
1325
1326 # Loop for each link
1327 for ($k = 0; isset( $a[$k] ); $k++) {
1328 $line = $a[$k];
1329 if ( $useLinkPrefixExtension ) {
1330 wfProfileIn( $fname.'-prefixhandling' );
1331 if ( preg_match( $e2, $s, $m ) ) {
1332 $prefix = $m[2];
1333 $s = $m[1];
1334 } else {
1335 $prefix='';
1336 }
1337 # first link
1338 if($first_prefix) {
1339 $prefix = $first_prefix;
1340 $first_prefix = false;
1341 }
1342 wfProfileOut( $fname.'-prefixhandling' );
1343 }
1344
1345 $might_be_img = false;
1346
1347 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1348 $text = $m[2];
1349 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1350 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1351 # the real problem is with the $e1 regex
1352 # See bug 1300.
1353 #
1354 # Still some problems for cases where the ] is meant to be outside punctuation,
1355 # and no image is in sight. See bug 2095.
1356 #
1357 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1358 $text .= ']'; # so that replaceExternalLinks($text) works later
1359 $m[3] = $n[1];
1360 }
1361 # fix up urlencoded title texts
1362 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1363 $trail = $m[3];
1364 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1365 $might_be_img = true;
1366 $text = $m[2];
1367 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1368 $trail = "";
1369 } else { # Invalid form; output directly
1370 $s .= $prefix . '[[' . $line ;
1371 continue;
1372 }
1373
1374 # Don't allow internal links to pages containing
1375 # PROTO: where PROTO is a valid URL protocol; these
1376 # should be external links.
1377 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1378 $s .= $prefix . '[[' . $line ;
1379 continue;
1380 }
1381
1382 # Make subpage if necessary
1383 if( $useSubpages ) {
1384 $link = $this->maybeDoSubpageLink( $m[1], $text );
1385 } else {
1386 $link = $m[1];
1387 }
1388
1389 $noforce = (substr($m[1], 0, 1) != ':');
1390 if (!$noforce) {
1391 # Strip off leading ':'
1392 $link = substr($link, 1);
1393 }
1394
1395 $nt = Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1396 if( !$nt ) {
1397 $s .= $prefix . '[[' . $line;
1398 continue;
1399 }
1400
1401 #check other language variants of the link
1402 #if the article does not exist
1403 if( $checkVariantLink
1404 && $nt->getArticleID() == 0 ) {
1405 $wgContLang->findVariantLink($link, $nt);
1406 }
1407
1408 $ns = $nt->getNamespace();
1409 $iw = $nt->getInterWiki();
1410
1411 if ($might_be_img) { # if this is actually an invalid link
1412 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1413 $found = false;
1414 while (isset ($a[$k+1]) ) {
1415 #look at the next 'line' to see if we can close it there
1416 $spliced = array_splice( $a, $k + 1, 1 );
1417 $next_line = array_shift( $spliced );
1418 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1419 # the first ]] closes the inner link, the second the image
1420 $found = true;
1421 $text .= '[[' . $m[1];
1422 $trail = $m[2];
1423 break;
1424 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1425 #if there's exactly one ]] that's fine, we'll keep looking
1426 $text .= '[[' . $m[0];
1427 } else {
1428 #if $next_line is invalid too, we need look no further
1429 $text .= '[[' . $next_line;
1430 break;
1431 }
1432 }
1433 if ( !$found ) {
1434 # we couldn't find the end of this imageLink, so output it raw
1435 #but don't ignore what might be perfectly normal links in the text we've examined
1436 $text = $this->replaceInternalLinks($text);
1437 $s .= $prefix . '[[' . $link . '|' . $text;
1438 # note: no $trail, because without an end, there *is* no trail
1439 continue;
1440 }
1441 } else { #it's not an image, so output it raw
1442 $s .= $prefix . '[[' . $link . '|' . $text;
1443 # note: no $trail, because without an end, there *is* no trail
1444 continue;
1445 }
1446 }
1447
1448 $wasblank = ( '' == $text );
1449 if( $wasblank ) $text = $link;
1450
1451
1452 # Link not escaped by : , create the various objects
1453 if( $noforce ) {
1454
1455 # Interwikis
1456 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1457 $this->mOutput->addLanguageLink( $nt->getFullText() );
1458 $s = rtrim($s . "\n");
1459 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1460 continue;
1461 }
1462
1463 if ( $ns == NS_IMAGE ) {
1464 wfProfileIn( "$fname-image" );
1465 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1466 # recursively parse links inside the image caption
1467 # actually, this will parse them in any other parameters, too,
1468 # but it might be hard to fix that, and it doesn't matter ATM
1469 $text = $this->replaceExternalLinks($text);
1470 $text = $this->replaceInternalLinks($text);
1471
1472 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1473 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1474 $this->mOutput->addImage( $nt->getDBkey() );
1475
1476 wfProfileOut( "$fname-image" );
1477 continue;
1478 }
1479 wfProfileOut( "$fname-image" );
1480
1481 }
1482
1483 if ( $ns == NS_CATEGORY ) {
1484 wfProfileIn( "$fname-category" );
1485 $s = rtrim($s . "\n"); # bug 87
1486
1487 if ( $wasblank ) {
1488 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1489 $sortkey = $this->mTitle->getText();
1490 } else {
1491 $sortkey = $this->mTitle->getPrefixedText();
1492 }
1493 } else {
1494 $sortkey = $text;
1495 }
1496 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1497 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1498 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1499
1500 /**
1501 * Strip the whitespace Category links produce, see bug 87
1502 * @todo We might want to use trim($tmp, "\n") here.
1503 */
1504 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1505
1506 wfProfileOut( "$fname-category" );
1507 continue;
1508 }
1509 }
1510
1511 if( ( $nt->getPrefixedText() === $selflink ) &&
1512 ( $nt->getFragment() === '' ) ) {
1513 # Self-links are handled specially; generally de-link and change to bold.
1514 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1515 continue;
1516 }
1517
1518 # Special and Media are pseudo-namespaces; no pages actually exist in them
1519 if( $ns == NS_MEDIA ) {
1520 $link = $sk->makeMediaLinkObj( $nt, $text );
1521 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1522 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1523 $this->mOutput->addImage( $nt->getDBkey() );
1524 continue;
1525 } elseif( $ns == NS_SPECIAL ) {
1526 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1527 continue;
1528 } elseif( $ns == NS_IMAGE ) {
1529 $img = Image::newFromTitle( $nt );
1530 if( $img->exists() ) {
1531 // Force a blue link if the file exists; may be a remote
1532 // upload on the shared repository, and we want to see its
1533 // auto-generated page.
1534 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1535 continue;
1536 }
1537 }
1538 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1539 }
1540 wfProfileOut( $fname );
1541 return $s;
1542 }
1543
1544 /**
1545 * Make a link placeholder. The text returned can be later resolved to a real link with
1546 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1547 * parsing of interwiki links, and secondly to allow all extistence checks and
1548 * article length checks (for stub links) to be bundled into a single query.
1549 *
1550 */
1551 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1552 if ( ! is_object($nt) ) {
1553 # Fail gracefully
1554 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1555 } else {
1556 # Separate the link trail from the rest of the link
1557 list( $inside, $trail ) = Linker::splitTrail( $trail );
1558
1559 if ( $nt->isExternal() ) {
1560 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1561 $this->mInterwikiLinkHolders['titles'][] = $nt;
1562 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1563 } else {
1564 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1565 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1566 $this->mLinkHolders['queries'][] = $query;
1567 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1568 $this->mLinkHolders['titles'][] = $nt;
1569
1570 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1571 }
1572 }
1573 return $retVal;
1574 }
1575
1576 /**
1577 * Render a forced-blue link inline; protect against double expansion of
1578 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1579 * Since this little disaster has to split off the trail text to avoid
1580 * breaking URLs in the following text without breaking trails on the
1581 * wiki links, it's been made into a horrible function.
1582 *
1583 * @param Title $nt
1584 * @param string $text
1585 * @param string $query
1586 * @param string $trail
1587 * @param string $prefix
1588 * @return string HTML-wikitext mix oh yuck
1589 */
1590 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1591 list( $inside, $trail ) = Linker::splitTrail( $trail );
1592 $sk =& $this->mOptions->getSkin();
1593 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1594 return $this->armorLinks( $link ) . $trail;
1595 }
1596
1597 /**
1598 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1599 * going to go through further parsing steps before inline URL expansion.
1600 *
1601 * In particular this is important when using action=render, which causes
1602 * full URLs to be included.
1603 *
1604 * Oh man I hate our multi-layer parser!
1605 *
1606 * @param string more-or-less HTML
1607 * @return string less-or-more HTML with NOPARSE bits
1608 */
1609 function armorLinks( $text ) {
1610 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1611 "{$this->mUniqPrefix}NOPARSE$1", $text );
1612 }
1613
1614 /**
1615 * Return true if subpage links should be expanded on this page.
1616 * @return bool
1617 */
1618 function areSubpagesAllowed() {
1619 # Some namespaces don't allow subpages
1620 global $wgNamespacesWithSubpages;
1621 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1622 }
1623
1624 /**
1625 * Handle link to subpage if necessary
1626 * @param string $target the source of the link
1627 * @param string &$text the link text, modified as necessary
1628 * @return string the full name of the link
1629 * @access private
1630 */
1631 function maybeDoSubpageLink($target, &$text) {
1632 # Valid link forms:
1633 # Foobar -- normal
1634 # :Foobar -- override special treatment of prefix (images, language links)
1635 # /Foobar -- convert to CurrentPage/Foobar
1636 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1637 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1638 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1639
1640 $fname = 'Parser::maybeDoSubpageLink';
1641 wfProfileIn( $fname );
1642 $ret = $target; # default return value is no change
1643
1644 # Some namespaces don't allow subpages,
1645 # so only perform processing if subpages are allowed
1646 if( $this->areSubpagesAllowed() ) {
1647 # Look at the first character
1648 if( $target != '' && $target{0} == '/' ) {
1649 # / at end means we don't want the slash to be shown
1650 if( substr( $target, -1, 1 ) == '/' ) {
1651 $target = substr( $target, 1, -1 );
1652 $noslash = $target;
1653 } else {
1654 $noslash = substr( $target, 1 );
1655 }
1656
1657 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1658 if( '' === $text ) {
1659 $text = $target;
1660 } # this might be changed for ugliness reasons
1661 } else {
1662 # check for .. subpage backlinks
1663 $dotdotcount = 0;
1664 $nodotdot = $target;
1665 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1666 ++$dotdotcount;
1667 $nodotdot = substr( $nodotdot, 3 );
1668 }
1669 if($dotdotcount > 0) {
1670 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1671 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1672 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1673 # / at the end means don't show full path
1674 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1675 $nodotdot = substr( $nodotdot, 0, -1 );
1676 if( '' === $text ) {
1677 $text = $nodotdot;
1678 }
1679 }
1680 $nodotdot = trim( $nodotdot );
1681 if( $nodotdot != '' ) {
1682 $ret .= '/' . $nodotdot;
1683 }
1684 }
1685 }
1686 }
1687 }
1688
1689 wfProfileOut( $fname );
1690 return $ret;
1691 }
1692
1693 /**#@+
1694 * Used by doBlockLevels()
1695 * @access private
1696 */
1697 /* private */ function closeParagraph() {
1698 $result = '';
1699 if ( '' != $this->mLastSection ) {
1700 $result = '</' . $this->mLastSection . ">\n";
1701 }
1702 $this->mInPre = false;
1703 $this->mLastSection = '';
1704 return $result;
1705 }
1706 # getCommon() returns the length of the longest common substring
1707 # of both arguments, starting at the beginning of both.
1708 #
1709 /* private */ function getCommon( $st1, $st2 ) {
1710 $fl = strlen( $st1 );
1711 $shorter = strlen( $st2 );
1712 if ( $fl < $shorter ) { $shorter = $fl; }
1713
1714 for ( $i = 0; $i < $shorter; ++$i ) {
1715 if ( $st1{$i} != $st2{$i} ) { break; }
1716 }
1717 return $i;
1718 }
1719 # These next three functions open, continue, and close the list
1720 # element appropriate to the prefix character passed into them.
1721 #
1722 /* private */ function openList( $char ) {
1723 $result = $this->closeParagraph();
1724
1725 if ( '*' == $char ) { $result .= '<ul><li>'; }
1726 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1727 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1728 else if ( ';' == $char ) {
1729 $result .= '<dl><dt>';
1730 $this->mDTopen = true;
1731 }
1732 else { $result = '<!-- ERR 1 -->'; }
1733
1734 return $result;
1735 }
1736
1737 /* private */ function nextItem( $char ) {
1738 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1739 else if ( ':' == $char || ';' == $char ) {
1740 $close = '</dd>';
1741 if ( $this->mDTopen ) { $close = '</dt>'; }
1742 if ( ';' == $char ) {
1743 $this->mDTopen = true;
1744 return $close . '<dt>';
1745 } else {
1746 $this->mDTopen = false;
1747 return $close . '<dd>';
1748 }
1749 }
1750 return '<!-- ERR 2 -->';
1751 }
1752
1753 /* private */ function closeList( $char ) {
1754 if ( '*' == $char ) { $text = '</li></ul>'; }
1755 else if ( '#' == $char ) { $text = '</li></ol>'; }
1756 else if ( ':' == $char ) {
1757 if ( $this->mDTopen ) {
1758 $this->mDTopen = false;
1759 $text = '</dt></dl>';
1760 } else {
1761 $text = '</dd></dl>';
1762 }
1763 }
1764 else { return '<!-- ERR 3 -->'; }
1765 return $text."\n";
1766 }
1767 /**#@-*/
1768
1769 /**
1770 * Make lists from lines starting with ':', '*', '#', etc.
1771 *
1772 * @access private
1773 * @return string the lists rendered as HTML
1774 */
1775 function doBlockLevels( $text, $linestart ) {
1776 $fname = 'Parser::doBlockLevels';
1777 wfProfileIn( $fname );
1778
1779 # Parsing through the text line by line. The main thing
1780 # happening here is handling of block-level elements p, pre,
1781 # and making lists from lines starting with * # : etc.
1782 #
1783 $textLines = explode( "\n", $text );
1784
1785 $lastPrefix = $output = '';
1786 $this->mDTopen = $inBlockElem = false;
1787 $prefixLength = 0;
1788 $paragraphStack = false;
1789
1790 if ( !$linestart ) {
1791 $output .= array_shift( $textLines );
1792 }
1793 foreach ( $textLines as $oLine ) {
1794 $lastPrefixLength = strlen( $lastPrefix );
1795 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1796 $preOpenMatch = preg_match('/<pre/i', $oLine );
1797 if ( !$this->mInPre ) {
1798 # Multiple prefixes may abut each other for nested lists.
1799 $prefixLength = strspn( $oLine, '*#:;' );
1800 $pref = substr( $oLine, 0, $prefixLength );
1801
1802 # eh?
1803 $pref2 = str_replace( ';', ':', $pref );
1804 $t = substr( $oLine, $prefixLength );
1805 $this->mInPre = !empty($preOpenMatch);
1806 } else {
1807 # Don't interpret any other prefixes in preformatted text
1808 $prefixLength = 0;
1809 $pref = $pref2 = '';
1810 $t = $oLine;
1811 }
1812
1813 # List generation
1814 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1815 # Same as the last item, so no need to deal with nesting or opening stuff
1816 $output .= $this->nextItem( substr( $pref, -1 ) );
1817 $paragraphStack = false;
1818
1819 if ( substr( $pref, -1 ) == ';') {
1820 # The one nasty exception: definition lists work like this:
1821 # ; title : definition text
1822 # So we check for : in the remainder text to split up the
1823 # title and definition, without b0rking links.
1824 $term = $t2 = '';
1825 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1826 $t = $t2;
1827 $output .= $term . $this->nextItem( ':' );
1828 }
1829 }
1830 } elseif( $prefixLength || $lastPrefixLength ) {
1831 # Either open or close a level...
1832 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1833 $paragraphStack = false;
1834
1835 while( $commonPrefixLength < $lastPrefixLength ) {
1836 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1837 --$lastPrefixLength;
1838 }
1839 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1840 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1841 }
1842 while ( $prefixLength > $commonPrefixLength ) {
1843 $char = substr( $pref, $commonPrefixLength, 1 );
1844 $output .= $this->openList( $char );
1845
1846 if ( ';' == $char ) {
1847 # FIXME: This is dupe of code above
1848 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1849 $t = $t2;
1850 $output .= $term . $this->nextItem( ':' );
1851 }
1852 }
1853 ++$commonPrefixLength;
1854 }
1855 $lastPrefix = $pref2;
1856 }
1857 if( 0 == $prefixLength ) {
1858 wfProfileIn( "$fname-paragraph" );
1859 # No prefix (not in list)--go to paragraph mode
1860 // XXX: use a stack for nestable elements like span, table and div
1861 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1862 $closematch = preg_match(
1863 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1864 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1865 if ( $openmatch or $closematch ) {
1866 $paragraphStack = false;
1867 $output .= $this->closeParagraph();
1868 if ( $preOpenMatch and !$preCloseMatch ) {
1869 $this->mInPre = true;
1870 }
1871 if ( $closematch ) {
1872 $inBlockElem = false;
1873 } else {
1874 $inBlockElem = true;
1875 }
1876 } else if ( !$inBlockElem && !$this->mInPre ) {
1877 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1878 // pre
1879 if ($this->mLastSection != 'pre') {
1880 $paragraphStack = false;
1881 $output .= $this->closeParagraph().'<pre>';
1882 $this->mLastSection = 'pre';
1883 }
1884 $t = substr( $t, 1 );
1885 } else {
1886 // paragraph
1887 if ( '' == trim($t) ) {
1888 if ( $paragraphStack ) {
1889 $output .= $paragraphStack.'<br />';
1890 $paragraphStack = false;
1891 $this->mLastSection = 'p';
1892 } else {
1893 if ($this->mLastSection != 'p' ) {
1894 $output .= $this->closeParagraph();
1895 $this->mLastSection = '';
1896 $paragraphStack = '<p>';
1897 } else {
1898 $paragraphStack = '</p><p>';
1899 }
1900 }
1901 } else {
1902 if ( $paragraphStack ) {
1903 $output .= $paragraphStack;
1904 $paragraphStack = false;
1905 $this->mLastSection = 'p';
1906 } else if ($this->mLastSection != 'p') {
1907 $output .= $this->closeParagraph().'<p>';
1908 $this->mLastSection = 'p';
1909 }
1910 }
1911 }
1912 }
1913 wfProfileOut( "$fname-paragraph" );
1914 }
1915 // somewhere above we forget to get out of pre block (bug 785)
1916 if($preCloseMatch && $this->mInPre) {
1917 $this->mInPre = false;
1918 }
1919 if ($paragraphStack === false) {
1920 $output .= $t."\n";
1921 }
1922 }
1923 while ( $prefixLength ) {
1924 $output .= $this->closeList( $pref2{$prefixLength-1} );
1925 --$prefixLength;
1926 }
1927 if ( '' != $this->mLastSection ) {
1928 $output .= '</' . $this->mLastSection . '>';
1929 $this->mLastSection = '';
1930 }
1931
1932 wfProfileOut( $fname );
1933 return $output;
1934 }
1935
1936 /**
1937 * Split up a string on ':', ignoring any occurences inside
1938 * <a>..</a> or <span>...</span>
1939 * @param string $str the string to split
1940 * @param string &$before set to everything before the ':'
1941 * @param string &$after set to everything after the ':'
1942 * return string the position of the ':', or false if none found
1943 */
1944 function findColonNoLinks($str, &$before, &$after) {
1945 # I wonder if we should make this count all tags, not just <a>
1946 # and <span>. That would prevent us from matching a ':' that
1947 # comes in the middle of italics other such formatting....
1948 # -- Wil
1949 $fname = 'Parser::findColonNoLinks';
1950 wfProfileIn( $fname );
1951 $pos = 0;
1952 do {
1953 $colon = strpos($str, ':', $pos);
1954
1955 if ($colon !== false) {
1956 $before = substr($str, 0, $colon);
1957 $after = substr($str, $colon + 1);
1958
1959 # Skip any ':' within <a> or <span> pairs
1960 $a = substr_count($before, '<a');
1961 $s = substr_count($before, '<span');
1962 $ca = substr_count($before, '</a>');
1963 $cs = substr_count($before, '</span>');
1964
1965 if ($a <= $ca and $s <= $cs) {
1966 # Tags are balanced before ':'; ok
1967 break;
1968 }
1969 $pos = $colon + 1;
1970 }
1971 } while ($colon !== false);
1972 wfProfileOut( $fname );
1973 return $colon;
1974 }
1975
1976 /**
1977 * Return value of a magic variable (like PAGENAME)
1978 *
1979 * @access private
1980 */
1981 function getVariableValue( $index ) {
1982 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1983
1984 /**
1985 * Some of these require message or data lookups and can be
1986 * expensive to check many times.
1987 */
1988 static $varCache = array();
1989 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1990 if ( isset( $varCache[$index] ) )
1991 return $varCache[$index];
1992
1993 $ts = time();
1994 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1995
1996 switch ( $index ) {
1997 case MAG_CURRENTMONTH:
1998 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1999 case MAG_CURRENTMONTHNAME:
2000 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2001 case MAG_CURRENTMONTHNAMEGEN:
2002 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2003 case MAG_CURRENTMONTHABBREV:
2004 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2005 case MAG_CURRENTDAY:
2006 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2007 case MAG_CURRENTDAY2:
2008 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2009 case MAG_PAGENAME:
2010 return $this->mTitle->getText();
2011 case MAG_PAGENAMEE:
2012 return $this->mTitle->getPartialURL();
2013 case MAG_FULLPAGENAME:
2014 return $this->mTitle->getPrefixedText();
2015 case MAG_FULLPAGENAMEE:
2016 return $this->mTitle->getPrefixedURL();
2017 case MAG_REVISIONID:
2018 return $this->mRevisionId;
2019 case MAG_NAMESPACE:
2020 return $wgContLang->getNsText( $this->mTitle->getNamespace() );
2021 case MAG_NAMESPACEE:
2022 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2023 case MAG_CURRENTDAYNAME:
2024 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
2025 case MAG_CURRENTYEAR:
2026 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2027 case MAG_CURRENTTIME:
2028 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2029 case MAG_CURRENTWEEK:
2030 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2031 // int to remove the padding
2032 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2033 case MAG_CURRENTDOW:
2034 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2035 case MAG_NUMBEROFARTICLES:
2036 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2037 case MAG_NUMBEROFFILES:
2038 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2039 case MAG_SITENAME:
2040 return $wgSitename;
2041 case MAG_SERVER:
2042 return $wgServer;
2043 case MAG_SERVERNAME:
2044 return $wgServerName;
2045 case MAG_SCRIPTPATH:
2046 return $wgScriptPath;
2047 default:
2048 $ret = null;
2049 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2050 return $ret;
2051 else
2052 return null;
2053 }
2054 }
2055
2056 /**
2057 * initialise the magic variables (like CURRENTMONTHNAME)
2058 *
2059 * @access private
2060 */
2061 function initialiseVariables() {
2062 $fname = 'Parser::initialiseVariables';
2063 wfProfileIn( $fname );
2064 global $wgVariableIDs;
2065 $this->mVariables = array();
2066 foreach ( $wgVariableIDs as $id ) {
2067 $mw =& MagicWord::get( $id );
2068 $mw->addToArray( $this->mVariables, $id );
2069 }
2070 wfProfileOut( $fname );
2071 }
2072
2073 /**
2074 * parse any parentheses in format ((title|part|part))
2075 * and call callbacks to get a replacement text for any found piece
2076 *
2077 * @param string $text The text to parse
2078 * @param array $callbacks rules in form:
2079 * '{' => array( # opening parentheses
2080 * 'end' => '}', # closing parentheses
2081 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2082 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2083 * )
2084 * )
2085 * @access private
2086 */
2087 function replace_callback ($text, $callbacks) {
2088 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2089 $lastOpeningBrace = -1; # last not closed parentheses
2090
2091 for ($i = 0; $i < strlen($text); $i++) {
2092 # check for any opening brace
2093 $rule = null;
2094 $nextPos = -1;
2095 foreach ($callbacks as $key => $value) {
2096 $pos = strpos ($text, $key, $i);
2097 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
2098 $rule = $value;
2099 $nextPos = $pos;
2100 }
2101 }
2102
2103 if ($lastOpeningBrace >= 0) {
2104 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2105
2106 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2107 $rule = null;
2108 $nextPos = $pos;
2109 }
2110
2111 $pos = strpos ($text, '|', $i);
2112
2113 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2114 $rule = null;
2115 $nextPos = $pos;
2116 }
2117 }
2118
2119 if ($nextPos == -1)
2120 break;
2121
2122 $i = $nextPos;
2123
2124 # found openning brace, lets add it to parentheses stack
2125 if (null != $rule) {
2126 $piece = array('brace' => $text[$i],
2127 'braceEnd' => $rule['end'],
2128 'count' => 1,
2129 'title' => '',
2130 'parts' => null);
2131
2132 # count openning brace characters
2133 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2134 $piece['count']++;
2135 $i++;
2136 }
2137
2138 $piece['startAt'] = $i+1;
2139 $piece['partStart'] = $i+1;
2140
2141 # we need to add to stack only if openning brace count is enough for any given rule
2142 foreach ($rule['cb'] as $cnt => $fn) {
2143 if ($piece['count'] >= $cnt) {
2144 $lastOpeningBrace ++;
2145 $openingBraceStack[$lastOpeningBrace] = $piece;
2146 break;
2147 }
2148 }
2149
2150 continue;
2151 }
2152 else if ($lastOpeningBrace >= 0) {
2153 # first check if it is a closing brace
2154 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2155 # lets check if it is enough characters for closing brace
2156 $count = 1;
2157 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2158 $count++;
2159
2160 # if there are more closing parentheses than opening ones, we parse less
2161 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2162 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2163
2164 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2165 $matchingCount = 0;
2166 $matchingCallback = null;
2167 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2168 if ($count >= $cnt && $matchingCount < $cnt) {
2169 $matchingCount = $cnt;
2170 $matchingCallback = $fn;
2171 }
2172 }
2173
2174 if ($matchingCount == 0) {
2175 $i += $count - 1;
2176 continue;
2177 }
2178
2179 # lets set a title or last part (if '|' was found)
2180 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2181 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2182 else
2183 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2184
2185 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2186 $pieceEnd = $i + $matchingCount;
2187
2188 if( is_callable( $matchingCallback ) ) {
2189 $cbArgs = array (
2190 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2191 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2192 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2193 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2194 );
2195 # finally we can call a user callback and replace piece of text
2196 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2197 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2198 $i = $pieceStart + strlen($replaceWith) - 1;
2199 }
2200 else {
2201 # null value for callback means that parentheses should be parsed, but not replaced
2202 $i += $matchingCount - 1;
2203 }
2204
2205 # reset last openning parentheses, but keep it in case there are unused characters
2206 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2207 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2208 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2209 'title' => '',
2210 'parts' => null,
2211 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2212 $openingBraceStack[$lastOpeningBrace--] = null;
2213
2214 if ($matchingCount < $piece['count']) {
2215 $piece['count'] -= $matchingCount;
2216 $piece['startAt'] -= $matchingCount;
2217 $piece['partStart'] = $piece['startAt'];
2218 # do we still qualify for any callback with remaining count?
2219 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2220 if ($piece['count'] >= $cnt) {
2221 $lastOpeningBrace ++;
2222 $openingBraceStack[$lastOpeningBrace] = $piece;
2223 break;
2224 }
2225 }
2226 }
2227 continue;
2228 }
2229
2230 # lets set a title if it is a first separator, or next part otherwise
2231 if ($text[$i] == '|') {
2232 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2233 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2234 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2235 }
2236 else
2237 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2238
2239 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2240 }
2241 }
2242 }
2243
2244 return $text;
2245 }
2246
2247 /**
2248 * Replace magic variables, templates, and template arguments
2249 * with the appropriate text. Templates are substituted recursively,
2250 * taking care to avoid infinite loops.
2251 *
2252 * Note that the substitution depends on value of $mOutputType:
2253 * OT_WIKI: only {{subst:}} templates
2254 * OT_MSG: only magic variables
2255 * OT_HTML: all templates and magic variables
2256 *
2257 * @param string $tex The text to transform
2258 * @param array $args Key-value pairs representing template parameters to substitute
2259 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2260 * @access private
2261 */
2262 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2263 # Prevent too big inclusions
2264 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2265 return $text;
2266 }
2267
2268 $fname = 'Parser::replaceVariables';
2269 wfProfileIn( $fname );
2270
2271 # This function is called recursively. To keep track of arguments we need a stack:
2272 array_push( $this->mArgStack, $args );
2273
2274 $braceCallbacks = array();
2275 if ( !$argsOnly ) {
2276 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2277 }
2278 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2279 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2280 }
2281 $callbacks = array();
2282 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2283 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2284 $text = $this->replace_callback ($text, $callbacks);
2285
2286 array_pop( $this->mArgStack );
2287
2288 wfProfileOut( $fname );
2289 return $text;
2290 }
2291
2292 /**
2293 * Replace magic variables
2294 * @access private
2295 */
2296 function variableSubstitution( $matches ) {
2297 $fname = 'Parser::variableSubstitution';
2298 $varname = $matches[1];
2299 wfProfileIn( $fname );
2300 if ( !$this->mVariables ) {
2301 $this->initialiseVariables();
2302 }
2303 $skip = false;
2304 if ( $this->mOutputType == OT_WIKI ) {
2305 # Do only magic variables prefixed by SUBST
2306 $mwSubst =& MagicWord::get( MAG_SUBST );
2307 if (!$mwSubst->matchStartAndRemove( $varname ))
2308 $skip = true;
2309 # Note that if we don't substitute the variable below,
2310 # we don't remove the {{subst:}} magic word, in case
2311 # it is a template rather than a magic variable.
2312 }
2313 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2314 $id = $this->mVariables[$varname];
2315 $text = $this->getVariableValue( $id );
2316 $this->mOutput->mContainsOldMagic = true;
2317 } else {
2318 $text = $matches[0];
2319 }
2320 wfProfileOut( $fname );
2321 return $text;
2322 }
2323
2324 # Split template arguments
2325 function getTemplateArgs( $argsString ) {
2326 if ( $argsString === '' ) {
2327 return array();
2328 }
2329
2330 $args = explode( '|', substr( $argsString, 1 ) );
2331
2332 # If any of the arguments contains a '[[' but no ']]', it needs to be
2333 # merged with the next arg because the '|' character between belongs
2334 # to the link syntax and not the template parameter syntax.
2335 $argc = count($args);
2336
2337 for ( $i = 0; $i < $argc-1; $i++ ) {
2338 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2339 $args[$i] .= '|'.$args[$i+1];
2340 array_splice($args, $i+1, 1);
2341 $i--;
2342 $argc--;
2343 }
2344 }
2345
2346 return $args;
2347 }
2348
2349 /**
2350 * Return the text of a template, after recursively
2351 * replacing any variables or templates within the template.
2352 *
2353 * @param array $piece The parts of the template
2354 * $piece['text']: matched text
2355 * $piece['title']: the title, i.e. the part before the |
2356 * $piece['parts']: the parameter array
2357 * @return string the text of the template
2358 * @access private
2359 */
2360 function braceSubstitution( $piece ) {
2361 global $wgContLang;
2362 $fname = 'Parser::braceSubstitution';
2363 wfProfileIn( $fname );
2364
2365 # Flags
2366 $found = false; # $text has been filled
2367 $nowiki = false; # wiki markup in $text should be escaped
2368 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2369 $noargs = false; # Don't replace triple-brace arguments in $text
2370 $replaceHeadings = false; # Make the edit section links go to the template not the article
2371 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2372 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2373
2374 # Title object, where $text came from
2375 $title = NULL;
2376
2377 $linestart = '';
2378
2379 # $part1 is the bit before the first |, and must contain only title characters
2380 # $args is a list of arguments, starting from index 0, not including $part1
2381
2382 $part1 = $piece['title'];
2383 # If the third subpattern matched anything, it will start with |
2384
2385 if (null == $piece['parts']) {
2386 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2387 if ($replaceWith != $piece['text']) {
2388 $text = $replaceWith;
2389 $found = true;
2390 $noparse = true;
2391 $noargs = true;
2392 }
2393 }
2394
2395 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2396 $argc = count( $args );
2397
2398 # SUBST
2399 if ( !$found ) {
2400 $mwSubst =& MagicWord::get( MAG_SUBST );
2401 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2402 # One of two possibilities is true:
2403 # 1) Found SUBST but not in the PST phase
2404 # 2) Didn't find SUBST and in the PST phase
2405 # In either case, return without further processing
2406 $text = $piece['text'];
2407 $found = true;
2408 $noparse = true;
2409 $noargs = true;
2410 }
2411 }
2412
2413 # MSG, MSGNW, INT and RAW
2414 if ( !$found ) {
2415 # Check for MSGNW:
2416 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2417 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2418 $nowiki = true;
2419 } else {
2420 # Remove obsolete MSG:
2421 $mwMsg =& MagicWord::get( MAG_MSG );
2422 $mwMsg->matchStartAndRemove( $part1 );
2423 }
2424
2425 # Check for RAW:
2426 $mwRaw =& MagicWord::get( MAG_RAW );
2427 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2428 $forceRawInterwiki = true;
2429 }
2430
2431 # Check if it is an internal message
2432 $mwInt =& MagicWord::get( MAG_INT );
2433 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2434 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2435 $text = $linestart . wfMsgReal( $part1, $args, true );
2436 $found = true;
2437 }
2438 }
2439 }
2440
2441 # NS
2442 if ( !$found ) {
2443 # Check for NS: (namespace expansion)
2444 $mwNs = MagicWord::get( MAG_NS );
2445 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2446 if ( intval( $part1 ) || $part1 == "0" ) {
2447 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2448 $found = true;
2449 } else {
2450 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2451 if ( !is_null( $index ) ) {
2452 $text = $linestart . $wgContLang->getNsText( $index );
2453 $found = true;
2454 }
2455 }
2456 }
2457 }
2458
2459 # LCFIRST, UCFIRST, LC and UC
2460 if ( !$found ) {
2461 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2462 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2463 $lc =& MagicWord::get( MAG_LC );
2464 $uc =& MagicWord::get( MAG_UC );
2465 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2466 $text = $linestart . $wgContLang->lcfirst( $part1 );
2467 $found = true;
2468 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2469 $text = $linestart . $wgContLang->ucfirst( $part1 );
2470 $found = true;
2471 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2472 $text = $linestart . $wgContLang->lc( $part1 );
2473 $found = true;
2474 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2475 $text = $linestart . $wgContLang->uc( $part1 );
2476 $found = true;
2477 }
2478 }
2479
2480 # LOCALURL and FULLURL
2481 if ( !$found ) {
2482 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2483 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2484 $mwFull =& MagicWord::get( MAG_FULLURL );
2485 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2486
2487
2488 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2489 $func = 'getLocalURL';
2490 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2491 $func = 'escapeLocalURL';
2492 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2493 $func = 'getFullURL';
2494 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2495 $func = 'escapeFullURL';
2496 } else {
2497 $func = false;
2498 }
2499
2500 if ( $func !== false ) {
2501 $title = Title::newFromText( $part1 );
2502 if ( !is_null( $title ) ) {
2503 if ( $argc > 0 ) {
2504 $text = $linestart . $title->$func( $args[0] );
2505 } else {
2506 $text = $linestart . $title->$func();
2507 }
2508 $found = true;
2509 }
2510 }
2511 }
2512
2513 # GRAMMAR
2514 if ( !$found && $argc == 1 ) {
2515 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2516 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2517 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2518 $found = true;
2519 }
2520 }
2521
2522 # PLURAL
2523 if ( !$found && $argc >= 2 ) {
2524 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2525 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2526 if ($argc==2) {$args[2]=$args[1];}
2527 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2528 $found = true;
2529 }
2530 }
2531
2532 # Template table test
2533
2534 # Did we encounter this template already? If yes, it is in the cache
2535 # and we need to check for loops.
2536 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
2537 $found = true;
2538
2539 # Infinite loop test
2540 if ( isset( $this->mTemplatePath[$part1] ) ) {
2541 $noparse = true;
2542 $noargs = true;
2543 $found = true;
2544 $text = $linestart .
2545 '{{' . $part1 . '}}' .
2546 '<!-- WARNING: template loop detected -->';
2547 wfDebug( "$fname: template loop broken at '$part1'\n" );
2548 } else {
2549 # set $text to cached message.
2550 $text = $linestart . $this->mTemplates[$piece['title']];
2551 }
2552 }
2553
2554 # Load from database
2555 $lastPathLevel = $this->mTemplatePath;
2556 if ( !$found ) {
2557 $ns = NS_TEMPLATE;
2558 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2559 if ($subpage !== '') {
2560 $ns = $this->mTitle->getNamespace();
2561 }
2562 $title = Title::newFromText( $part1, $ns );
2563
2564 if ( !is_null( $title ) ) {
2565 if ( !$title->isExternal() ) {
2566 # Check for excessive inclusion
2567 $dbk = $title->getPrefixedDBkey();
2568 if ( $this->incrementIncludeCount( $dbk ) ) {
2569 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2570 # Capture special page output
2571 $text = SpecialPage::capturePath( $title );
2572 if ( is_string( $text ) ) {
2573 $found = true;
2574 $noparse = true;
2575 $noargs = true;
2576 $isHTML = true;
2577 $this->disableCache();
2578 }
2579 } else {
2580 $articleContent = $this->fetchTemplate( $title );
2581 if ( $articleContent !== false ) {
2582 $found = true;
2583 $text = $articleContent;
2584 $replaceHeadings = true;
2585 }
2586 }
2587 }
2588
2589 # If the title is valid but undisplayable, make a link to it
2590 if ( $this->mOutputType == OT_HTML && !$found ) {
2591 $text = '[['.$title->getPrefixedText().']]';
2592 $found = true;
2593 }
2594 } elseif ( $title->isTrans() ) {
2595 // Interwiki transclusion
2596 if ( $this->mOutputType == OT_HTML && !$forceRawInterwiki ) {
2597 $text = $this->interwikiTransclude( $title, 'render' );
2598 $isHTML = true;
2599 $noparse = true;
2600 } else {
2601 $text = $this->interwikiTransclude( $title, 'raw' );
2602 $replaceHeadings = true;
2603 }
2604 $found = true;
2605 }
2606
2607 # Template cache array insertion
2608 # Use the original $piece['title'] not the mangled $part1, so that
2609 # modifiers such as RAW: produce separate cache entries
2610 if( $found ) {
2611 $this->mTemplates[$piece['title']] = $text;
2612 $text = $linestart . $text;
2613 }
2614 }
2615 }
2616
2617 # Recursive parsing, escaping and link table handling
2618 # Only for HTML output
2619 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2620 $text = wfEscapeWikiText( $text );
2621 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found ) {
2622 if ( !$noargs ) {
2623 # Clean up argument array
2624 $assocArgs = array();
2625 $index = 1;
2626 foreach( $args as $arg ) {
2627 $eqpos = strpos( $arg, '=' );
2628 if ( $eqpos === false ) {
2629 $assocArgs[$index++] = $arg;
2630 } else {
2631 $name = trim( substr( $arg, 0, $eqpos ) );
2632 $value = trim( substr( $arg, $eqpos+1 ) );
2633 if ( $value === false ) {
2634 $value = '';
2635 }
2636 if ( $name !== false ) {
2637 $assocArgs[$name] = $value;
2638 }
2639 }
2640 }
2641
2642 # Add a new element to the templace recursion path
2643 $this->mTemplatePath[$part1] = 1;
2644 }
2645
2646 if ( !$noparse ) {
2647 # If there are any <onlyinclude> tags, only include them
2648 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2649 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2650 $text = '';
2651 foreach ($m[1] as $piece)
2652 $text .= $piece;
2653 }
2654 # Remove <noinclude> sections and <includeonly> tags
2655 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2656 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2657
2658 if( $this->mOutputType == OT_HTML ) {
2659 # Strip <nowiki>, <pre>, etc.
2660 $text = $this->strip( $text, $this->mStripState );
2661 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2662 }
2663 $text = $this->replaceVariables( $text, $assocArgs );
2664
2665 # If the template begins with a table or block-level
2666 # element, it should be treated as beginning a new line.
2667 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2668 $text = "\n" . $text;
2669 }
2670 } elseif ( !$noargs ) {
2671 # $noparse and !$noargs
2672 # Just replace the arguments, not any double-brace items
2673 # This is used for rendered interwiki transclusion
2674 $text = $this->replaceVariables( $text, $assocArgs, true );
2675 }
2676 }
2677 # Prune lower levels off the recursion check path
2678 $this->mTemplatePath = $lastPathLevel;
2679
2680 if ( !$found ) {
2681 wfProfileOut( $fname );
2682 return $piece['text'];
2683 } else {
2684 if ( $isHTML ) {
2685 # Replace raw HTML by a placeholder
2686 # Add a blank line preceding, to prevent it from mucking up
2687 # immediately preceding headings
2688 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2689 } else {
2690 # replace ==section headers==
2691 # XXX this needs to go away once we have a better parser.
2692 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2693 if( !is_null( $title ) )
2694 $encodedname = base64_encode($title->getPrefixedDBkey());
2695 else
2696 $encodedname = base64_encode("");
2697 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2698 PREG_SPLIT_DELIM_CAPTURE);
2699 $text = '';
2700 $nsec = 0;
2701 for( $i = 0; $i < count($m); $i += 2 ) {
2702 $text .= $m[$i];
2703 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2704 $hl = $m[$i + 1];
2705 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2706 $text .= $hl;
2707 continue;
2708 }
2709 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2710 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2711 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2712
2713 $nsec++;
2714 }
2715 }
2716 }
2717 }
2718
2719 # Prune lower levels off the recursion check path
2720 $this->mTemplatePath = $lastPathLevel;
2721
2722 if ( !$found ) {
2723 wfProfileOut( $fname );
2724 return $piece['text'];
2725 } else {
2726 wfProfileOut( $fname );
2727 return $text;
2728 }
2729 }
2730
2731 /**
2732 * Fetch the unparsed text of a template and register a reference to it.
2733 */
2734 function fetchTemplate( $title ) {
2735 $text = false;
2736 // Loop to fetch the article, with up to 1 redirect
2737 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
2738 $rev = Revision::newFromTitle( $title );
2739 $this->mOutput->addTemplate( $title, $title->getArticleID() );
2740 if ( !$rev ) {
2741 break;
2742 }
2743 $text = $rev->getText();
2744 if ( $text === false ) {
2745 break;
2746 }
2747 // Redirect?
2748 $title = Title::newFromRedirect( $text );
2749 }
2750 return $text;
2751 }
2752
2753 /**
2754 * Transclude an interwiki link.
2755 */
2756 function interwikiTransclude( $title, $action ) {
2757 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2758
2759 if (!$wgEnableScaryTranscluding)
2760 return wfMsg('scarytranscludedisabled');
2761
2762 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2763 // But we'll handle it generally anyway
2764 if ( $title->getNamespace() ) {
2765 // Use the canonical namespace, which should work anywhere
2766 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2767 } else {
2768 $articleName = $title->getDBkey();
2769 }
2770
2771 $url = str_replace('$1', urlencode($articleName), Title::getInterwikiLink($title->getInterwiki()));
2772 $url .= "?action=$action";
2773 if (strlen($url) > 255)
2774 return wfMsg('scarytranscludetoolong');
2775 return $this->fetchScaryTemplateMaybeFromCache($url);
2776 }
2777
2778 function fetchScaryTemplateMaybeFromCache($url) {
2779 global $wgTranscludeCacheExpiry;
2780 $dbr =& wfGetDB(DB_SLAVE);
2781 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2782 array('tc_url' => $url));
2783 if ($obj) {
2784 $time = $obj->tc_time;
2785 $text = $obj->tc_contents;
2786 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
2787 return $text;
2788 }
2789 }
2790
2791 $text = wfGetHTTP($url);
2792 if (!$text)
2793 return wfMsg('scarytranscludefailed', $url);
2794
2795 $dbw =& wfGetDB(DB_MASTER);
2796 $dbw->replace('transcache', array('tc_url'), array(
2797 'tc_url' => $url,
2798 'tc_time' => time(),
2799 'tc_contents' => $text));
2800 return $text;
2801 }
2802
2803
2804 /**
2805 * Triple brace replacement -- used for template arguments
2806 * @access private
2807 */
2808 function argSubstitution( $matches ) {
2809 $arg = trim( $matches['title'] );
2810 $text = $matches['text'];
2811 $inputArgs = end( $this->mArgStack );
2812
2813 if ( array_key_exists( $arg, $inputArgs ) ) {
2814 $text = $inputArgs[$arg];
2815 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
2816 $text = $matches['parts'][0];
2817 }
2818
2819 return $text;
2820 }
2821
2822 /**
2823 * Returns true if the function is allowed to include this entity
2824 * @access private
2825 */
2826 function incrementIncludeCount( $dbk ) {
2827 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2828 $this->mIncludeCount[$dbk] = 0;
2829 }
2830 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2831 return true;
2832 } else {
2833 return false;
2834 }
2835 }
2836
2837 /**
2838 * This function accomplishes several tasks:
2839 * 1) Auto-number headings if that option is enabled
2840 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2841 * 3) Add a Table of contents on the top for users who have enabled the option
2842 * 4) Auto-anchor headings
2843 *
2844 * It loops through all headlines, collects the necessary data, then splits up the
2845 * string and re-inserts the newly formatted headlines.
2846 *
2847 * @param string $text
2848 * @param boolean $isMain
2849 * @access private
2850 */
2851 function formatHeadings( $text, $isMain=true ) {
2852 global $wgMaxTocLevel, $wgContLang;
2853
2854 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2855 $doShowToc = true;
2856 $forceTocHere = false;
2857 if( !$this->mTitle->userCanEdit() ) {
2858 $showEditLink = 0;
2859 } else {
2860 $showEditLink = $this->mOptions->getEditSection();
2861 }
2862
2863 # Inhibit editsection links if requested in the page
2864 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2865 if( $esw->matchAndRemove( $text ) ) {
2866 $showEditLink = 0;
2867 }
2868 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2869 # do not add TOC
2870 $mw =& MagicWord::get( MAG_NOTOC );
2871 if( $mw->matchAndRemove( $text ) ) {
2872 $doShowToc = false;
2873 }
2874
2875 # Get all headlines for numbering them and adding funky stuff like [edit]
2876 # links - this is for later, but we need the number of headlines right now
2877 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2878
2879 # if there are fewer than 4 headlines in the article, do not show TOC
2880 if( $numMatches < 4 ) {
2881 $doShowToc = false;
2882 }
2883
2884 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2885 # override above conditions and always show TOC at that place
2886
2887 $mw =& MagicWord::get( MAG_TOC );
2888 if($mw->match( $text ) ) {
2889 $doShowToc = true;
2890 $forceTocHere = true;
2891 } else {
2892 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2893 # override above conditions and always show TOC above first header
2894 $mw =& MagicWord::get( MAG_FORCETOC );
2895 if ($mw->matchAndRemove( $text ) ) {
2896 $doShowToc = true;
2897 }
2898 }
2899
2900 # Never ever show TOC if no headers
2901 if( $numMatches < 1 ) {
2902 $doShowToc = false;
2903 }
2904
2905 # We need this to perform operations on the HTML
2906 $sk =& $this->mOptions->getSkin();
2907
2908 # headline counter
2909 $headlineCount = 0;
2910 $sectionCount = 0; # headlineCount excluding template sections
2911
2912 # Ugh .. the TOC should have neat indentation levels which can be
2913 # passed to the skin functions. These are determined here
2914 $toc = '';
2915 $full = '';
2916 $head = array();
2917 $sublevelCount = array();
2918 $levelCount = array();
2919 $toclevel = 0;
2920 $level = 0;
2921 $prevlevel = 0;
2922 $toclevel = 0;
2923 $prevtoclevel = 0;
2924
2925 foreach( $matches[3] as $headline ) {
2926 $istemplate = 0;
2927 $templatetitle = '';
2928 $templatesection = 0;
2929 $numbering = '';
2930
2931 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2932 $istemplate = 1;
2933 $templatetitle = base64_decode($mat[1]);
2934 $templatesection = 1 + (int)base64_decode($mat[2]);
2935 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2936 }
2937
2938 if( $toclevel ) {
2939 $prevlevel = $level;
2940 $prevtoclevel = $toclevel;
2941 }
2942 $level = $matches[1][$headlineCount];
2943
2944 if( $doNumberHeadings || $doShowToc ) {
2945
2946 if ( $level > $prevlevel ) {
2947 # Increase TOC level
2948 $toclevel++;
2949 $sublevelCount[$toclevel] = 0;
2950 $toc .= $sk->tocIndent();
2951 }
2952 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2953 # Decrease TOC level, find level to jump to
2954
2955 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2956 # Can only go down to level 1
2957 $toclevel = 1;
2958 } else {
2959 for ($i = $toclevel; $i > 0; $i--) {
2960 if ( $levelCount[$i] == $level ) {
2961 # Found last matching level
2962 $toclevel = $i;
2963 break;
2964 }
2965 elseif ( $levelCount[$i] < $level ) {
2966 # Found first matching level below current level
2967 $toclevel = $i + 1;
2968 break;
2969 }
2970 }
2971 }
2972
2973 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2974 }
2975 else {
2976 # No change in level, end TOC line
2977 $toc .= $sk->tocLineEnd();
2978 }
2979
2980 $levelCount[$toclevel] = $level;
2981
2982 # count number of headlines for each level
2983 @$sublevelCount[$toclevel]++;
2984 $dot = 0;
2985 for( $i = 1; $i <= $toclevel; $i++ ) {
2986 if( !empty( $sublevelCount[$i] ) ) {
2987 if( $dot ) {
2988 $numbering .= '.';
2989 }
2990 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2991 $dot = 1;
2992 }
2993 }
2994 }
2995
2996 # The canonized header is a version of the header text safe to use for links
2997 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2998 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2999 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
3000
3001 # Remove link placeholders by the link text.
3002 # <!--LINK number-->
3003 # turns into
3004 # link text with suffix
3005 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3006 "\$this->mLinkHolders['texts'][\$1]",
3007 $canonized_headline );
3008 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3009 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3010 $canonized_headline );
3011
3012 # strip out HTML
3013 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3014 $tocline = trim( $canonized_headline );
3015 $canonized_headline = Sanitizer::escapeId( $tocline );
3016 $refers[$headlineCount] = $canonized_headline;
3017
3018 # count how many in assoc. array so we can track dupes in anchors
3019 @$refers[$canonized_headline]++;
3020 $refcount[$headlineCount]=$refers[$canonized_headline];
3021
3022 # Don't number the heading if it is the only one (looks silly)
3023 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3024 # the two are different if the line contains a link
3025 $headline=$numbering . ' ' . $headline;
3026 }
3027
3028 # Create the anchor for linking from the TOC to the section
3029 $anchor = $canonized_headline;
3030 if($refcount[$headlineCount] > 1 ) {
3031 $anchor .= '_' . $refcount[$headlineCount];
3032 }
3033 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3034 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3035 }
3036 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3037 if ( empty( $head[$headlineCount] ) ) {
3038 $head[$headlineCount] = '';
3039 }
3040 if( $istemplate )
3041 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3042 else
3043 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
3044 }
3045
3046 # give headline the correct <h#> tag
3047 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3048
3049 $headlineCount++;
3050 if( !$istemplate )
3051 $sectionCount++;
3052 }
3053
3054 if( $doShowToc ) {
3055 $toc .= $sk->tocUnindent( $toclevel - 1 );
3056 $toc = $sk->tocList( $toc );
3057 }
3058
3059 # split up and insert constructed headlines
3060
3061 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3062 $i = 0;
3063
3064 foreach( $blocks as $block ) {
3065 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3066 # This is the [edit] link that appears for the top block of text when
3067 # section editing is enabled
3068
3069 # Disabled because it broke block formatting
3070 # For example, a bullet point in the top line
3071 # $full .= $sk->editSectionLink(0);
3072 }
3073 $full .= $block;
3074 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3075 # Top anchor now in skin
3076 $full = $full.$toc;
3077 }
3078
3079 if( !empty( $head[$i] ) ) {
3080 $full .= $head[$i];
3081 }
3082 $i++;
3083 }
3084 if($forceTocHere) {
3085 $mw =& MagicWord::get( MAG_TOC );
3086 return $mw->replace( $toc, $full );
3087 } else {
3088 return $full;
3089 }
3090 }
3091
3092 /**
3093 * Return an HTML link for the "ISBN 123456" text
3094 * @access private
3095 */
3096 function magicISBN( $text ) {
3097 $fname = 'Parser::magicISBN';
3098 wfProfileIn( $fname );
3099
3100 $a = split( 'ISBN ', ' '.$text );
3101 if ( count ( $a ) < 2 ) {
3102 wfProfileOut( $fname );
3103 return $text;
3104 }
3105 $text = substr( array_shift( $a ), 1);
3106 $valid = '0123456789-Xx';
3107
3108 foreach ( $a as $x ) {
3109 $isbn = $blank = '' ;
3110 while ( ' ' == $x{0} ) {
3111 $blank .= ' ';
3112 $x = substr( $x, 1 );
3113 }
3114 if ( $x == '' ) { # blank isbn
3115 $text .= "ISBN $blank";
3116 continue;
3117 }
3118 while ( strstr( $valid, $x{0} ) != false ) {
3119 $isbn .= $x{0};
3120 $x = substr( $x, 1 );
3121 }
3122 $num = str_replace( '-', '', $isbn );
3123 $num = str_replace( ' ', '', $num );
3124 $num = str_replace( 'x', 'X', $num );
3125
3126 if ( '' == $num ) {
3127 $text .= "ISBN $blank$x";
3128 } else {
3129 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
3130 $text .= '<a href="' .
3131 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3132 "\" class=\"internal\">ISBN $isbn</a>";
3133 $text .= $x;
3134 }
3135 }
3136 wfProfileOut( $fname );
3137 return $text;
3138 }
3139
3140 /**
3141 * Return an HTML link for the "RFC 1234" text
3142 *
3143 * @access private
3144 * @param string $text Text to be processed
3145 * @param string $keyword Magic keyword to use (default RFC)
3146 * @param string $urlmsg Interface message to use (default rfcurl)
3147 * @return string
3148 */
3149 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3150
3151 $valid = '0123456789';
3152 $internal = false;
3153
3154 $a = split( $keyword, ' '.$text );
3155 if ( count ( $a ) < 2 ) {
3156 return $text;
3157 }
3158 $text = substr( array_shift( $a ), 1);
3159
3160 /* Check if keyword is preceed by [[.
3161 * This test is made here cause of the array_shift above
3162 * that prevent the test to be done in the foreach.
3163 */
3164 if ( substr( $text, -2 ) == '[[' ) {
3165 $internal = true;
3166 }
3167
3168 foreach ( $a as $x ) {
3169 /* token might be empty if we have RFC RFC 1234 */
3170 if ( $x=='' ) {
3171 $text.=$keyword;
3172 continue;
3173 }
3174
3175 $id = $blank = '' ;
3176
3177 /** remove and save whitespaces in $blank */
3178 while ( $x{0} == ' ' ) {
3179 $blank .= ' ';
3180 $x = substr( $x, 1 );
3181 }
3182
3183 /** remove and save the rfc number in $id */
3184 while ( strstr( $valid, $x{0} ) != false ) {
3185 $id .= $x{0};
3186 $x = substr( $x, 1 );
3187 }
3188
3189 if ( $id == '' ) {
3190 /* call back stripped spaces*/
3191 $text .= $keyword.$blank.$x;
3192 } elseif( $internal ) {
3193 /* normal link */
3194 $text .= $keyword.$id.$x;
3195 } else {
3196 /* build the external link*/
3197 $url = wfMsg( $urlmsg, $id);
3198 $sk =& $this->mOptions->getSkin();
3199 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3200 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3201 }
3202
3203 /* Check if the next RFC keyword is preceed by [[ */
3204 $internal = ( substr($x,-2) == '[[' );
3205 }
3206 return $text;
3207 }
3208
3209 /**
3210 * Transform wiki markup when saving a page by doing \r\n -> \n
3211 * conversion, substitting signatures, {{subst:}} templates, etc.
3212 *
3213 * @param string $text the text to transform
3214 * @param Title &$title the Title object for the current article
3215 * @param User &$user the User object describing the current user
3216 * @param ParserOptions $options parsing options
3217 * @param bool $clearState whether to clear the parser state first
3218 * @return string the altered wiki markup
3219 * @access public
3220 */
3221 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3222 $this->mOptions = $options;
3223 $this->mTitle =& $title;
3224 $this->mOutputType = OT_WIKI;
3225
3226 if ( $clearState ) {
3227 $this->clearState();
3228 }
3229
3230 $stripState = false;
3231 $pairs = array(
3232 "\r\n" => "\n",
3233 );
3234 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3235 $text = $this->strip( $text, $stripState, true );
3236 $text = $this->pstPass2( $text, $user );
3237 $text = $this->unstrip( $text, $stripState );
3238 $text = $this->unstripNoWiki( $text, $stripState );
3239 return $text;
3240 }
3241
3242 /**
3243 * Pre-save transform helper function
3244 * @access private
3245 */
3246 function pstPass2( $text, &$user ) {
3247 global $wgContLang, $wgLocaltimezone;
3248
3249 /* Note: This is the timestamp saved as hardcoded wikitext to
3250 * the database, we use $wgContLang here in order to give
3251 * everyone the same signiture and use the default one rather
3252 * than the one selected in each users preferences.
3253 */
3254 if ( isset( $wgLocaltimezone ) ) {
3255 $oldtz = getenv( 'TZ' );
3256 putenv( 'TZ='.$wgLocaltimezone );
3257 }
3258 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3259 ' (' . date( 'T' ) . ')';
3260 if ( isset( $wgLocaltimezone ) ) {
3261 putenv( 'TZ='.$oldtz );
3262 }
3263
3264 # Variable replacement
3265 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3266 $text = $this->replaceVariables( $text );
3267
3268 # Signatures
3269 $sigText = $this->getUserSig( $user );
3270 $text = strtr( $text, array(
3271 '~~~~~' => $d,
3272 '~~~~' => "$sigText $d",
3273 '~~~' => $sigText
3274 ) );
3275
3276 # Context links: [[|name]] and [[name (context)|]]
3277 #
3278 global $wgLegalTitleChars;
3279 $tc = "[$wgLegalTitleChars]";
3280 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3281
3282 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3283 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3284
3285 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3286 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3287 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3288 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3289 $context = '';
3290 $t = $this->mTitle->getText();
3291 if ( preg_match( $conpat, $t, $m ) ) {
3292 $context = $m[2];
3293 }
3294 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3295 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3296 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3297
3298 if ( '' == $context ) {
3299 $text = preg_replace( $p2, '[[\\1]]', $text );
3300 } else {
3301 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3302 }
3303
3304 # Trim trailing whitespace
3305 # MAG_END (__END__) tag allows for trailing
3306 # whitespace to be deliberately included
3307 $text = rtrim( $text );
3308 $mw =& MagicWord::get( MAG_END );
3309 $mw->matchAndRemove( $text );
3310
3311 return $text;
3312 }
3313
3314 /**
3315 * Fetch the user's signature text, if any, and normalize to
3316 * validated, ready-to-insert wikitext.
3317 *
3318 * @param User $user
3319 * @return string
3320 * @access private
3321 */
3322 function getUserSig( &$user ) {
3323 global $wgContLang;
3324
3325 $username = $user->getName();
3326 $nickname = $user->getOption( 'nickname' );
3327 $nickname = $nickname === '' ? $username : $nickname;
3328
3329 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3330 # Sig. might contain markup; validate this
3331 if( $this->validateSig( $nickname ) !== false ) {
3332 # Validated; clean up (if needed) and return it
3333 return( $this->cleanSig( $nickname ) );
3334 } else {
3335 # Failed to validate; fall back to the default
3336 $nickname = $username;
3337 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3338 }
3339 }
3340
3341 # If we're still here, make it a link to the user page
3342 $userpage = $user->getUserPage();
3343 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3344 }
3345
3346 /**
3347 * Check that the user's signature contains no bad XML
3348 *
3349 * @param string $text
3350 * @return mixed An expanded string, or false if invalid.
3351 */
3352 function validateSig( $text ) {
3353 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3354 }
3355
3356 /**
3357 * Clean up signature text
3358 *
3359 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3360 * 2) Substitute all transclusions
3361 *
3362 * @param string $text
3363 * @return string Signature text
3364 */
3365 function cleanSig( $text ) {
3366 $substWord = MagicWord::get( MAG_SUBST );
3367 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3368 $substText = '{{' . $substWord->getSynonym( 0 );
3369
3370 $text = preg_replace( $substRegex, $substText, $text );
3371 $text = preg_replace( '/~{3,5}/', '', $text );
3372 $text = $this->replaceVariables( $text );
3373
3374 return $text;
3375 }
3376
3377 /**
3378 * Set up some variables which are usually set up in parse()
3379 * so that an external function can call some class members with confidence
3380 * @access public
3381 */
3382 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3383 $this->mTitle =& $title;
3384 $this->mOptions = $options;
3385 $this->mOutputType = $outputType;
3386 if ( $clearState ) {
3387 $this->clearState();
3388 }
3389 }
3390
3391 /**
3392 * Transform a MediaWiki message by replacing magic variables.
3393 *
3394 * @param string $text the text to transform
3395 * @param ParserOptions $options options
3396 * @return string the text with variables substituted
3397 * @access public
3398 */
3399 function transformMsg( $text, $options ) {
3400 global $wgTitle;
3401 static $executing = false;
3402
3403 $fname = "Parser::transformMsg";
3404
3405 # Guard against infinite recursion
3406 if ( $executing ) {
3407 return $text;
3408 }
3409 $executing = true;
3410
3411 wfProfileIn($fname);
3412
3413 $this->mTitle = $wgTitle;
3414 $this->mOptions = $options;
3415 $this->mOutputType = OT_MSG;
3416 $this->clearState();
3417 $text = $this->replaceVariables( $text );
3418
3419 $executing = false;
3420 wfProfileOut($fname);
3421 return $text;
3422 }
3423
3424 /**
3425 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3426 * Callback will be called with the text within
3427 * Transform and return the text within
3428 *
3429 * @access public
3430 *
3431 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3432 * @param mixed $callback The callback function (and object) to use for the tag
3433 *
3434 * @return The old value of the mTagHooks array associated with the hook
3435 */
3436 function setHook( $tag, $callback ) {
3437 $oldVal = @$this->mTagHooks[$tag];
3438 $this->mTagHooks[$tag] = $callback;
3439
3440 return $oldVal;
3441 }
3442
3443 /**
3444 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3445 * Placeholders created in Skin::makeLinkObj()
3446 * Returns an array of links found, indexed by PDBK:
3447 * 0 - broken
3448 * 1 - normal link
3449 * 2 - stub
3450 * $options is a bit field, RLH_FOR_UPDATE to select for update
3451 */
3452 function replaceLinkHolders( &$text, $options = 0 ) {
3453 global $wgUser;
3454 global $wgOutputReplace;
3455
3456 $fname = 'Parser::replaceLinkHolders';
3457 wfProfileIn( $fname );
3458
3459 $pdbks = array();
3460 $colours = array();
3461 $sk =& $this->mOptions->getSkin();
3462 $linkCache =& LinkCache::singleton();
3463
3464 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3465 wfProfileIn( $fname.'-check' );
3466 $dbr =& wfGetDB( DB_SLAVE );
3467 $page = $dbr->tableName( 'page' );
3468 $threshold = $wgUser->getOption('stubthreshold');
3469
3470 # Sort by namespace
3471 asort( $this->mLinkHolders['namespaces'] );
3472
3473 # Generate query
3474 $query = false;
3475 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3476 # Make title object
3477 $title = $this->mLinkHolders['titles'][$key];
3478
3479 # Skip invalid entries.
3480 # Result will be ugly, but prevents crash.
3481 if ( is_null( $title ) ) {
3482 continue;
3483 }
3484 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3485
3486 # Check if it's a static known link, e.g. interwiki
3487 if ( $title->isAlwaysKnown() ) {
3488 $colours[$pdbk] = 1;
3489 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3490 $colours[$pdbk] = 1;
3491 $this->mOutput->addLink( $title, $id );
3492 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3493 $colours[$pdbk] = 0;
3494 } else {
3495 # Not in the link cache, add it to the query
3496 if ( !isset( $current ) ) {
3497 $current = $ns;
3498 $query = "SELECT page_id, page_namespace, page_title";
3499 if ( $threshold > 0 ) {
3500 $query .= ', page_len, page_is_redirect';
3501 }
3502 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3503 } elseif ( $current != $ns ) {
3504 $current = $ns;
3505 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3506 } else {
3507 $query .= ', ';
3508 }
3509
3510 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3511 }
3512 }
3513 if ( $query ) {
3514 $query .= '))';
3515 if ( $options & RLH_FOR_UPDATE ) {
3516 $query .= ' FOR UPDATE';
3517 }
3518
3519 $res = $dbr->query( $query, $fname );
3520
3521 # Fetch data and form into an associative array
3522 # non-existent = broken
3523 # 1 = known
3524 # 2 = stub
3525 while ( $s = $dbr->fetchObject($res) ) {
3526 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3527 $pdbk = $title->getPrefixedDBkey();
3528 $linkCache->addGoodLinkObj( $s->page_id, $title );
3529 $this->mOutput->addLink( $title, $s->page_id );
3530
3531 if ( $threshold > 0 ) {
3532 $size = $s->page_len;
3533 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3534 $colours[$pdbk] = 1;
3535 } else {
3536 $colours[$pdbk] = 2;
3537 }
3538 } else {
3539 $colours[$pdbk] = 1;
3540 }
3541 }
3542 }
3543 wfProfileOut( $fname.'-check' );
3544
3545 # Construct search and replace arrays
3546 wfProfileIn( $fname.'-construct' );
3547 $wgOutputReplace = array();
3548 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3549 $pdbk = $pdbks[$key];
3550 $searchkey = "<!--LINK $key-->";
3551 $title = $this->mLinkHolders['titles'][$key];
3552 if ( empty( $colours[$pdbk] ) ) {
3553 $linkCache->addBadLinkObj( $title );
3554 $colours[$pdbk] = 0;
3555 $this->mOutput->addLink( $title, 0 );
3556 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3557 $this->mLinkHolders['texts'][$key],
3558 $this->mLinkHolders['queries'][$key] );
3559 } elseif ( $colours[$pdbk] == 1 ) {
3560 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3561 $this->mLinkHolders['texts'][$key],
3562 $this->mLinkHolders['queries'][$key] );
3563 } elseif ( $colours[$pdbk] == 2 ) {
3564 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3565 $this->mLinkHolders['texts'][$key],
3566 $this->mLinkHolders['queries'][$key] );
3567 }
3568 }
3569 wfProfileOut( $fname.'-construct' );
3570
3571 # Do the thing
3572 wfProfileIn( $fname.'-replace' );
3573
3574 $text = preg_replace_callback(
3575 '/(<!--LINK .*?-->)/',
3576 "wfOutputReplaceMatches",
3577 $text);
3578
3579 wfProfileOut( $fname.'-replace' );
3580 }
3581
3582 # Now process interwiki link holders
3583 # This is quite a bit simpler than internal links
3584 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3585 wfProfileIn( $fname.'-interwiki' );
3586 # Make interwiki link HTML
3587 $wgOutputReplace = array();
3588 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3589 $title = $this->mInterwikiLinkHolders['titles'][$key];
3590 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3591 }
3592
3593 $text = preg_replace_callback(
3594 '/<!--IWLINK (.*?)-->/',
3595 "wfOutputReplaceMatches",
3596 $text );
3597 wfProfileOut( $fname.'-interwiki' );
3598 }
3599
3600 wfProfileOut( $fname );
3601 return $colours;
3602 }
3603
3604 /**
3605 * Replace <!--LINK--> link placeholders with plain text of links
3606 * (not HTML-formatted).
3607 * @param string $text
3608 * @return string
3609 */
3610 function replaceLinkHoldersText( $text ) {
3611 global $wgUser;
3612 global $wgOutputReplace;
3613
3614 $fname = 'Parser::replaceLinkHoldersText';
3615 wfProfileIn( $fname );
3616
3617 $text = preg_replace_callback(
3618 '/<!--(LINK|IWLINK) (.*?)-->/',
3619 array( &$this, 'replaceLinkHoldersTextCallback' ),
3620 $text );
3621
3622 wfProfileOut( $fname );
3623 return $text;
3624 }
3625
3626 /**
3627 * @param array $matches
3628 * @return string
3629 * @access private
3630 */
3631 function replaceLinkHoldersTextCallback( $matches ) {
3632 $type = $matches[1];
3633 $key = $matches[2];
3634 if( $type == 'LINK' ) {
3635 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3636 return $this->mLinkHolders['texts'][$key];
3637 }
3638 } elseif( $type == 'IWLINK' ) {
3639 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3640 return $this->mInterwikiLinkHolders['texts'][$key];
3641 }
3642 }
3643 return $matches[0];
3644 }
3645
3646 /**
3647 * Renders an image gallery from a text with one line per image.
3648 * text labels may be given by using |-style alternative text. E.g.
3649 * Image:one.jpg|The number "1"
3650 * Image:tree.jpg|A tree
3651 * given as text will return the HTML of a gallery with two images,
3652 * labeled 'The number "1"' and
3653 * 'A tree'.
3654 */
3655 function renderImageGallery( $text ) {
3656 # Setup the parser
3657 $parserOptions = new ParserOptions;
3658 $localParser = new Parser();
3659
3660 $ig = new ImageGallery();
3661 $ig->setShowBytes( false );
3662 $ig->setShowFilename( false );
3663 $lines = explode( "\n", $text );
3664
3665 foreach ( $lines as $line ) {
3666 # match lines like these:
3667 # Image:someimage.jpg|This is some image
3668 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3669 # Skip empty lines
3670 if ( count( $matches ) == 0 ) {
3671 continue;
3672 }
3673 $nt =& Title::newFromText( $matches[1] );
3674 if( is_null( $nt ) ) {
3675 # Bogus title. Ignore these so we don't bomb out later.
3676 continue;
3677 }
3678 if ( isset( $matches[3] ) ) {
3679 $label = $matches[3];
3680 } else {
3681 $label = '';
3682 }
3683
3684 $pout = $localParser->parse( $label , $this->mTitle, $parserOptions );
3685 $html = $pout->getText();
3686
3687 $ig->add( new Image( $nt ), $html );
3688 $this->mOutput->addImage( $nt->getDBkey() );
3689 }
3690 return $ig->toHTML();
3691 }
3692
3693 /**
3694 * Parse image options text and use it to make an image
3695 */
3696 function makeImage( &$nt, $options ) {
3697 global $wgContLang, $wgUseImageResize, $wgUser;
3698
3699 $align = '';
3700
3701 # Check if the options text is of the form "options|alt text"
3702 # Options are:
3703 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3704 # * left no resizing, just left align. label is used for alt= only
3705 # * right same, but right aligned
3706 # * none same, but not aligned
3707 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3708 # * center center the image
3709 # * framed Keep original image size, no magnify-button.
3710
3711 $part = explode( '|', $options);
3712
3713 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3714 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
3715 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3716 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3717 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3718 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3719 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3720 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3721 $caption = '';
3722
3723 $width = $height = $framed = $thumb = false;
3724 $manual_thumb = '' ;
3725
3726 foreach( $part as $key => $val ) {
3727 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3728 $thumb=true;
3729 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3730 # use manually specified thumbnail
3731 $thumb=true;
3732 $manual_thumb = $match;
3733 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3734 # remember to set an alignment, don't render immediately
3735 $align = 'right';
3736 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3737 # remember to set an alignment, don't render immediately
3738 $align = 'left';
3739 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3740 # remember to set an alignment, don't render immediately
3741 $align = 'center';
3742 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3743 # remember to set an alignment, don't render immediately
3744 $align = 'none';
3745 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3746 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3747 # $match is the image width in pixels
3748 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3749 $width = intval( $m[1] );
3750 $height = intval( $m[2] );
3751 } else {
3752 $width = intval($match);
3753 }
3754 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3755 $framed=true;
3756 } else {
3757 $caption = $val;
3758 }
3759 }
3760 # Strip bad stuff out of the alt text
3761 $alt = $this->replaceLinkHoldersText( $caption );
3762 $alt = Sanitizer::stripAllTags( $alt );
3763
3764 # Linker does the rest
3765 $sk =& $this->mOptions->getSkin();
3766 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3767 }
3768
3769 /**
3770 * Set a flag in the output object indicating that the content is dynamic and
3771 * shouldn't be cached.
3772 */
3773 function disableCache() {
3774 $this->mOutput->mCacheTime = -1;
3775 }
3776
3777 /**#@+
3778 * Callback from the Sanitizer for expanding items found in HTML attribute
3779 * values, so they can be safely tested and escaped.
3780 * @param string $text
3781 * @param array $args
3782 * @return string
3783 * @access private
3784 */
3785 function attributeStripCallback( &$text, $args ) {
3786 $text = $this->replaceVariables( $text, $args );
3787 $text = $this->unstripForHTML( $text );
3788 return $text;
3789 }
3790
3791 function unstripForHTML( $text ) {
3792 $text = $this->unstrip( $text, $this->mStripState );
3793 $text = $this->unstripNoWiki( $text, $this->mStripState );
3794 return $text;
3795 }
3796 /**#@-*/
3797
3798 /**#@+
3799 * Accessor/mutator
3800 */
3801 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
3802 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
3803 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
3804 /**#@-*/
3805
3806 /**#@+
3807 * Accessor
3808 */
3809 function getTags() { return array_keys( $this->mTagHooks ); }
3810 /**#@-*/
3811 }
3812
3813 /**
3814 * @todo document
3815 * @package MediaWiki
3816 */
3817 class ParserOutput
3818 {
3819 var $mText, # The output text
3820 $mLanguageLinks, # List of the full text of language links, in the order they appear
3821 $mCategories, # Map of category names to sort keys
3822 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3823 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3824 $mVersion, # Compatibility check
3825 $mTitleText, # title text of the chosen language variant
3826 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3827 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3828 $mImages, # DB keys of the images used, in the array key only
3829 $mExternalLinks; # External link URLs, in the key only
3830
3831 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3832 $containsOldMagic = false, $titletext = '' )
3833 {
3834 $this->mText = $text;
3835 $this->mLanguageLinks = $languageLinks;
3836 $this->mCategories = $categoryLinks;
3837 $this->mContainsOldMagic = $containsOldMagic;
3838 $this->mCacheTime = '';
3839 $this->mVersion = MW_PARSER_VERSION;
3840 $this->mTitleText = $titletext;
3841 $this->mLinks = array();
3842 $this->mTemplates = array();
3843 $this->mImages = array();
3844 $this->mExternalLinks = array();
3845 }
3846
3847 function getText() { return $this->mText; }
3848 function getLanguageLinks() { return $this->mLanguageLinks; }
3849 function getCategoryLinks() { return array_keys( $this->mCategories ); }
3850 function &getCategories() { return $this->mCategories; }
3851 function getCacheTime() { return $this->mCacheTime; }
3852 function getTitleText() { return $this->mTitleText; }
3853 function &getLinks() { return $this->mLinks; }
3854 function &getTemplates() { return $this->mTemplates; }
3855 function &getImages() { return $this->mImages; }
3856 function &getExternalLinks() { return $this->mExternalLinks; }
3857
3858 function containsOldMagic() { return $this->mContainsOldMagic; }
3859 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3860 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3861 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
3862 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3863 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3864 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3865
3866 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
3867 function addImage( $name ) { $this->mImages[$name] = 1; }
3868 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
3869 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
3870
3871 function addLink( $title, $id ) {
3872 $ns = $title->getNamespace();
3873 $dbk = $title->getDBkey();
3874 if ( !isset( $this->mLinks[$ns] ) ) {
3875 $this->mLinks[$ns] = array();
3876 }
3877 $this->mLinks[$ns][$dbk] = $id;
3878 }
3879
3880 function addTemplate( $title, $id ) {
3881 $ns = $title->getNamespace();
3882 $dbk = $title->getDBkey();
3883 if ( !isset( $this->mTemplates[$ns] ) ) {
3884 $this->mTemplates[$ns] = array();
3885 }
3886 $this->mTemplates[$ns][$dbk] = $id;
3887 }
3888
3889 /**
3890 * @deprecated
3891 */
3892 /*
3893 function merge( $other ) {
3894 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3895 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3896 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3897 }*/
3898
3899 /**
3900 * Return true if this cached output object predates the global or
3901 * per-article cache invalidation timestamps, or if it comes from
3902 * an incompatible older version.
3903 *
3904 * @param string $touched the affected article's last touched timestamp
3905 * @return bool
3906 * @access public
3907 */
3908 function expired( $touched ) {
3909 global $wgCacheEpoch;
3910 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3911 $this->getCacheTime() < $touched ||
3912 $this->getCacheTime() <= $wgCacheEpoch ||
3913 !isset( $this->mVersion ) ||
3914 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3915 }
3916 }
3917
3918 /**
3919 * Set options of the Parser
3920 * @todo document
3921 * @package MediaWiki
3922 */
3923 class ParserOptions
3924 {
3925 # All variables are private
3926 var $mUseTeX; # Use texvc to expand <math> tags
3927 var $mUseDynamicDates; # Use DateFormatter to format dates
3928 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3929 var $mAllowExternalImages; # Allow external images inline
3930 var $mAllowExternalImagesFrom; # If not, any exception?
3931 var $mSkin; # Reference to the preferred skin
3932 var $mDateFormat; # Date format index
3933 var $mEditSection; # Create "edit section" links
3934 var $mNumberHeadings; # Automatically number headings
3935 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3936 var $mTidy; # Ask for tidy cleanup
3937
3938 function getUseTeX() { return $this->mUseTeX; }
3939 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3940 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3941 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3942 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
3943 function &getSkin() { return $this->mSkin; }
3944 function getDateFormat() { return $this->mDateFormat; }
3945 function getEditSection() { return $this->mEditSection; }
3946 function getNumberHeadings() { return $this->mNumberHeadings; }
3947 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3948 function getTidy() { return $this->mTidy; }
3949
3950 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3951 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3952 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3953 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3954 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
3955 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3956 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3957 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3958 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3959 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
3960 function setSkin( &$x ) { $this->mSkin =& $x; }
3961
3962 function ParserOptions() {
3963 global $wgUser;
3964 $this->initialiseFromUser( $wgUser );
3965 }
3966
3967 /**
3968 * Get parser options
3969 * @static
3970 */
3971 function newFromUser( &$user ) {
3972 $popts = new ParserOptions;
3973 $popts->initialiseFromUser( $user );
3974 return $popts;
3975 }
3976
3977 /** Get user options */
3978 function initialiseFromUser( &$userInput ) {
3979 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3980 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3981 $fname = 'ParserOptions::initialiseFromUser';
3982 wfProfileIn( $fname );
3983 if ( !$userInput ) {
3984 $user = new User;
3985 $user->setLoaded( true );
3986 } else {
3987 $user =& $userInput;
3988 }
3989
3990 $this->mUseTeX = $wgUseTeX;
3991 $this->mUseDynamicDates = $wgUseDynamicDates;
3992 $this->mInterwikiMagic = $wgInterwikiMagic;
3993 $this->mAllowExternalImages = $wgAllowExternalImages;
3994 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
3995 wfProfileIn( $fname.'-skin' );
3996 $this->mSkin =& $user->getSkin();
3997 wfProfileOut( $fname.'-skin' );
3998 $this->mDateFormat = $user->getOption( 'date' );
3999 $this->mEditSection = true;
4000 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4001 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4002 $this->mTidy = false;
4003 wfProfileOut( $fname );
4004 }
4005 }
4006
4007 /**
4008 * Callback function used by Parser::replaceLinkHolders()
4009 * to substitute link placeholders.
4010 */
4011 function &wfOutputReplaceMatches( $matches ) {
4012 global $wgOutputReplace;
4013 return $wgOutputReplace[$matches[1]];
4014 }
4015
4016 /**
4017 * Return the total number of articles
4018 */
4019 function wfNumberOfArticles() {
4020 global $wgNumberOfArticles;
4021
4022 wfLoadSiteStats();
4023 return $wgNumberOfArticles;
4024 }
4025
4026 /**
4027 * Return the number of files
4028 */
4029 function wfNumberOfFiles() {
4030 $fname = 'Parser::wfNumberOfFiles';
4031
4032 wfProfileIn( $fname );
4033 $dbr =& wfGetDB( DB_SLAVE );
4034 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4035 wfProfileOut( $fname );
4036
4037 return $res;
4038 }
4039
4040 /**
4041 * Get various statistics from the database
4042 * @access private
4043 */
4044 function wfLoadSiteStats() {
4045 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4046 $fname = 'wfLoadSiteStats';
4047
4048 if ( -1 != $wgNumberOfArticles ) return;
4049 $dbr =& wfGetDB( DB_SLAVE );
4050 $s = $dbr->selectRow( 'site_stats',
4051 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4052 array( 'ss_row_id' => 1 ), $fname
4053 );
4054
4055 if ( $s === false ) {
4056 return;
4057 } else {
4058 $wgTotalViews = $s->ss_total_views;
4059 $wgTotalEdits = $s->ss_total_edits;
4060 $wgNumberOfArticles = $s->ss_good_articles;
4061 }
4062 }
4063
4064 /**
4065 * Escape html tags
4066 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4067 *
4068 * @param string $in Text that might contain HTML tags
4069 * @return string Escaped string
4070 */
4071 function wfEscapeHTMLTagsOnly( $in ) {
4072 return str_replace(
4073 array( '"', '>', '<' ),
4074 array( '&quot;', '&gt;', '&lt;' ),
4075 $in );
4076 }
4077
4078 ?>