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