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