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