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