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