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