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