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