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