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