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