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