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