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