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