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