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