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