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