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