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