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