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