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