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