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