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