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