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