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