Broke some TOC interaction with <ref> in 14350; fixed.
[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 $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() ? $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_CURRENTVERSION:
2170 global $wgVersion;
2171 return $wgVersion;
2172 case MAG_SITENAME:
2173 return $wgSitename;
2174 case MAG_SERVER:
2175 return $wgServer;
2176 case MAG_SERVERNAME:
2177 return $wgServerName;
2178 case MAG_SCRIPTPATH:
2179 return $wgScriptPath;
2180 default:
2181 $ret = null;
2182 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2183 return $ret;
2184 else
2185 return null;
2186 }
2187 }
2188
2189 /**
2190 * initialise the magic variables (like CURRENTMONTHNAME)
2191 *
2192 * @private
2193 */
2194 function initialiseVariables() {
2195 $fname = 'Parser::initialiseVariables';
2196 wfProfileIn( $fname );
2197 global $wgVariableIDs;
2198 $this->mVariables = array();
2199 foreach ( $wgVariableIDs as $id ) {
2200 $mw =& MagicWord::get( $id );
2201 $mw->addToArray( $this->mVariables, $id );
2202 }
2203 wfProfileOut( $fname );
2204 }
2205
2206 /**
2207 * parse any parentheses in format ((title|part|part))
2208 * and call callbacks to get a replacement text for any found piece
2209 *
2210 * @param string $text The text to parse
2211 * @param array $callbacks rules in form:
2212 * '{' => array( # opening parentheses
2213 * 'end' => '}', # closing parentheses
2214 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2215 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2216 * )
2217 * )
2218 * @private
2219 */
2220 function replace_callback ($text, $callbacks) {
2221 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2222 $lastOpeningBrace = -1; # last not closed parentheses
2223
2224 for ($i = 0; $i < strlen($text); $i++) {
2225 # check for any opening brace
2226 $rule = null;
2227 $nextPos = -1;
2228 foreach ($callbacks as $key => $value) {
2229 $pos = strpos ($text, $key, $i);
2230 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
2231 $rule = $value;
2232 $nextPos = $pos;
2233 }
2234 }
2235
2236 if ($lastOpeningBrace >= 0) {
2237 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2238
2239 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2240 $rule = null;
2241 $nextPos = $pos;
2242 }
2243
2244 $pos = strpos ($text, '|', $i);
2245
2246 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2247 $rule = null;
2248 $nextPos = $pos;
2249 }
2250 }
2251
2252 if ($nextPos == -1)
2253 break;
2254
2255 $i = $nextPos;
2256
2257 # found openning brace, lets add it to parentheses stack
2258 if (null != $rule) {
2259 $piece = array('brace' => $text[$i],
2260 'braceEnd' => $rule['end'],
2261 'count' => 1,
2262 'title' => '',
2263 'parts' => null);
2264
2265 # count openning brace characters
2266 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2267 $piece['count']++;
2268 $i++;
2269 }
2270
2271 $piece['startAt'] = $i+1;
2272 $piece['partStart'] = $i+1;
2273
2274 # we need to add to stack only if openning brace count is enough for any given rule
2275 foreach ($rule['cb'] as $cnt => $fn) {
2276 if ($piece['count'] >= $cnt) {
2277 $lastOpeningBrace ++;
2278 $openingBraceStack[$lastOpeningBrace] = $piece;
2279 break;
2280 }
2281 }
2282
2283 continue;
2284 }
2285 else if ($lastOpeningBrace >= 0) {
2286 # first check if it is a closing brace
2287 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2288 # lets check if it is enough characters for closing brace
2289 $count = 1;
2290 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2291 $count++;
2292
2293 # if there are more closing parentheses than opening ones, we parse less
2294 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2295 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2296
2297 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2298 $matchingCount = 0;
2299 $matchingCallback = null;
2300 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2301 if ($count >= $cnt && $matchingCount < $cnt) {
2302 $matchingCount = $cnt;
2303 $matchingCallback = $fn;
2304 }
2305 }
2306
2307 if ($matchingCount == 0) {
2308 $i += $count - 1;
2309 continue;
2310 }
2311
2312 # lets set a title or last part (if '|' was found)
2313 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2314 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2315 else
2316 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2317
2318 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2319 $pieceEnd = $i + $matchingCount;
2320
2321 if( is_callable( $matchingCallback ) ) {
2322 $cbArgs = array (
2323 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2324 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2325 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2326 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2327 );
2328 # finally we can call a user callback and replace piece of text
2329 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2330 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2331 $i = $pieceStart + strlen($replaceWith) - 1;
2332 }
2333 else {
2334 # null value for callback means that parentheses should be parsed, but not replaced
2335 $i += $matchingCount - 1;
2336 }
2337
2338 # reset last openning parentheses, but keep it in case there are unused characters
2339 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2340 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2341 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2342 'title' => '',
2343 'parts' => null,
2344 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2345 $openingBraceStack[$lastOpeningBrace--] = null;
2346
2347 if ($matchingCount < $piece['count']) {
2348 $piece['count'] -= $matchingCount;
2349 $piece['startAt'] -= $matchingCount;
2350 $piece['partStart'] = $piece['startAt'];
2351 # do we still qualify for any callback with remaining count?
2352 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2353 if ($piece['count'] >= $cnt) {
2354 $lastOpeningBrace ++;
2355 $openingBraceStack[$lastOpeningBrace] = $piece;
2356 break;
2357 }
2358 }
2359 }
2360 continue;
2361 }
2362
2363 # lets set a title if it is a first separator, or next part otherwise
2364 if ($text[$i] == '|') {
2365 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2366 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2367 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2368 }
2369 else
2370 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2371
2372 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2373 }
2374 }
2375 }
2376
2377 return $text;
2378 }
2379
2380 /**
2381 * Replace magic variables, templates, and template arguments
2382 * with the appropriate text. Templates are substituted recursively,
2383 * taking care to avoid infinite loops.
2384 *
2385 * Note that the substitution depends on value of $mOutputType:
2386 * OT_WIKI: only {{subst:}} templates
2387 * OT_MSG: only magic variables
2388 * OT_HTML: all templates and magic variables
2389 *
2390 * @param string $tex The text to transform
2391 * @param array $args Key-value pairs representing template parameters to substitute
2392 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2393 * @private
2394 */
2395 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2396 # Prevent too big inclusions
2397 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2398 return $text;
2399 }
2400
2401 $fname = 'Parser::replaceVariables';
2402 wfProfileIn( $fname );
2403
2404 # This function is called recursively. To keep track of arguments we need a stack:
2405 array_push( $this->mArgStack, $args );
2406
2407 $braceCallbacks = array();
2408 if ( !$argsOnly ) {
2409 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2410 }
2411 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2412 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2413 }
2414 $callbacks = array();
2415 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2416 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2417 $text = $this->replace_callback ($text, $callbacks);
2418
2419 array_pop( $this->mArgStack );
2420
2421 wfProfileOut( $fname );
2422 return $text;
2423 }
2424
2425 /**
2426 * Replace magic variables
2427 * @private
2428 */
2429 function variableSubstitution( $matches ) {
2430 $fname = 'Parser::variableSubstitution';
2431 $varname = $matches[1];
2432 wfProfileIn( $fname );
2433 if ( !$this->mVariables ) {
2434 $this->initialiseVariables();
2435 }
2436 $skip = false;
2437 if ( $this->mOutputType == OT_WIKI ) {
2438 # Do only magic variables prefixed by SUBST
2439 $mwSubst =& MagicWord::get( MAG_SUBST );
2440 if (!$mwSubst->matchStartAndRemove( $varname ))
2441 $skip = true;
2442 # Note that if we don't substitute the variable below,
2443 # we don't remove the {{subst:}} magic word, in case
2444 # it is a template rather than a magic variable.
2445 }
2446 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2447 $id = $this->mVariables[$varname];
2448 $text = $this->getVariableValue( $id );
2449 $this->mOutput->mContainsOldMagic = true;
2450 } else {
2451 $text = $matches[0];
2452 }
2453 wfProfileOut( $fname );
2454 return $text;
2455 }
2456
2457 # Split template arguments
2458 function getTemplateArgs( $argsString ) {
2459 if ( $argsString === '' ) {
2460 return array();
2461 }
2462
2463 $args = explode( '|', substr( $argsString, 1 ) );
2464
2465 # If any of the arguments contains a '[[' but no ']]', it needs to be
2466 # merged with the next arg because the '|' character between belongs
2467 # to the link syntax and not the template parameter syntax.
2468 $argc = count($args);
2469
2470 for ( $i = 0; $i < $argc-1; $i++ ) {
2471 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2472 $args[$i] .= '|'.$args[$i+1];
2473 array_splice($args, $i+1, 1);
2474 $i--;
2475 $argc--;
2476 }
2477 }
2478
2479 return $args;
2480 }
2481
2482 /**
2483 * Return the text of a template, after recursively
2484 * replacing any variables or templates within the template.
2485 *
2486 * @param array $piece The parts of the template
2487 * $piece['text']: matched text
2488 * $piece['title']: the title, i.e. the part before the |
2489 * $piece['parts']: the parameter array
2490 * @return string the text of the template
2491 * @private
2492 */
2493 function braceSubstitution( $piece ) {
2494 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2495 $fname = 'Parser::braceSubstitution';
2496 wfProfileIn( $fname );
2497
2498 # Flags
2499 $found = false; # $text has been filled
2500 $nowiki = false; # wiki markup in $text should be escaped
2501 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2502 $noargs = false; # Don't replace triple-brace arguments in $text
2503 $replaceHeadings = false; # Make the edit section links go to the template not the article
2504 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2505 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2506
2507 # Title object, where $text came from
2508 $title = NULL;
2509
2510 $linestart = '';
2511
2512 # $part1 is the bit before the first |, and must contain only title characters
2513 # $args is a list of arguments, starting from index 0, not including $part1
2514
2515 $part1 = $piece['title'];
2516 # If the third subpattern matched anything, it will start with |
2517
2518 if (null == $piece['parts']) {
2519 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2520 if ($replaceWith != $piece['text']) {
2521 $text = $replaceWith;
2522 $found = true;
2523 $noparse = true;
2524 $noargs = true;
2525 }
2526 }
2527
2528 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2529 $argc = count( $args );
2530
2531 # SUBST
2532 if ( !$found ) {
2533 $mwSubst =& MagicWord::get( MAG_SUBST );
2534 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2535 # One of two possibilities is true:
2536 # 1) Found SUBST but not in the PST phase
2537 # 2) Didn't find SUBST and in the PST phase
2538 # In either case, return without further processing
2539 $text = $piece['text'];
2540 $found = true;
2541 $noparse = true;
2542 $noargs = true;
2543 }
2544 }
2545
2546 # MSG, MSGNW, INT and RAW
2547 if ( !$found ) {
2548 # Check for MSGNW:
2549 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2550 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2551 $nowiki = true;
2552 } else {
2553 # Remove obsolete MSG:
2554 $mwMsg =& MagicWord::get( MAG_MSG );
2555 $mwMsg->matchStartAndRemove( $part1 );
2556 }
2557
2558 # Check for RAW:
2559 $mwRaw =& MagicWord::get( MAG_RAW );
2560 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2561 $forceRawInterwiki = true;
2562 }
2563
2564 # Check if it is an internal message
2565 $mwInt =& MagicWord::get( MAG_INT );
2566 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2567 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2568 $text = $linestart . wfMsgReal( $part1, $args, true );
2569 $found = true;
2570 }
2571 }
2572 }
2573
2574 # NS
2575 if ( !$found ) {
2576 # Check for NS: (namespace expansion)
2577 $mwNs = MagicWord::get( MAG_NS );
2578 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2579 if ( intval( $part1 ) || $part1 == "0" ) {
2580 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2581 $found = true;
2582 } else {
2583 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2584 if ( !is_null( $index ) ) {
2585 $text = $linestart . $wgContLang->getNsText( $index );
2586 $found = true;
2587 }
2588 }
2589 }
2590 }
2591
2592 # URLENCODE
2593 if( !$found ) {
2594 $urlencode =& MagicWord::get( MAG_URLENCODE );
2595 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2596 $text = $linestart . urlencode( $part1 );
2597 $found = true;
2598 }
2599 }
2600
2601 # LCFIRST, UCFIRST, LC and UC
2602 if ( !$found ) {
2603 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2604 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2605 $lc =& MagicWord::get( MAG_LC );
2606 $uc =& MagicWord::get( MAG_UC );
2607 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2608 $text = $linestart . $wgContLang->lcfirst( $part1 );
2609 $found = true;
2610 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2611 $text = $linestart . $wgContLang->ucfirst( $part1 );
2612 $found = true;
2613 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2614 $text = $linestart . $wgContLang->lc( $part1 );
2615 $found = true;
2616 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2617 $text = $linestart . $wgContLang->uc( $part1 );
2618 $found = true;
2619 }
2620 }
2621
2622 # LOCALURL and FULLURL
2623 if ( !$found ) {
2624 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2625 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2626 $mwFull =& MagicWord::get( MAG_FULLURL );
2627 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2628
2629
2630 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2631 $func = 'getLocalURL';
2632 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2633 $func = 'escapeLocalURL';
2634 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2635 $func = 'getFullURL';
2636 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2637 $func = 'escapeFullURL';
2638 } else {
2639 $func = false;
2640 }
2641
2642 if ( $func !== false ) {
2643 $title = Title::newFromText( $part1 );
2644 # Due to order of execution of a lot of bits, the values might be encoded
2645 # before arriving here; if that's true, then the title can't be created
2646 # and the variable will fail. If we can't get a decent title from the first
2647 # attempt, url-decode and try for a second.
2648 if( is_null( $title ) )
2649 $title = Title::newFromUrl( urldecode( $part1 ) );
2650 if ( !is_null( $title ) ) {
2651 if ( $argc > 0 ) {
2652 $text = $linestart . $title->$func( $args[0] );
2653 } else {
2654 $text = $linestart . $title->$func();
2655 }
2656 $found = true;
2657 }
2658 }
2659 }
2660
2661 $lang = $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
2662 # GRAMMAR
2663 if ( !$found && $argc == 1 ) {
2664 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2665 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2666 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2667 $found = true;
2668 }
2669 }
2670
2671 # PLURAL
2672 if ( !$found && $argc >= 2 ) {
2673 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2674 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2675 if ($argc==2) {$args[2]=$args[1];}
2676 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2677 $found = true;
2678 }
2679 }
2680
2681 # DISPLAYTITLE
2682 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2683 $mwDT =& MagicWord::get( MAG_DISPLAYTITLE );
2684 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2685
2686 # Set title in parser output object
2687 $param = $args[0];
2688 $parserOptions = new ParserOptions;
2689 $local_parser = new Parser ();
2690 $t2 = $local_parser->parse ( $param, $this->mTitle, $parserOptions, false );
2691 $this->mOutput->mHTMLtitle = $t2->GetText();
2692
2693 # Add subtitle
2694 $t = $this->mTitle->getPrefixedText();
2695 $this->mOutput->mSubtitle .= wfMsg('displaytitle', $t);
2696 $text = "" ;
2697 $found = true ;
2698 }
2699 }
2700
2701 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2702 if( !$found ) {
2703 $mwWordsToCheck = array( MAG_NUMBEROFPAGES => 'wfNumberOfPages',
2704 MAG_NUMBEROFUSERS => 'wfNumberOfUsers',
2705 MAG_NUMBEROFARTICLES => 'wfNumberOfArticles',
2706 MAG_NUMBEROFFILES => 'wfNumberOfFiles' );
2707 foreach( $mwWordsToCheck as $word => $func ) {
2708 $mwCurrentWord =& MagicWord::get( $word );
2709 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2710 $mwRawSuffix =& MagicWord::get( MAG_RAWSUFFIX );
2711 if( $mwRawSuffix->match( $args[0] ) ) {
2712 # Raw and unformatted
2713 $text = $linestart . call_user_func( $func );
2714 } else {
2715 # Formatted according to the content default
2716 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2717 }
2718 $found = true;
2719 }
2720 }
2721 }
2722
2723 # Extensions
2724 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2725 $colonPos = strpos( $part1, ':' );
2726 if ( $colonPos !== false ) {
2727 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2728 if ( isset( $this->mFunctionHooks[$function] ) ) {
2729 $funcArgs = array_map( 'trim', $args );
2730 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos + 1 ) ) ), $funcArgs );
2731 $result = call_user_func_array( $this->mFunctionHooks[$function], $funcArgs );
2732 $found = true;
2733
2734 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2735 //$noargs = true;
2736 //$noparse = true;
2737
2738 if ( is_array( $result ) ) {
2739 $text = $linestart . $result[0];
2740 unset( $result[0] );
2741
2742 // Extract flags into the local scope
2743 // This allows callers to set flags such as nowiki, noparse, found, etc.
2744 extract( $result );
2745 } else {
2746 $text = $linestart . $result;
2747 }
2748 }
2749 }
2750 }
2751
2752 # Template table test
2753
2754 # Did we encounter this template already? If yes, it is in the cache
2755 # and we need to check for loops.
2756 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
2757 $found = true;
2758
2759 # Infinite loop test
2760 if ( isset( $this->mTemplatePath[$part1] ) ) {
2761 $noparse = true;
2762 $noargs = true;
2763 $found = true;
2764 $text = $linestart .
2765 '{{' . $part1 . '}}' .
2766 '<!-- WARNING: template loop detected -->';
2767 wfDebug( "$fname: template loop broken at '$part1'\n" );
2768 } else {
2769 # set $text to cached message.
2770 $text = $linestart . $this->mTemplates[$piece['title']];
2771 }
2772 }
2773
2774 # Load from database
2775 $lastPathLevel = $this->mTemplatePath;
2776 if ( !$found ) {
2777 $ns = NS_TEMPLATE;
2778 # declaring $subpage directly in the function call
2779 # does not work correctly with references and breaks
2780 # {{/subpage}}-style inclusions
2781 $subpage = '';
2782 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2783 if ($subpage !== '') {
2784 $ns = $this->mTitle->getNamespace();
2785 }
2786 $title = Title::newFromText( $part1, $ns );
2787
2788 if ( !is_null( $title ) ) {
2789 if ( !$title->isExternal() ) {
2790 # Check for excessive inclusion
2791 $dbk = $title->getPrefixedDBkey();
2792 if ( $this->incrementIncludeCount( $dbk ) ) {
2793 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->mOutputType != OT_WIKI ) {
2794 $text = SpecialPage::capturePath( $title );
2795 if ( is_string( $text ) ) {
2796 $found = true;
2797 $noparse = true;
2798 $noargs = true;
2799 $isHTML = true;
2800 $this->disableCache();
2801 }
2802 } else {
2803 $articleContent = $this->fetchTemplate( $title );
2804 if ( $articleContent !== false ) {
2805 $found = true;
2806 $text = $articleContent;
2807 $replaceHeadings = true;
2808 }
2809 }
2810 }
2811
2812 # If the title is valid but undisplayable, make a link to it
2813 if ( $this->mOutputType == OT_HTML && !$found ) {
2814 $text = '[['.$title->getPrefixedText().']]';
2815 $found = true;
2816 }
2817 } elseif ( $title->isTrans() ) {
2818 // Interwiki transclusion
2819 if ( $this->mOutputType == OT_HTML && !$forceRawInterwiki ) {
2820 $text = $this->interwikiTransclude( $title, 'render' );
2821 $isHTML = true;
2822 $noparse = true;
2823 } else {
2824 $text = $this->interwikiTransclude( $title, 'raw' );
2825 $replaceHeadings = true;
2826 }
2827 $found = true;
2828 }
2829
2830 # Template cache array insertion
2831 # Use the original $piece['title'] not the mangled $part1, so that
2832 # modifiers such as RAW: produce separate cache entries
2833 if( $found ) {
2834 $this->mTemplates[$piece['title']] = $text;
2835 $text = $linestart . $text;
2836 }
2837 }
2838 }
2839
2840 # Recursive parsing, escaping and link table handling
2841 # Only for HTML output
2842 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2843 $text = wfEscapeWikiText( $text );
2844 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found ) {
2845 if ( $noargs ) {
2846 $assocArgs = array();
2847 } else {
2848 # Clean up argument array
2849 $assocArgs = array();
2850 $index = 1;
2851 foreach( $args as $arg ) {
2852 $eqpos = strpos( $arg, '=' );
2853 if ( $eqpos === false ) {
2854 $assocArgs[$index++] = $arg;
2855 } else {
2856 $name = trim( substr( $arg, 0, $eqpos ) );
2857 $value = trim( substr( $arg, $eqpos+1 ) );
2858 if ( $value === false ) {
2859 $value = '';
2860 }
2861 if ( $name !== false ) {
2862 $assocArgs[$name] = $value;
2863 }
2864 }
2865 }
2866
2867 # Add a new element to the templace recursion path
2868 $this->mTemplatePath[$part1] = 1;
2869 }
2870
2871 if ( !$noparse ) {
2872 # If there are any <onlyinclude> tags, only include them
2873 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2874 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2875 $text = '';
2876 foreach ($m[1] as $piece)
2877 $text .= $piece;
2878 }
2879 # Remove <noinclude> sections and <includeonly> tags
2880 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2881 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2882
2883 if( $this->mOutputType == OT_HTML ) {
2884 # Strip <nowiki>, <pre>, etc.
2885 $text = $this->strip( $text, $this->mStripState );
2886 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2887 }
2888 $text = $this->replaceVariables( $text, $assocArgs );
2889
2890 # If the template begins with a table or block-level
2891 # element, it should be treated as beginning a new line.
2892 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2893 $text = "\n" . $text;
2894 }
2895 } elseif ( !$noargs ) {
2896 # $noparse and !$noargs
2897 # Just replace the arguments, not any double-brace items
2898 # This is used for rendered interwiki transclusion
2899 $text = $this->replaceVariables( $text, $assocArgs, true );
2900 }
2901 }
2902 # Prune lower levels off the recursion check path
2903 $this->mTemplatePath = $lastPathLevel;
2904
2905 if ( !$found ) {
2906 wfProfileOut( $fname );
2907 return $piece['text'];
2908 } else {
2909 if ( $isHTML ) {
2910 # Replace raw HTML by a placeholder
2911 # Add a blank line preceding, to prevent it from mucking up
2912 # immediately preceding headings
2913 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2914 } else {
2915 # replace ==section headers==
2916 # XXX this needs to go away once we have a better parser.
2917 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2918 if( !is_null( $title ) )
2919 $encodedname = base64_encode($title->getPrefixedDBkey());
2920 else
2921 $encodedname = base64_encode("");
2922 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2923 PREG_SPLIT_DELIM_CAPTURE);
2924 $text = '';
2925 $nsec = 0;
2926 for( $i = 0; $i < count($m); $i += 2 ) {
2927 $text .= $m[$i];
2928 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2929 $hl = $m[$i + 1];
2930 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2931 $text .= $hl;
2932 continue;
2933 }
2934 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2935 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2936 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2937
2938 $nsec++;
2939 }
2940 }
2941 }
2942 }
2943
2944 # Prune lower levels off the recursion check path
2945 $this->mTemplatePath = $lastPathLevel;
2946
2947 if ( !$found ) {
2948 wfProfileOut( $fname );
2949 return $piece['text'];
2950 } else {
2951 wfProfileOut( $fname );
2952 return $text;
2953 }
2954 }
2955
2956 /**
2957 * Fetch the unparsed text of a template and register a reference to it.
2958 */
2959 function fetchTemplate( $title ) {
2960 $text = false;
2961 // Loop to fetch the article, with up to 1 redirect
2962 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
2963 $rev = Revision::newFromTitle( $title );
2964 $this->mOutput->addTemplate( $title, $title->getArticleID() );
2965 if ( !$rev ) {
2966 break;
2967 }
2968 $text = $rev->getText();
2969 if ( $text === false ) {
2970 break;
2971 }
2972 // Redirect?
2973 $title = Title::newFromRedirect( $text );
2974 }
2975 return $text;
2976 }
2977
2978 /**
2979 * Transclude an interwiki link.
2980 */
2981 function interwikiTransclude( $title, $action ) {
2982 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2983
2984 if (!$wgEnableScaryTranscluding)
2985 return wfMsg('scarytranscludedisabled');
2986
2987 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2988 // But we'll handle it generally anyway
2989 if ( $title->getNamespace() ) {
2990 // Use the canonical namespace, which should work anywhere
2991 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2992 } else {
2993 $articleName = $title->getDBkey();
2994 }
2995
2996 $url = str_replace('$1', urlencode($articleName), Title::getInterwikiLink($title->getInterwiki()));
2997 $url .= "?action=$action";
2998 if (strlen($url) > 255)
2999 return wfMsg('scarytranscludetoolong');
3000 return $this->fetchScaryTemplateMaybeFromCache($url);
3001 }
3002
3003 function fetchScaryTemplateMaybeFromCache($url) {
3004 global $wgTranscludeCacheExpiry;
3005 $dbr =& wfGetDB(DB_SLAVE);
3006 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3007 array('tc_url' => $url));
3008 if ($obj) {
3009 $time = $obj->tc_time;
3010 $text = $obj->tc_contents;
3011 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3012 return $text;
3013 }
3014 }
3015
3016 $text = wfGetHTTP($url);
3017 if (!$text)
3018 return wfMsg('scarytranscludefailed', $url);
3019
3020 $dbw =& wfGetDB(DB_MASTER);
3021 $dbw->replace('transcache', array('tc_url'), array(
3022 'tc_url' => $url,
3023 'tc_time' => time(),
3024 'tc_contents' => $text));
3025 return $text;
3026 }
3027
3028
3029 /**
3030 * Triple brace replacement -- used for template arguments
3031 * @private
3032 */
3033 function argSubstitution( $matches ) {
3034 $arg = trim( $matches['title'] );
3035 $text = $matches['text'];
3036 $inputArgs = end( $this->mArgStack );
3037
3038 if ( array_key_exists( $arg, $inputArgs ) ) {
3039 $text = $inputArgs[$arg];
3040 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
3041 $text = $matches['parts'][0];
3042 }
3043
3044 return $text;
3045 }
3046
3047 /**
3048 * Returns true if the function is allowed to include this entity
3049 * @private
3050 */
3051 function incrementIncludeCount( $dbk ) {
3052 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
3053 $this->mIncludeCount[$dbk] = 0;
3054 }
3055 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
3056 return true;
3057 } else {
3058 return false;
3059 }
3060 }
3061
3062 /**
3063 * Detect __TOC__ magic word and set a placeholder
3064 */
3065 function stripToc( $text ) {
3066 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3067 # do not add TOC
3068 $mw = MagicWord::get( MAG_NOTOC );
3069 if( $mw->matchAndRemove( $text ) ) {
3070 $this->mShowToc = false;
3071 }
3072
3073 $mw = MagicWord::get( MAG_TOC );
3074 if( $mw->match( $text ) ) {
3075 $this->mShowToc = true;
3076 $this->mForceTocPosition = true;
3077
3078 // Set a placeholder. At the end we'll fill it in with the TOC.
3079 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3080
3081 // Only keep the first one.
3082 $text = $mw->replace( '', $text );
3083 }
3084 return $text;
3085 }
3086
3087 /**
3088 * This function accomplishes several tasks:
3089 * 1) Auto-number headings if that option is enabled
3090 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3091 * 3) Add a Table of contents on the top for users who have enabled the option
3092 * 4) Auto-anchor headings
3093 *
3094 * It loops through all headlines, collects the necessary data, then splits up the
3095 * string and re-inserts the newly formatted headlines.
3096 *
3097 * @param string $text
3098 * @param boolean $isMain
3099 * @private
3100 */
3101 function formatHeadings( $text, $isMain=true ) {
3102 global $wgMaxTocLevel, $wgContLang;
3103
3104 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3105 if( !$this->mTitle->userCanEdit() ) {
3106 $showEditLink = 0;
3107 } else {
3108 $showEditLink = $this->mOptions->getEditSection();
3109 }
3110
3111 # Inhibit editsection links if requested in the page
3112 $esw =& MagicWord::get( MAG_NOEDITSECTION );
3113 if( $esw->matchAndRemove( $text ) ) {
3114 $showEditLink = 0;
3115 }
3116
3117 # Get all headlines for numbering them and adding funky stuff like [edit]
3118 # links - this is for later, but we need the number of headlines right now
3119 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3120
3121 # if there are fewer than 4 headlines in the article, do not show TOC
3122 # unless it's been explicitly enabled.
3123 $enoughToc = $this->mShowToc &&
3124 (($numMatches >= 4) || $this->mForceTocPosition);
3125
3126 # Allow user to stipulate that a page should have a "new section"
3127 # link added via __NEWSECTIONLINK__
3128 $mw =& MagicWord::get( MAG_NEWSECTIONLINK );
3129 if( $mw->matchAndRemove( $text ) )
3130 $this->mOutput->setNewSection( true );
3131
3132 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3133 # override above conditions and always show TOC above first header
3134 $mw =& MagicWord::get( MAG_FORCETOC );
3135 if ($mw->matchAndRemove( $text ) ) {
3136 $this->mShowToc = true;
3137 $enoughToc = true;
3138 }
3139
3140 # Never ever show TOC if no headers
3141 if( $numMatches < 1 ) {
3142 $enoughToc = false;
3143 }
3144
3145 # We need this to perform operations on the HTML
3146 $sk =& $this->mOptions->getSkin();
3147
3148 # headline counter
3149 $headlineCount = 0;
3150 $sectionCount = 0; # headlineCount excluding template sections
3151
3152 # Ugh .. the TOC should have neat indentation levels which can be
3153 # passed to the skin functions. These are determined here
3154 $toc = '';
3155 $full = '';
3156 $head = array();
3157 $sublevelCount = array();
3158 $levelCount = array();
3159 $toclevel = 0;
3160 $level = 0;
3161 $prevlevel = 0;
3162 $toclevel = 0;
3163 $prevtoclevel = 0;
3164
3165 foreach( $matches[3] as $headline ) {
3166 $istemplate = 0;
3167 $templatetitle = '';
3168 $templatesection = 0;
3169 $numbering = '';
3170
3171 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3172 $istemplate = 1;
3173 $templatetitle = base64_decode($mat[1]);
3174 $templatesection = 1 + (int)base64_decode($mat[2]);
3175 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3176 }
3177
3178 if( $toclevel ) {
3179 $prevlevel = $level;
3180 $prevtoclevel = $toclevel;
3181 }
3182 $level = $matches[1][$headlineCount];
3183
3184 if( $doNumberHeadings || $enoughToc ) {
3185
3186 if ( $level > $prevlevel ) {
3187 # Increase TOC level
3188 $toclevel++;
3189 $sublevelCount[$toclevel] = 0;
3190 if( $toclevel<$wgMaxTocLevel ) {
3191 $toc .= $sk->tocIndent();
3192 }
3193 }
3194 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3195 # Decrease TOC level, find level to jump to
3196
3197 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3198 # Can only go down to level 1
3199 $toclevel = 1;
3200 } else {
3201 for ($i = $toclevel; $i > 0; $i--) {
3202 if ( $levelCount[$i] == $level ) {
3203 # Found last matching level
3204 $toclevel = $i;
3205 break;
3206 }
3207 elseif ( $levelCount[$i] < $level ) {
3208 # Found first matching level below current level
3209 $toclevel = $i + 1;
3210 break;
3211 }
3212 }
3213 }
3214 if( $toclevel<$wgMaxTocLevel ) {
3215 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3216 }
3217 }
3218 else {
3219 # No change in level, end TOC line
3220 if( $toclevel<$wgMaxTocLevel ) {
3221 $toc .= $sk->tocLineEnd();
3222 }
3223 }
3224
3225 $levelCount[$toclevel] = $level;
3226
3227 # count number of headlines for each level
3228 @$sublevelCount[$toclevel]++;
3229 $dot = 0;
3230 for( $i = 1; $i <= $toclevel; $i++ ) {
3231 if( !empty( $sublevelCount[$i] ) ) {
3232 if( $dot ) {
3233 $numbering .= '.';
3234 }
3235 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3236 $dot = 1;
3237 }
3238 }
3239 }
3240
3241 # The canonized header is a version of the header text safe to use for links
3242 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3243 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
3244 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
3245
3246 # Remove link placeholders by the link text.
3247 # <!--LINK number-->
3248 # turns into
3249 # link text with suffix
3250 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3251 "\$this->mLinkHolders['texts'][\$1]",
3252 $canonized_headline );
3253 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3254 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3255 $canonized_headline );
3256
3257 # strip out HTML
3258 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3259 $tocline = trim( $canonized_headline );
3260 # Save headline for section edit hint before it's escaped
3261 $headline_hint = trim( $canonized_headline );
3262 $canonized_headline = Sanitizer::escapeId( $tocline );
3263 $refers[$headlineCount] = $canonized_headline;
3264
3265 # count how many in assoc. array so we can track dupes in anchors
3266 @$refers[$canonized_headline]++;
3267 $refcount[$headlineCount]=$refers[$canonized_headline];
3268
3269 # Don't number the heading if it is the only one (looks silly)
3270 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3271 # the two are different if the line contains a link
3272 $headline=$numbering . ' ' . $headline;
3273 }
3274
3275 # Create the anchor for linking from the TOC to the section
3276 $anchor = $canonized_headline;
3277 if($refcount[$headlineCount] > 1 ) {
3278 $anchor .= '_' . $refcount[$headlineCount];
3279 }
3280 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3281 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3282 }
3283 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3284 if ( empty( $head[$headlineCount] ) ) {
3285 $head[$headlineCount] = '';
3286 }
3287 if( $istemplate )
3288 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3289 else
3290 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3291 }
3292
3293 # give headline the correct <h#> tag
3294 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3295
3296 $headlineCount++;
3297 if( !$istemplate )
3298 $sectionCount++;
3299 }
3300
3301 if( $enoughToc ) {
3302 if( $toclevel<$wgMaxTocLevel ) {
3303 $toc .= $sk->tocUnindent( $toclevel - 1 );
3304 }
3305 $toc = $sk->tocList( $toc );
3306 }
3307
3308 # split up and insert constructed headlines
3309
3310 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3311 $i = 0;
3312
3313 foreach( $blocks as $block ) {
3314 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3315 # This is the [edit] link that appears for the top block of text when
3316 # section editing is enabled
3317
3318 # Disabled because it broke block formatting
3319 # For example, a bullet point in the top line
3320 # $full .= $sk->editSectionLink(0);
3321 }
3322 $full .= $block;
3323 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3324 # Top anchor now in skin
3325 $full = $full.$toc;
3326 }
3327
3328 if( !empty( $head[$i] ) ) {
3329 $full .= $head[$i];
3330 }
3331 $i++;
3332 }
3333 if( $this->mForceTocPosition ) {
3334 return str_replace( '<!--MWTOC-->', $toc, $full );
3335 } else {
3336 return $full;
3337 }
3338 }
3339
3340 /**
3341 * Return an HTML link for the "ISBN 123456" text
3342 * @private
3343 */
3344 function magicISBN( $text ) {
3345 $fname = 'Parser::magicISBN';
3346 wfProfileIn( $fname );
3347
3348 $a = split( 'ISBN ', ' '.$text );
3349 if ( count ( $a ) < 2 ) {
3350 wfProfileOut( $fname );
3351 return $text;
3352 }
3353 $text = substr( array_shift( $a ), 1);
3354 $valid = '0123456789-Xx';
3355
3356 foreach ( $a as $x ) {
3357 # hack: don't replace inside thumbnail title/alt
3358 # attributes
3359 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3360 $text .= "ISBN $x";
3361 continue;
3362 }
3363
3364 $isbn = $blank = '' ;
3365 while ( ' ' == $x{0} ) {
3366 $blank .= ' ';
3367 $x = substr( $x, 1 );
3368 }
3369 if ( $x == '' ) { # blank isbn
3370 $text .= "ISBN $blank";
3371 continue;
3372 }
3373 while ( strstr( $valid, $x{0} ) != false ) {
3374 $isbn .= $x{0};
3375 $x = substr( $x, 1 );
3376 }
3377 $num = str_replace( '-', '', $isbn );
3378 $num = str_replace( ' ', '', $num );
3379 $num = str_replace( 'x', 'X', $num );
3380
3381 if ( '' == $num ) {
3382 $text .= "ISBN $blank$x";
3383 } else {
3384 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
3385 $text .= '<a href="' .
3386 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3387 "\" class=\"internal\">ISBN $isbn</a>";
3388 $text .= $x;
3389 }
3390 }
3391 wfProfileOut( $fname );
3392 return $text;
3393 }
3394
3395 /**
3396 * Return an HTML link for the "RFC 1234" text
3397 *
3398 * @private
3399 * @param string $text Text to be processed
3400 * @param string $keyword Magic keyword to use (default RFC)
3401 * @param string $urlmsg Interface message to use (default rfcurl)
3402 * @return string
3403 */
3404 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3405
3406 $valid = '0123456789';
3407 $internal = false;
3408
3409 $a = split( $keyword, ' '.$text );
3410 if ( count ( $a ) < 2 ) {
3411 return $text;
3412 }
3413 $text = substr( array_shift( $a ), 1);
3414
3415 /* Check if keyword is preceed by [[.
3416 * This test is made here cause of the array_shift above
3417 * that prevent the test to be done in the foreach.
3418 */
3419 if ( substr( $text, -2 ) == '[[' ) {
3420 $internal = true;
3421 }
3422
3423 foreach ( $a as $x ) {
3424 /* token might be empty if we have RFC RFC 1234 */
3425 if ( $x=='' ) {
3426 $text.=$keyword;
3427 continue;
3428 }
3429
3430 # hack: don't replace inside thumbnail title/alt
3431 # attributes
3432 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3433 $text .= $keyword . $x;
3434 continue;
3435 }
3436
3437 $id = $blank = '' ;
3438
3439 /** remove and save whitespaces in $blank */
3440 while ( $x{0} == ' ' ) {
3441 $blank .= ' ';
3442 $x = substr( $x, 1 );
3443 }
3444
3445 /** remove and save the rfc number in $id */
3446 while ( strstr( $valid, $x{0} ) != false ) {
3447 $id .= $x{0};
3448 $x = substr( $x, 1 );
3449 }
3450
3451 if ( $id == '' ) {
3452 /* call back stripped spaces*/
3453 $text .= $keyword.$blank.$x;
3454 } elseif( $internal ) {
3455 /* normal link */
3456 $text .= $keyword.$id.$x;
3457 } else {
3458 /* build the external link*/
3459 $url = wfMsg( $urlmsg, $id);
3460 $sk =& $this->mOptions->getSkin();
3461 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3462 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3463 }
3464
3465 /* Check if the next RFC keyword is preceed by [[ */
3466 $internal = ( substr($x,-2) == '[[' );
3467 }
3468 return $text;
3469 }
3470
3471 /**
3472 * Transform wiki markup when saving a page by doing \r\n -> \n
3473 * conversion, substitting signatures, {{subst:}} templates, etc.
3474 *
3475 * @param string $text the text to transform
3476 * @param Title &$title the Title object for the current article
3477 * @param User &$user the User object describing the current user
3478 * @param ParserOptions $options parsing options
3479 * @param bool $clearState whether to clear the parser state first
3480 * @return string the altered wiki markup
3481 * @public
3482 */
3483 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3484 $this->mOptions = $options;
3485 $this->mTitle =& $title;
3486 $this->mOutputType = OT_WIKI;
3487
3488 if ( $clearState ) {
3489 $this->clearState();
3490 }
3491
3492 $stripState = false;
3493 $pairs = array(
3494 "\r\n" => "\n",
3495 );
3496 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3497 $text = $this->strip( $text, $stripState, true );
3498 $text = $this->pstPass2( $text, $stripState, $user );
3499 $text = $this->unstrip( $text, $stripState );
3500 $text = $this->unstripNoWiki( $text, $stripState );
3501 return $text;
3502 }
3503
3504 /**
3505 * Pre-save transform helper function
3506 * @private
3507 */
3508 function pstPass2( $text, &$stripState, &$user ) {
3509 global $wgContLang, $wgLocaltimezone;
3510
3511 /* Note: This is the timestamp saved as hardcoded wikitext to
3512 * the database, we use $wgContLang here in order to give
3513 * everyone the same signature and use the default one rather
3514 * than the one selected in each user's preferences.
3515 */
3516 if ( isset( $wgLocaltimezone ) ) {
3517 $oldtz = getenv( 'TZ' );
3518 putenv( 'TZ='.$wgLocaltimezone );
3519 }
3520 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3521 ' (' . date( 'T' ) . ')';
3522 if ( isset( $wgLocaltimezone ) ) {
3523 putenv( 'TZ='.$oldtz );
3524 }
3525
3526 # Variable replacement
3527 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3528 $text = $this->replaceVariables( $text );
3529
3530 # Strip out <nowiki> etc. added via replaceVariables
3531 $text = $this->strip( $text, $stripState );
3532
3533 # Signatures
3534 $sigText = $this->getUserSig( $user );
3535 $text = strtr( $text, array(
3536 '~~~~~' => $d,
3537 '~~~~' => "$sigText $d",
3538 '~~~' => $sigText
3539 ) );
3540
3541 # Context links: [[|name]] and [[name (context)|]]
3542 #
3543 global $wgLegalTitleChars;
3544 $tc = "[$wgLegalTitleChars]";
3545 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3546
3547 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3548 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3549
3550 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3551 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3552 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3553 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3554 $context = '';
3555 $t = $this->mTitle->getText();
3556 if ( preg_match( $conpat, $t, $m ) ) {
3557 $context = $m[2];
3558 }
3559 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3560 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3561 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3562
3563 if ( '' == $context ) {
3564 $text = preg_replace( $p2, '[[\\1]]', $text );
3565 } else {
3566 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3567 }
3568
3569 # Trim trailing whitespace
3570 # MAG_END (__END__) tag allows for trailing
3571 # whitespace to be deliberately included
3572 $text = rtrim( $text );
3573 $mw =& MagicWord::get( MAG_END );
3574 $mw->matchAndRemove( $text );
3575
3576 return $text;
3577 }
3578
3579 /**
3580 * Fetch the user's signature text, if any, and normalize to
3581 * validated, ready-to-insert wikitext.
3582 *
3583 * @param User $user
3584 * @return string
3585 * @private
3586 */
3587 function getUserSig( &$user ) {
3588 $username = $user->getName();
3589 $nickname = $user->getOption( 'nickname' );
3590 $nickname = $nickname === '' ? $username : $nickname;
3591
3592 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3593 # Sig. might contain markup; validate this
3594 if( $this->validateSig( $nickname ) !== false ) {
3595 # Validated; clean up (if needed) and return it
3596 return $this->cleanSig( $nickname, true );
3597 } else {
3598 # Failed to validate; fall back to the default
3599 $nickname = $username;
3600 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3601 }
3602 }
3603
3604 # If we're still here, make it a link to the user page
3605 $userpage = $user->getUserPage();
3606 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3607 }
3608
3609 /**
3610 * Check that the user's signature contains no bad XML
3611 *
3612 * @param string $text
3613 * @return mixed An expanded string, or false if invalid.
3614 */
3615 function validateSig( $text ) {
3616 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3617 }
3618
3619 /**
3620 * Clean up signature text
3621 *
3622 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3623 * 2) Substitute all transclusions
3624 *
3625 * @param string $text
3626 * @param $parsing Whether we're cleaning (preferences save) or parsing
3627 * @return string Signature text
3628 */
3629 function cleanSig( $text, $parsing = false ) {
3630 global $wgTitle;
3631 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI : OT_MSG );
3632
3633 $substWord = MagicWord::get( MAG_SUBST );
3634 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3635 $substText = '{{' . $substWord->getSynonym( 0 );
3636
3637 $text = preg_replace( $substRegex, $substText, $text );
3638 $text = preg_replace( '/~{3,5}/', '', $text );
3639 $text = $this->replaceVariables( $text );
3640
3641 $this->clearState();
3642 return $text;
3643 }
3644
3645 /**
3646 * Set up some variables which are usually set up in parse()
3647 * so that an external function can call some class members with confidence
3648 * @public
3649 */
3650 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3651 $this->mTitle =& $title;
3652 $this->mOptions = $options;
3653 $this->mOutputType = $outputType;
3654 if ( $clearState ) {
3655 $this->clearState();
3656 }
3657 }
3658
3659 /**
3660 * Transform a MediaWiki message by replacing magic variables.
3661 *
3662 * @param string $text the text to transform
3663 * @param ParserOptions $options options
3664 * @return string the text with variables substituted
3665 * @public
3666 */
3667 function transformMsg( $text, $options ) {
3668 global $wgTitle;
3669 static $executing = false;
3670
3671 $fname = "Parser::transformMsg";
3672
3673 # Guard against infinite recursion
3674 if ( $executing ) {
3675 return $text;
3676 }
3677 $executing = true;
3678
3679 wfProfileIn($fname);
3680
3681 $this->mTitle = $wgTitle;
3682 $this->mOptions = $options;
3683 $this->mOutputType = OT_MSG;
3684 $this->clearState();
3685 $text = $this->replaceVariables( $text );
3686
3687 $executing = false;
3688 wfProfileOut($fname);
3689 return $text;
3690 }
3691
3692 /**
3693 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3694 * The callback should have the following form:
3695 * function myParserHook( $text, $params, &$parser ) { ... }
3696 *
3697 * Transform and return $text. Use $parser for any required context, e.g. use
3698 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3699 *
3700 * @public
3701 *
3702 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3703 * @param mixed $callback The callback function (and object) to use for the tag
3704 *
3705 * @return The old value of the mTagHooks array associated with the hook
3706 */
3707 function setHook( $tag, $callback ) {
3708 $oldVal = @$this->mTagHooks[$tag];
3709 $this->mTagHooks[$tag] = $callback;
3710
3711 return $oldVal;
3712 }
3713
3714 /**
3715 * Create a function, e.g. {{sum:1|2|3}}
3716 * The callback function should have the form:
3717 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3718 *
3719 * The callback may either return the text result of the function, or an array with the text
3720 * in element 0, and a number of flags in the other elements. The names of the flags are
3721 * specified in the keys. Valid flags are:
3722 * found The text returned is valid, stop processing the template. This
3723 * is on by default.
3724 * nowiki Wiki markup in the return value should be escaped
3725 * noparse Unsafe HTML tags should not be stripped, etc.
3726 * noargs Don't replace triple-brace arguments in the return value
3727 * isHTML The returned text is HTML, armour it against wikitext transformation
3728 *
3729 * @public
3730 *
3731 * @param string $name The function name. Function names are case-insensitive.
3732 * @param mixed $callback The callback function (and object) to use
3733 *
3734 * @return The old callback function for this name, if any
3735 */
3736 function setFunctionHook( $name, $callback ) {
3737 $name = strtolower( $name );
3738 $oldVal = @$this->mFunctionHooks[$name];
3739 $this->mFunctionHooks[$name] = $callback;
3740 return $oldVal;
3741 }
3742
3743 /**
3744 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3745 * Placeholders created in Skin::makeLinkObj()
3746 * Returns an array of links found, indexed by PDBK:
3747 * 0 - broken
3748 * 1 - normal link
3749 * 2 - stub
3750 * $options is a bit field, RLH_FOR_UPDATE to select for update
3751 */
3752 function replaceLinkHolders( &$text, $options = 0 ) {
3753 global $wgUser;
3754 global $wgOutputReplace;
3755
3756 $fname = 'Parser::replaceLinkHolders';
3757 wfProfileIn( $fname );
3758
3759 $pdbks = array();
3760 $colours = array();
3761 $sk =& $this->mOptions->getSkin();
3762 $linkCache =& LinkCache::singleton();
3763
3764 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3765 wfProfileIn( $fname.'-check' );
3766 $dbr =& wfGetDB( DB_SLAVE );
3767 $page = $dbr->tableName( 'page' );
3768 $threshold = $wgUser->getOption('stubthreshold');
3769
3770 # Sort by namespace
3771 asort( $this->mLinkHolders['namespaces'] );
3772
3773 # Generate query
3774 $query = false;
3775 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3776 # Make title object
3777 $title = $this->mLinkHolders['titles'][$key];
3778
3779 # Skip invalid entries.
3780 # Result will be ugly, but prevents crash.
3781 if ( is_null( $title ) ) {
3782 continue;
3783 }
3784 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3785
3786 # Check if it's a static known link, e.g. interwiki
3787 if ( $title->isAlwaysKnown() ) {
3788 $colours[$pdbk] = 1;
3789 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3790 $colours[$pdbk] = 1;
3791 $this->mOutput->addLink( $title, $id );
3792 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3793 $colours[$pdbk] = 0;
3794 } else {
3795 # Not in the link cache, add it to the query
3796 if ( !isset( $current ) ) {
3797 $current = $ns;
3798 $query = "SELECT page_id, page_namespace, page_title";
3799 if ( $threshold > 0 ) {
3800 $query .= ', page_len, page_is_redirect';
3801 }
3802 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3803 } elseif ( $current != $ns ) {
3804 $current = $ns;
3805 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3806 } else {
3807 $query .= ', ';
3808 }
3809
3810 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3811 }
3812 }
3813 if ( $query ) {
3814 $query .= '))';
3815 if ( $options & RLH_FOR_UPDATE ) {
3816 $query .= ' FOR UPDATE';
3817 }
3818
3819 $res = $dbr->query( $query, $fname );
3820
3821 # Fetch data and form into an associative array
3822 # non-existent = broken
3823 # 1 = known
3824 # 2 = stub
3825 while ( $s = $dbr->fetchObject($res) ) {
3826 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3827 $pdbk = $title->getPrefixedDBkey();
3828 $linkCache->addGoodLinkObj( $s->page_id, $title );
3829 $this->mOutput->addLink( $title, $s->page_id );
3830
3831 if ( $threshold > 0 ) {
3832 $size = $s->page_len;
3833 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3834 $colours[$pdbk] = 1;
3835 } else {
3836 $colours[$pdbk] = 2;
3837 }
3838 } else {
3839 $colours[$pdbk] = 1;
3840 }
3841 }
3842 }
3843 wfProfileOut( $fname.'-check' );
3844
3845 # Construct search and replace arrays
3846 wfProfileIn( $fname.'-construct' );
3847 $wgOutputReplace = array();
3848 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3849 $pdbk = $pdbks[$key];
3850 $searchkey = "<!--LINK $key-->";
3851 $title = $this->mLinkHolders['titles'][$key];
3852 if ( empty( $colours[$pdbk] ) ) {
3853 $linkCache->addBadLinkObj( $title );
3854 $colours[$pdbk] = 0;
3855 $this->mOutput->addLink( $title, 0 );
3856 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3857 $this->mLinkHolders['texts'][$key],
3858 $this->mLinkHolders['queries'][$key] );
3859 } elseif ( $colours[$pdbk] == 1 ) {
3860 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3861 $this->mLinkHolders['texts'][$key],
3862 $this->mLinkHolders['queries'][$key] );
3863 } elseif ( $colours[$pdbk] == 2 ) {
3864 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3865 $this->mLinkHolders['texts'][$key],
3866 $this->mLinkHolders['queries'][$key] );
3867 }
3868 }
3869 wfProfileOut( $fname.'-construct' );
3870
3871 # Do the thing
3872 wfProfileIn( $fname.'-replace' );
3873
3874 $text = preg_replace_callback(
3875 '/(<!--LINK .*?-->)/',
3876 "wfOutputReplaceMatches",
3877 $text);
3878
3879 wfProfileOut( $fname.'-replace' );
3880 }
3881
3882 # Now process interwiki link holders
3883 # This is quite a bit simpler than internal links
3884 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3885 wfProfileIn( $fname.'-interwiki' );
3886 # Make interwiki link HTML
3887 $wgOutputReplace = array();
3888 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3889 $title = $this->mInterwikiLinkHolders['titles'][$key];
3890 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3891 }
3892
3893 $text = preg_replace_callback(
3894 '/<!--IWLINK (.*?)-->/',
3895 "wfOutputReplaceMatches",
3896 $text );
3897 wfProfileOut( $fname.'-interwiki' );
3898 }
3899
3900 wfProfileOut( $fname );
3901 return $colours;
3902 }
3903
3904 /**
3905 * Replace <!--LINK--> link placeholders with plain text of links
3906 * (not HTML-formatted).
3907 * @param string $text
3908 * @return string
3909 */
3910 function replaceLinkHoldersText( $text ) {
3911 $fname = 'Parser::replaceLinkHoldersText';
3912 wfProfileIn( $fname );
3913
3914 $text = preg_replace_callback(
3915 '/<!--(LINK|IWLINK) (.*?)-->/',
3916 array( &$this, 'replaceLinkHoldersTextCallback' ),
3917 $text );
3918
3919 wfProfileOut( $fname );
3920 return $text;
3921 }
3922
3923 /**
3924 * @param array $matches
3925 * @return string
3926 * @private
3927 */
3928 function replaceLinkHoldersTextCallback( $matches ) {
3929 $type = $matches[1];
3930 $key = $matches[2];
3931 if( $type == 'LINK' ) {
3932 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3933 return $this->mLinkHolders['texts'][$key];
3934 }
3935 } elseif( $type == 'IWLINK' ) {
3936 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3937 return $this->mInterwikiLinkHolders['texts'][$key];
3938 }
3939 }
3940 return $matches[0];
3941 }
3942
3943 /**
3944 * Renders an image gallery from a text with one line per image.
3945 * text labels may be given by using |-style alternative text. E.g.
3946 * Image:one.jpg|The number "1"
3947 * Image:tree.jpg|A tree
3948 * given as text will return the HTML of a gallery with two images,
3949 * labeled 'The number "1"' and
3950 * 'A tree'.
3951 */
3952 function renderImageGallery( $text ) {
3953 # Setup the parser
3954 $parserOptions = new ParserOptions;
3955 $localParser = new Parser();
3956
3957 $ig = new ImageGallery();
3958 $ig->setShowBytes( false );
3959 $ig->setShowFilename( false );
3960 $ig->setParsing();
3961 $lines = explode( "\n", $text );
3962
3963 foreach ( $lines as $line ) {
3964 # match lines like these:
3965 # Image:someimage.jpg|This is some image
3966 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3967 # Skip empty lines
3968 if ( count( $matches ) == 0 ) {
3969 continue;
3970 }
3971 $nt =& Title::newFromText( $matches[1] );
3972 if( is_null( $nt ) ) {
3973 # Bogus title. Ignore these so we don't bomb out later.
3974 continue;
3975 }
3976 if ( isset( $matches[3] ) ) {
3977 $label = $matches[3];
3978 } else {
3979 $label = '';
3980 }
3981
3982 $pout = $localParser->parse( $label , $this->mTitle, $parserOptions );
3983 $html = $pout->getText();
3984
3985 $ig->add( new Image( $nt ), $html );
3986
3987 # Only add real images (bug #5586)
3988 if ( $nt->getNamespace() == NS_IMAGE ) {
3989 $this->mOutput->addImage( $nt->getDBkey() );
3990 }
3991
3992 # Register links with the parent parser
3993 foreach( $pout->getLinks() as $ns => $keys ) {
3994 foreach( $keys as $dbk => $id )
3995 $this->mOutput->addLink( Title::makeTitle( $ns, $dbk ), $id );
3996 }
3997
3998 }
3999 return $ig->toHTML();
4000 }
4001
4002 /**
4003 * Parse image options text and use it to make an image
4004 */
4005 function makeImage( &$nt, $options ) {
4006 global $wgUseImageResize;
4007
4008 $align = '';
4009
4010 # Check if the options text is of the form "options|alt text"
4011 # Options are:
4012 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4013 # * left no resizing, just left align. label is used for alt= only
4014 # * right same, but right aligned
4015 # * none same, but not aligned
4016 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4017 # * center center the image
4018 # * framed Keep original image size, no magnify-button.
4019
4020 $part = explode( '|', $options);
4021
4022 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
4023 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
4024 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
4025 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
4026 $mwNone =& MagicWord::get( MAG_IMG_NONE );
4027 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
4028 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
4029 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
4030 $caption = '';
4031
4032 $width = $height = $framed = $thumb = false;
4033 $manual_thumb = '' ;
4034
4035 foreach( $part as $key => $val ) {
4036 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4037 $thumb=true;
4038 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4039 # use manually specified thumbnail
4040 $thumb=true;
4041 $manual_thumb = $match;
4042 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4043 # remember to set an alignment, don't render immediately
4044 $align = 'right';
4045 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4046 # remember to set an alignment, don't render immediately
4047 $align = 'left';
4048 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4049 # remember to set an alignment, don't render immediately
4050 $align = 'center';
4051 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4052 # remember to set an alignment, don't render immediately
4053 $align = 'none';
4054 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4055 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4056 # $match is the image width in pixels
4057 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4058 $width = intval( $m[1] );
4059 $height = intval( $m[2] );
4060 } else {
4061 $width = intval($match);
4062 }
4063 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4064 $framed=true;
4065 } else {
4066 $caption = $val;
4067 }
4068 }
4069 # Strip bad stuff out of the alt text
4070 $alt = $this->replaceLinkHoldersText( $caption );
4071
4072 # make sure there are no placeholders in thumbnail attributes
4073 # that are later expanded to html- so expand them now and
4074 # remove the tags
4075 $alt = $this->unstrip($alt, $this->mStripState);
4076 $alt = Sanitizer::stripAllTags( $alt );
4077
4078 # Linker does the rest
4079 $sk =& $this->mOptions->getSkin();
4080 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4081 }
4082
4083 /**
4084 * Set a flag in the output object indicating that the content is dynamic and
4085 * shouldn't be cached.
4086 */
4087 function disableCache() {
4088 wfDebug( "Parser output marked as uncacheable.\n" );
4089 $this->mOutput->mCacheTime = -1;
4090 }
4091
4092 /**#@+
4093 * Callback from the Sanitizer for expanding items found in HTML attribute
4094 * values, so they can be safely tested and escaped.
4095 * @param string $text
4096 * @param array $args
4097 * @return string
4098 * @private
4099 */
4100 function attributeStripCallback( &$text, $args ) {
4101 $text = $this->replaceVariables( $text, $args );
4102 $text = $this->unstripForHTML( $text );
4103 return $text;
4104 }
4105
4106 function unstripForHTML( $text ) {
4107 $text = $this->unstrip( $text, $this->mStripState );
4108 $text = $this->unstripNoWiki( $text, $this->mStripState );
4109 return $text;
4110 }
4111 /**#@-*/
4112
4113 /**#@+
4114 * Accessor/mutator
4115 */
4116 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4117 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4118 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4119 /**#@-*/
4120
4121 /**#@+
4122 * Accessor
4123 */
4124 function getTags() { return array_keys( $this->mTagHooks ); }
4125 /**#@-*/
4126 }
4127
4128 /**
4129 * @todo document
4130 * @package MediaWiki
4131 */
4132 class ParserOutput
4133 {
4134 var $mText, # The output text
4135 $mLanguageLinks, # List of the full text of language links, in the order they appear
4136 $mCategories, # Map of category names to sort keys
4137 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4138 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4139 $mVersion, # Compatibility check
4140 $mTitleText, # title text of the chosen language variant
4141 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4142 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4143 $mImages, # DB keys of the images used, in the array key only
4144 $mExternalLinks, # External link URLs, in the key only
4145 $mHTMLtitle, # Display HTML title
4146 $mSubtitle, # Additional subtitle
4147 $mNewSection; # Show a new section link?
4148
4149 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4150 $containsOldMagic = false, $titletext = '' )
4151 {
4152 $this->mText = $text;
4153 $this->mLanguageLinks = $languageLinks;
4154 $this->mCategories = $categoryLinks;
4155 $this->mContainsOldMagic = $containsOldMagic;
4156 $this->mCacheTime = '';
4157 $this->mVersion = MW_PARSER_VERSION;
4158 $this->mTitleText = $titletext;
4159 $this->mLinks = array();
4160 $this->mTemplates = array();
4161 $this->mImages = array();
4162 $this->mExternalLinks = array();
4163 $this->mHTMLtitle = "" ;
4164 $this->mSubtitle = "" ;
4165 $this->mNewSection = false;
4166 }
4167
4168 function getText() { return $this->mText; }
4169 function &getLanguageLinks() { return $this->mLanguageLinks; }
4170 function getCategoryLinks() { return array_keys( $this->mCategories ); }
4171 function &getCategories() { return $this->mCategories; }
4172 function getCacheTime() { return $this->mCacheTime; }
4173 function getTitleText() { return $this->mTitleText; }
4174 function &getLinks() { return $this->mLinks; }
4175 function &getTemplates() { return $this->mTemplates; }
4176 function &getImages() { return $this->mImages; }
4177 function &getExternalLinks() { return $this->mExternalLinks; }
4178
4179 function containsOldMagic() { return $this->mContainsOldMagic; }
4180 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
4181 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
4182 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
4183 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
4184 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
4185 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
4186
4187 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
4188 function addImage( $name ) { $this->mImages[$name] = 1; }
4189 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
4190 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
4191
4192 function setNewSection( $value ) {
4193 $this->mNewSection = (bool)$value;
4194 }
4195 function getNewSection() {
4196 return (bool)$this->mNewSection;
4197 }
4198
4199 function addLink( $title, $id ) {
4200 $ns = $title->getNamespace();
4201 $dbk = $title->getDBkey();
4202 if ( !isset( $this->mLinks[$ns] ) ) {
4203 $this->mLinks[$ns] = array();
4204 }
4205 $this->mLinks[$ns][$dbk] = $id;
4206 }
4207
4208 function addTemplate( $title, $id ) {
4209 $ns = $title->getNamespace();
4210 $dbk = $title->getDBkey();
4211 if ( !isset( $this->mTemplates[$ns] ) ) {
4212 $this->mTemplates[$ns] = array();
4213 }
4214 $this->mTemplates[$ns][$dbk] = $id;
4215 }
4216
4217 /**
4218 * Return true if this cached output object predates the global or
4219 * per-article cache invalidation timestamps, or if it comes from
4220 * an incompatible older version.
4221 *
4222 * @param string $touched the affected article's last touched timestamp
4223 * @return bool
4224 * @public
4225 */
4226 function expired( $touched ) {
4227 global $wgCacheEpoch;
4228 return $this->getCacheTime() == -1 || // parser says it's uncacheable
4229 $this->getCacheTime() < $touched ||
4230 $this->getCacheTime() <= $wgCacheEpoch ||
4231 !isset( $this->mVersion ) ||
4232 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
4233 }
4234 }
4235
4236 /**
4237 * Set options of the Parser
4238 * @todo document
4239 * @package MediaWiki
4240 */
4241 class ParserOptions
4242 {
4243 # All variables are private
4244 var $mUseTeX; # Use texvc to expand <math> tags
4245 var $mUseDynamicDates; # Use DateFormatter to format dates
4246 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4247 var $mAllowExternalImages; # Allow external images inline
4248 var $mAllowExternalImagesFrom; # If not, any exception?
4249 var $mSkin; # Reference to the preferred skin
4250 var $mDateFormat; # Date format index
4251 var $mEditSection; # Create "edit section" links
4252 var $mNumberHeadings; # Automatically number headings
4253 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4254 var $mTidy; # Ask for tidy cleanup
4255 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4256
4257 function getUseTeX() { return $this->mUseTeX; }
4258 function getUseDynamicDates() { return $this->mUseDynamicDates; }
4259 function getInterwikiMagic() { return $this->mInterwikiMagic; }
4260 function getAllowExternalImages() { return $this->mAllowExternalImages; }
4261 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
4262 function &getSkin() { return $this->mSkin; }
4263 function getDateFormat() { return $this->mDateFormat; }
4264 function getEditSection() { return $this->mEditSection; }
4265 function getNumberHeadings() { return $this->mNumberHeadings; }
4266 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
4267 function getTidy() { return $this->mTidy; }
4268 function getInterfaceMessage() { return $this->mInterfaceMessage; }
4269
4270 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
4271 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
4272 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
4273 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
4274 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
4275 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
4276 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
4277 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
4278 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
4279 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
4280 function setSkin( &$x ) { $this->mSkin =& $x; }
4281 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage, $x); }
4282
4283 function ParserOptions() {
4284 global $wgUser;
4285 $this->initialiseFromUser( $wgUser );
4286 }
4287
4288 /**
4289 * Get parser options
4290 * @static
4291 */
4292 function newFromUser( &$user ) {
4293 $popts = new ParserOptions;
4294 $popts->initialiseFromUser( $user );
4295 return $popts;
4296 }
4297
4298 /** Get user options */
4299 function initialiseFromUser( &$userInput ) {
4300 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4301 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4302 $fname = 'ParserOptions::initialiseFromUser';
4303 wfProfileIn( $fname );
4304 if ( !$userInput ) {
4305 $user = new User;
4306 $user->setLoaded( true );
4307 } else {
4308 $user =& $userInput;
4309 }
4310
4311 $this->mUseTeX = $wgUseTeX;
4312 $this->mUseDynamicDates = $wgUseDynamicDates;
4313 $this->mInterwikiMagic = $wgInterwikiMagic;
4314 $this->mAllowExternalImages = $wgAllowExternalImages;
4315 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
4316 wfProfileIn( $fname.'-skin' );
4317 $this->mSkin =& $user->getSkin();
4318 wfProfileOut( $fname.'-skin' );
4319 $this->mDateFormat = $user->getOption( 'date' );
4320 $this->mEditSection = true;
4321 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4322 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4323 $this->mTidy = false;
4324 $this->mInterfaceMessage = false;
4325 wfProfileOut( $fname );
4326 }
4327 }
4328
4329 /**
4330 * Callback function used by Parser::replaceLinkHolders()
4331 * to substitute link placeholders.
4332 */
4333 function &wfOutputReplaceMatches( $matches ) {
4334 global $wgOutputReplace;
4335 return $wgOutputReplace[$matches[1]];
4336 }
4337
4338 /**
4339 * Return the total number of articles
4340 */
4341 function wfNumberOfArticles() {
4342 global $wgNumberOfArticles;
4343
4344 wfLoadSiteStats();
4345 return $wgNumberOfArticles;
4346 }
4347
4348 /**
4349 * Return the number of files
4350 */
4351 function wfNumberOfFiles() {
4352 $fname = 'wfNumberOfFiles';
4353
4354 wfProfileIn( $fname );
4355 $dbr =& wfGetDB( DB_SLAVE );
4356 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4357 wfProfileOut( $fname );
4358
4359 return $numImages;
4360 }
4361
4362 /**
4363 * Return the number of user accounts
4364 * @return integer
4365 */
4366 function wfNumberOfUsers() {
4367 wfProfileIn( 'wfNumberOfUsers' );
4368 $dbr =& wfGetDB( DB_SLAVE );
4369 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4370 wfProfileOut( 'wfNumberOfUsers' );
4371 return (int)$count;
4372 }
4373
4374 /**
4375 * Return the total number of pages
4376 * @return integer
4377 */
4378 function wfNumberOfPages() {
4379 wfProfileIn( 'wfNumberOfPages' );
4380 $dbr =& wfGetDB( DB_SLAVE );
4381 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4382 wfProfileOut( 'wfNumberOfPages' );
4383 return (int)$count;
4384 }
4385
4386 /**
4387 * Get various statistics from the database
4388 * @private
4389 */
4390 function wfLoadSiteStats() {
4391 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4392 $fname = 'wfLoadSiteStats';
4393
4394 if ( -1 != $wgNumberOfArticles ) return;
4395 $dbr =& wfGetDB( DB_SLAVE );
4396 $s = $dbr->selectRow( 'site_stats',
4397 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4398 array( 'ss_row_id' => 1 ), $fname
4399 );
4400
4401 if ( $s === false ) {
4402 return;
4403 } else {
4404 $wgTotalViews = $s->ss_total_views;
4405 $wgTotalEdits = $s->ss_total_edits;
4406 $wgNumberOfArticles = $s->ss_good_articles;
4407 }
4408 }
4409
4410 /**
4411 * Escape html tags
4412 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4413 *
4414 * @param $in String: text that might contain HTML tags.
4415 * @return string Escaped string
4416 */
4417 function wfEscapeHTMLTagsOnly( $in ) {
4418 return str_replace(
4419 array( '"', '>', '<' ),
4420 array( '&quot;', '&gt;', '&lt;' ),
4421 $in );
4422 }
4423
4424 ?>