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