Fix {{NUMBEROFADMINS}} magic word
[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_NUMBEROFADMINS:
2247 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2248 case MAG_CURRENTTIMESTAMP:
2249 return $varCache[$index] = wfTimestampNow();
2250 case MAG_CURRENTVERSION:
2251 global $wgVersion;
2252 return $wgVersion;
2253 case MAG_SITENAME:
2254 return $wgSitename;
2255 case MAG_SERVER:
2256 return $wgServer;
2257 case MAG_SERVERNAME:
2258 return $wgServerName;
2259 case MAG_SCRIPTPATH:
2260 return $wgScriptPath;
2261 case MAG_DIRECTIONMARK:
2262 return $wgContLang->getDirMark();
2263 case MAG_CONTENTLANGUAGE:
2264 global $wgContLanguageCode;
2265 return $wgContLanguageCode;
2266 default:
2267 $ret = null;
2268 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2269 return $ret;
2270 else
2271 return null;
2272 }
2273 }
2274
2275 /**
2276 * initialise the magic variables (like CURRENTMONTHNAME)
2277 *
2278 * @private
2279 */
2280 function initialiseVariables() {
2281 $fname = 'Parser::initialiseVariables';
2282 wfProfileIn( $fname );
2283 global $wgVariableIDs;
2284 $this->mVariables = array();
2285 foreach ( $wgVariableIDs as $id ) {
2286 $mw =& MagicWord::get( $id );
2287 $mw->addToArray( $this->mVariables, $id );
2288 }
2289 wfProfileOut( $fname );
2290 }
2291
2292 /**
2293 * parse any parentheses in format ((title|part|part))
2294 * and call callbacks to get a replacement text for any found piece
2295 *
2296 * @param string $text The text to parse
2297 * @param array $callbacks rules in form:
2298 * '{' => array( # opening parentheses
2299 * 'end' => '}', # closing parentheses
2300 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2301 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2302 * )
2303 * )
2304 * @private
2305 */
2306 function replace_callback ($text, $callbacks) {
2307 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2308 $lastOpeningBrace = -1; # last not closed parentheses
2309
2310 for ($i = 0; $i < strlen($text); $i++) {
2311 # check for any opening brace
2312 $rule = null;
2313 $nextPos = -1;
2314 foreach ($callbacks as $key => $value) {
2315 $pos = strpos ($text, $key, $i);
2316 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
2317 $rule = $value;
2318 $nextPos = $pos;
2319 }
2320 }
2321
2322 if ($lastOpeningBrace >= 0) {
2323 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2324
2325 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2326 $rule = null;
2327 $nextPos = $pos;
2328 }
2329
2330 $pos = strpos ($text, '|', $i);
2331
2332 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2333 $rule = null;
2334 $nextPos = $pos;
2335 }
2336 }
2337
2338 if ($nextPos == -1)
2339 break;
2340
2341 $i = $nextPos;
2342
2343 # found openning brace, lets add it to parentheses stack
2344 if (null != $rule) {
2345 $piece = array('brace' => $text[$i],
2346 'braceEnd' => $rule['end'],
2347 'count' => 1,
2348 'title' => '',
2349 'parts' => null);
2350
2351 # count openning brace characters
2352 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2353 $piece['count']++;
2354 $i++;
2355 }
2356
2357 $piece['startAt'] = $i+1;
2358 $piece['partStart'] = $i+1;
2359
2360 # we need to add to stack only if openning brace count is enough for any given rule
2361 foreach ($rule['cb'] as $cnt => $fn) {
2362 if ($piece['count'] >= $cnt) {
2363 $lastOpeningBrace ++;
2364 $openingBraceStack[$lastOpeningBrace] = $piece;
2365 break;
2366 }
2367 }
2368
2369 continue;
2370 }
2371 else if ($lastOpeningBrace >= 0) {
2372 # first check if it is a closing brace
2373 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2374 # lets check if it is enough characters for closing brace
2375 $count = 1;
2376 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2377 $count++;
2378
2379 # if there are more closing parentheses than opening ones, we parse less
2380 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2381 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2382
2383 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2384 $matchingCount = 0;
2385 $matchingCallback = null;
2386 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2387 if ($count >= $cnt && $matchingCount < $cnt) {
2388 $matchingCount = $cnt;
2389 $matchingCallback = $fn;
2390 }
2391 }
2392
2393 if ($matchingCount == 0) {
2394 $i += $count - 1;
2395 continue;
2396 }
2397
2398 # lets set a title or last part (if '|' was found)
2399 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2400 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2401 else
2402 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2403
2404 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2405 $pieceEnd = $i + $matchingCount;
2406
2407 if( is_callable( $matchingCallback ) ) {
2408 $cbArgs = array (
2409 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2410 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2411 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2412 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2413 );
2414 # finally we can call a user callback and replace piece of text
2415 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2416 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2417 $i = $pieceStart + strlen($replaceWith) - 1;
2418 }
2419 else {
2420 # null value for callback means that parentheses should be parsed, but not replaced
2421 $i += $matchingCount - 1;
2422 }
2423
2424 # reset last openning parentheses, but keep it in case there are unused characters
2425 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2426 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2427 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2428 'title' => '',
2429 'parts' => null,
2430 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2431 $openingBraceStack[$lastOpeningBrace--] = null;
2432
2433 if ($matchingCount < $piece['count']) {
2434 $piece['count'] -= $matchingCount;
2435 $piece['startAt'] -= $matchingCount;
2436 $piece['partStart'] = $piece['startAt'];
2437 # do we still qualify for any callback with remaining count?
2438 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2439 if ($piece['count'] >= $cnt) {
2440 $lastOpeningBrace ++;
2441 $openingBraceStack[$lastOpeningBrace] = $piece;
2442 break;
2443 }
2444 }
2445 }
2446 continue;
2447 }
2448
2449 # lets set a title if it is a first separator, or next part otherwise
2450 if ($text[$i] == '|') {
2451 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2452 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2453 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2454 }
2455 else
2456 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2457
2458 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2459 }
2460 }
2461 }
2462
2463 return $text;
2464 }
2465
2466 /**
2467 * Replace magic variables, templates, and template arguments
2468 * with the appropriate text. Templates are substituted recursively,
2469 * taking care to avoid infinite loops.
2470 *
2471 * Note that the substitution depends on value of $mOutputType:
2472 * OT_WIKI: only {{subst:}} templates
2473 * OT_MSG: only magic variables
2474 * OT_HTML: all templates and magic variables
2475 *
2476 * @param string $tex The text to transform
2477 * @param array $args Key-value pairs representing template parameters to substitute
2478 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2479 * @private
2480 */
2481 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2482 # Prevent too big inclusions
2483 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2484 return $text;
2485 }
2486
2487 $fname = 'Parser::replaceVariables';
2488 wfProfileIn( $fname );
2489
2490 # This function is called recursively. To keep track of arguments we need a stack:
2491 array_push( $this->mArgStack, $args );
2492
2493 $braceCallbacks = array();
2494 if ( !$argsOnly ) {
2495 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2496 }
2497 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2498 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2499 }
2500 $callbacks = array();
2501 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2502 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2503 $text = $this->replace_callback ($text, $callbacks);
2504
2505 array_pop( $this->mArgStack );
2506
2507 wfProfileOut( $fname );
2508 return $text;
2509 }
2510
2511 /**
2512 * Replace magic variables
2513 * @private
2514 */
2515 function variableSubstitution( $matches ) {
2516 $fname = 'Parser::variableSubstitution';
2517 $varname = $matches[1];
2518 wfProfileIn( $fname );
2519 if ( !$this->mVariables ) {
2520 $this->initialiseVariables();
2521 }
2522 $skip = false;
2523 if ( $this->mOutputType == OT_WIKI ) {
2524 # Do only magic variables prefixed by SUBST
2525 $mwSubst =& MagicWord::get( MAG_SUBST );
2526 if (!$mwSubst->matchStartAndRemove( $varname ))
2527 $skip = true;
2528 # Note that if we don't substitute the variable below,
2529 # we don't remove the {{subst:}} magic word, in case
2530 # it is a template rather than a magic variable.
2531 }
2532 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2533 $id = $this->mVariables[$varname];
2534 $text = $this->getVariableValue( $id );
2535 $this->mOutput->mContainsOldMagic = true;
2536 } else {
2537 $text = $matches[0];
2538 }
2539 wfProfileOut( $fname );
2540 return $text;
2541 }
2542
2543 # Split template arguments
2544 function getTemplateArgs( $argsString ) {
2545 if ( $argsString === '' ) {
2546 return array();
2547 }
2548
2549 $args = explode( '|', substr( $argsString, 1 ) );
2550
2551 # If any of the arguments contains a '[[' but no ']]', it needs to be
2552 # merged with the next arg because the '|' character between belongs
2553 # to the link syntax and not the template parameter syntax.
2554 $argc = count($args);
2555
2556 for ( $i = 0; $i < $argc-1; $i++ ) {
2557 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2558 $args[$i] .= '|'.$args[$i+1];
2559 array_splice($args, $i+1, 1);
2560 $i--;
2561 $argc--;
2562 }
2563 }
2564
2565 return $args;
2566 }
2567
2568 /**
2569 * Return the text of a template, after recursively
2570 * replacing any variables or templates within the template.
2571 *
2572 * @param array $piece The parts of the template
2573 * $piece['text']: matched text
2574 * $piece['title']: the title, i.e. the part before the |
2575 * $piece['parts']: the parameter array
2576 * @return string the text of the template
2577 * @private
2578 */
2579 function braceSubstitution( $piece ) {
2580 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2581 $fname = 'Parser::braceSubstitution';
2582 wfProfileIn( $fname );
2583
2584 # Flags
2585 $found = false; # $text has been filled
2586 $nowiki = false; # wiki markup in $text should be escaped
2587 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2588 $noargs = false; # Don't replace triple-brace arguments in $text
2589 $replaceHeadings = false; # Make the edit section links go to the template not the article
2590 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2591 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2592
2593 # Title object, where $text came from
2594 $title = NULL;
2595
2596 $linestart = '';
2597
2598 # $part1 is the bit before the first |, and must contain only title characters
2599 # $args is a list of arguments, starting from index 0, not including $part1
2600
2601 $part1 = $piece['title'];
2602 # If the third subpattern matched anything, it will start with |
2603
2604 if (null == $piece['parts']) {
2605 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2606 if ($replaceWith != $piece['text']) {
2607 $text = $replaceWith;
2608 $found = true;
2609 $noparse = true;
2610 $noargs = true;
2611 }
2612 }
2613
2614 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2615 $argc = count( $args );
2616
2617 # SUBST
2618 if ( !$found ) {
2619 $mwSubst =& MagicWord::get( MAG_SUBST );
2620 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2621 # One of two possibilities is true:
2622 # 1) Found SUBST but not in the PST phase
2623 # 2) Didn't find SUBST and in the PST phase
2624 # In either case, return without further processing
2625 $text = $piece['text'];
2626 $found = true;
2627 $noparse = true;
2628 $noargs = true;
2629 }
2630 }
2631
2632 # MSG, MSGNW, INT and RAW
2633 if ( !$found ) {
2634 # Check for MSGNW:
2635 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2636 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2637 $nowiki = true;
2638 } else {
2639 # Remove obsolete MSG:
2640 $mwMsg =& MagicWord::get( MAG_MSG );
2641 $mwMsg->matchStartAndRemove( $part1 );
2642 }
2643
2644 # Check for RAW:
2645 $mwRaw =& MagicWord::get( MAG_RAW );
2646 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2647 $forceRawInterwiki = true;
2648 }
2649
2650 # Check if it is an internal message
2651 $mwInt =& MagicWord::get( MAG_INT );
2652 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2653 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2654 $text = $linestart . wfMsgReal( $part1, $args, true );
2655 $found = true;
2656 }
2657 }
2658 }
2659
2660 # NS
2661 if ( !$found ) {
2662 # Check for NS: (namespace expansion)
2663 $mwNs = MagicWord::get( MAG_NS );
2664 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2665 if ( intval( $part1 ) || $part1 == "0" ) {
2666 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2667 $found = true;
2668 } else {
2669 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2670 if ( !is_null( $index ) ) {
2671 $text = $linestart . $wgContLang->getNsText( $index );
2672 $found = true;
2673 }
2674 }
2675 }
2676 }
2677
2678 # URLENCODE
2679 if( !$found ) {
2680 $urlencode =& MagicWord::get( MAG_URLENCODE );
2681 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2682 $text = $linestart . urlencode( $part1 );
2683 $found = true;
2684 }
2685 }
2686
2687 # LCFIRST, UCFIRST, LC and UC
2688 if ( !$found ) {
2689 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2690 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2691 $lc =& MagicWord::get( MAG_LC );
2692 $uc =& MagicWord::get( MAG_UC );
2693 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2694 $text = $linestart . $wgContLang->lcfirst( $part1 );
2695 $found = true;
2696 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2697 $text = $linestart . $wgContLang->ucfirst( $part1 );
2698 $found = true;
2699 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2700 $text = $linestart . $wgContLang->lc( $part1 );
2701 $found = true;
2702 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2703 $text = $linestart . $wgContLang->uc( $part1 );
2704 $found = true;
2705 }
2706 }
2707
2708 # LOCALURL and FULLURL
2709 if ( !$found ) {
2710 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2711 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2712 $mwFull =& MagicWord::get( MAG_FULLURL );
2713 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2714
2715
2716 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2717 $func = 'getLocalURL';
2718 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2719 $func = 'escapeLocalURL';
2720 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2721 $func = 'getFullURL';
2722 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2723 $func = 'escapeFullURL';
2724 } else {
2725 $func = false;
2726 }
2727
2728 if ( $func !== false ) {
2729 $title = Title::newFromText( $part1 );
2730 # Due to order of execution of a lot of bits, the values might be encoded
2731 # before arriving here; if that's true, then the title can't be created
2732 # and the variable will fail. If we can't get a decent title from the first
2733 # attempt, url-decode and try for a second.
2734 if( is_null( $title ) )
2735 $title = Title::newFromUrl( urldecode( $part1 ) );
2736 if ( !is_null( $title ) ) {
2737 if ( $argc > 0 ) {
2738 $text = $linestart . $title->$func( $args[0] );
2739 } else {
2740 $text = $linestart . $title->$func();
2741 }
2742 $found = true;
2743 }
2744 }
2745 }
2746
2747 $lang = $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
2748 # GRAMMAR
2749 if ( !$found && $argc == 1 ) {
2750 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2751 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2752 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2753 $found = true;
2754 }
2755 }
2756
2757 # PLURAL
2758 if ( !$found && $argc >= 2 ) {
2759 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2760 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2761 while ( count($args) < 5 ) { $args[] = $args[count($args)-1]; }
2762 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1],
2763 $args[2], $args[3], $args[4]);
2764 $found = true;
2765 }
2766 }
2767
2768 # DISPLAYTITLE
2769 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2770 $mwDT =& MagicWord::get( MAG_DISPLAYTITLE );
2771 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2772
2773 # Set title in parser output object
2774 $param = $args[0];
2775 $parserOptions = new ParserOptions;
2776 $local_parser = new Parser ();
2777 $t2 = $local_parser->parse ( $param, $this->mTitle, $parserOptions, false );
2778 $this->mOutput->mHTMLtitle = $t2->GetText();
2779
2780 # Add subtitle
2781 $t = $this->mTitle->getPrefixedText();
2782 $this->mOutput->mSubtitle .= wfMsg('displaytitle', $t);
2783 $text = "" ;
2784 $found = true ;
2785 }
2786 }
2787
2788 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2789 if( !$found ) {
2790 $mwWordsToCheck = array( MAG_NUMBEROFPAGES => 'wfNumberOfPages',
2791 MAG_NUMBEROFUSERS => 'wfNumberOfUsers',
2792 MAG_NUMBEROFARTICLES => 'wfNumberOfArticles',
2793 MAG_NUMBEROFFILES => 'wfNumberOfFiles',
2794 MAG_NUMBEROFADMINS => 'wfNumberOfAdmins' );
2795 foreach( $mwWordsToCheck as $word => $func ) {
2796 $mwCurrentWord =& MagicWord::get( $word );
2797 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2798 $mwRawSuffix =& MagicWord::get( MAG_RAWSUFFIX );
2799 if( isset( $args[0] ) && $mwRawSuffix->match( $args[0] ) ) {
2800 # Raw and unformatted
2801 $text = $linestart . call_user_func( $func );
2802 } else {
2803 # Formatted according to the content default
2804 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2805 }
2806 $found = true;
2807 }
2808 }
2809 }
2810
2811 # PAGESINNAMESPACE
2812 if( !$found ) {
2813 $mwPagesInNs =& MagicWord::get( MAG_PAGESINNAMESPACE );
2814 if( $mwPagesInNs->matchStartAndRemove( $part1 ) ) {
2815 $found = true;
2816 $count = wfPagesInNs( intval( $part1 ) );
2817 $mwRawSuffix =& MagicWord::get( MAG_RAWSUFFIX );
2818 if( isset( $args[0] ) && $mwRawSuffix->match( $args[0] ) ) {
2819 $text = $linestart . $count;
2820 } else {
2821 $text = $linestart . $wgContLang->formatNum( $count );
2822 }
2823 }
2824 }
2825
2826 # #LANGUAGE:
2827 if( !$found ) {
2828 $mwLanguage =& MagicWord::get( MAG_LANGUAGE );
2829 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2830 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2831 $text = $linestart . ( $lang != '' ? $lang : $part1 );
2832 $found = true;
2833 }
2834 }
2835
2836 # Extensions
2837 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2838 $colonPos = strpos( $part1, ':' );
2839 if ( $colonPos !== false ) {
2840 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2841 if ( isset( $this->mFunctionHooks[$function] ) ) {
2842 $funcArgs = array_map( 'trim', $args );
2843 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos + 1 ) ) ), $funcArgs );
2844 $result = call_user_func_array( $this->mFunctionHooks[$function], $funcArgs );
2845 $found = true;
2846
2847 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2848 //$noargs = true;
2849 //$noparse = true;
2850
2851 if ( is_array( $result ) ) {
2852 $text = $linestart . $result[0];
2853 unset( $result[0] );
2854
2855 // Extract flags into the local scope
2856 // This allows callers to set flags such as nowiki, noparse, found, etc.
2857 extract( $result );
2858 } else {
2859 $text = $linestart . $result;
2860 }
2861 }
2862 }
2863 }
2864
2865 # Template table test
2866
2867 # Did we encounter this template already? If yes, it is in the cache
2868 # and we need to check for loops.
2869 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
2870 $found = true;
2871
2872 # Infinite loop test
2873 if ( isset( $this->mTemplatePath[$part1] ) ) {
2874 $noparse = true;
2875 $noargs = true;
2876 $found = true;
2877 $text = $linestart .
2878 '{{' . $part1 . '}}' .
2879 '<!-- WARNING: template loop detected -->';
2880 wfDebug( "$fname: template loop broken at '$part1'\n" );
2881 } else {
2882 # set $text to cached message.
2883 $text = $linestart . $this->mTemplates[$piece['title']];
2884 }
2885 }
2886
2887 # Load from database
2888 $lastPathLevel = $this->mTemplatePath;
2889 if ( !$found ) {
2890 $ns = NS_TEMPLATE;
2891 # declaring $subpage directly in the function call
2892 # does not work correctly with references and breaks
2893 # {{/subpage}}-style inclusions
2894 $subpage = '';
2895 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2896 if ($subpage !== '') {
2897 $ns = $this->mTitle->getNamespace();
2898 }
2899 $title = Title::newFromText( $part1, $ns );
2900
2901
2902 if ( !is_null( $title ) ) {
2903 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2904 # Check for language variants if the template is not found
2905 if($checkVariantLink && $title->getArticleID() == 0){
2906 $wgContLang->findVariantLink($part1, $title);
2907 }
2908
2909 if ( !$title->isExternal() ) {
2910 # Check for excessive inclusion
2911 $dbk = $title->getPrefixedDBkey();
2912 if ( $this->incrementIncludeCount( $dbk ) ) {
2913 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->mOutputType != OT_WIKI ) {
2914 $text = SpecialPage::capturePath( $title );
2915 if ( is_string( $text ) ) {
2916 $found = true;
2917 $noparse = true;
2918 $noargs = true;
2919 $isHTML = true;
2920 $this->disableCache();
2921 }
2922 } else {
2923 $articleContent = $this->fetchTemplate( $title );
2924 if ( $articleContent !== false ) {
2925 $found = true;
2926 $text = $articleContent;
2927 $replaceHeadings = true;
2928 }
2929 }
2930 }
2931
2932 # If the title is valid but undisplayable, make a link to it
2933 if ( $this->mOutputType == OT_HTML && !$found ) {
2934 $text = '[['.$title->getPrefixedText().']]';
2935 $found = true;
2936 }
2937 } elseif ( $title->isTrans() ) {
2938 // Interwiki transclusion
2939 if ( $this->mOutputType == OT_HTML && !$forceRawInterwiki ) {
2940 $text = $this->interwikiTransclude( $title, 'render' );
2941 $isHTML = true;
2942 $noparse = true;
2943 } else {
2944 $text = $this->interwikiTransclude( $title, 'raw' );
2945 $replaceHeadings = true;
2946 }
2947 $found = true;
2948 }
2949
2950 # Template cache array insertion
2951 # Use the original $piece['title'] not the mangled $part1, so that
2952 # modifiers such as RAW: produce separate cache entries
2953 if( $found ) {
2954 if( $isHTML ) {
2955 // A special page; don't store it in the template cache.
2956 } else {
2957 $this->mTemplates[$piece['title']] = $text;
2958 }
2959 $text = $linestart . $text;
2960 }
2961 }
2962 }
2963
2964 # Recursive parsing, escaping and link table handling
2965 # Only for HTML output
2966 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2967 $text = wfEscapeWikiText( $text );
2968 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found ) {
2969 if ( $noargs ) {
2970 $assocArgs = array();
2971 } else {
2972 # Clean up argument array
2973 $assocArgs = array();
2974 $index = 1;
2975 foreach( $args as $arg ) {
2976 $eqpos = strpos( $arg, '=' );
2977 if ( $eqpos === false ) {
2978 $assocArgs[$index++] = $arg;
2979 } else {
2980 $name = trim( substr( $arg, 0, $eqpos ) );
2981 $value = trim( substr( $arg, $eqpos+1 ) );
2982 if ( $value === false ) {
2983 $value = '';
2984 }
2985 if ( $name !== false ) {
2986 $assocArgs[$name] = $value;
2987 }
2988 }
2989 }
2990
2991 # Add a new element to the templace recursion path
2992 $this->mTemplatePath[$part1] = 1;
2993 }
2994
2995 if ( !$noparse ) {
2996 # If there are any <onlyinclude> tags, only include them
2997 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2998 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2999 $text = '';
3000 foreach ($m[1] as $piece)
3001 $text .= $piece;
3002 }
3003 # Remove <noinclude> sections and <includeonly> tags
3004 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3005 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3006
3007 if( $this->mOutputType == OT_HTML ) {
3008 # Strip <nowiki>, <pre>, etc.
3009 $text = $this->strip( $text, $this->mStripState );
3010 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3011 }
3012 $text = $this->replaceVariables( $text, $assocArgs );
3013
3014 # If the template begins with a table or block-level
3015 # element, it should be treated as beginning a new line.
3016 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
3017 $text = "\n" . $text;
3018 }
3019 } elseif ( !$noargs ) {
3020 # $noparse and !$noargs
3021 # Just replace the arguments, not any double-brace items
3022 # This is used for rendered interwiki transclusion
3023 $text = $this->replaceVariables( $text, $assocArgs, true );
3024 }
3025 }
3026 # Prune lower levels off the recursion check path
3027 $this->mTemplatePath = $lastPathLevel;
3028
3029 if ( !$found ) {
3030 wfProfileOut( $fname );
3031 return $piece['text'];
3032 } else {
3033 if ( $isHTML ) {
3034 # Replace raw HTML by a placeholder
3035 # Add a blank line preceding, to prevent it from mucking up
3036 # immediately preceding headings
3037 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
3038 } else {
3039 # replace ==section headers==
3040 # XXX this needs to go away once we have a better parser.
3041 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
3042 if( !is_null( $title ) )
3043 $encodedname = base64_encode($title->getPrefixedDBkey());
3044 else
3045 $encodedname = base64_encode("");
3046 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3047 PREG_SPLIT_DELIM_CAPTURE);
3048 $text = '';
3049 $nsec = 0;
3050 for( $i = 0; $i < count($m); $i += 2 ) {
3051 $text .= $m[$i];
3052 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
3053 $hl = $m[$i + 1];
3054 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3055 $text .= $hl;
3056 continue;
3057 }
3058 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3059 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3060 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3061
3062 $nsec++;
3063 }
3064 }
3065 }
3066 }
3067
3068 # Prune lower levels off the recursion check path
3069 $this->mTemplatePath = $lastPathLevel;
3070
3071 if ( !$found ) {
3072 wfProfileOut( $fname );
3073 return $piece['text'];
3074 } else {
3075 wfProfileOut( $fname );
3076 return $text;
3077 }
3078 }
3079
3080 /**
3081 * Fetch the unparsed text of a template and register a reference to it.
3082 */
3083 function fetchTemplate( $title ) {
3084 $text = false;
3085 // Loop to fetch the article, with up to 1 redirect
3086 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3087 $rev = Revision::newFromTitle( $title );
3088 $this->mOutput->addTemplate( $title, $title->getArticleID() );
3089 if ( !$rev ) {
3090 break;
3091 }
3092 $text = $rev->getText();
3093 if ( $text === false ) {
3094 break;
3095 }
3096 // Redirect?
3097 $title = Title::newFromRedirect( $text );
3098 }
3099 return $text;
3100 }
3101
3102 /**
3103 * Transclude an interwiki link.
3104 */
3105 function interwikiTransclude( $title, $action ) {
3106 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3107
3108 if (!$wgEnableScaryTranscluding)
3109 return wfMsg('scarytranscludedisabled');
3110
3111 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3112 // But we'll handle it generally anyway
3113 if ( $title->getNamespace() ) {
3114 // Use the canonical namespace, which should work anywhere
3115 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3116 } else {
3117 $articleName = $title->getDBkey();
3118 }
3119
3120 $url = str_replace('$1', urlencode($articleName), Title::getInterwikiLink($title->getInterwiki()));
3121 $url .= "?action=$action";
3122 if (strlen($url) > 255)
3123 return wfMsg('scarytranscludetoolong');
3124 return $this->fetchScaryTemplateMaybeFromCache($url);
3125 }
3126
3127 function fetchScaryTemplateMaybeFromCache($url) {
3128 global $wgTranscludeCacheExpiry;
3129 $dbr =& wfGetDB(DB_SLAVE);
3130 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3131 array('tc_url' => $url));
3132 if ($obj) {
3133 $time = $obj->tc_time;
3134 $text = $obj->tc_contents;
3135 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3136 return $text;
3137 }
3138 }
3139
3140 $text = wfGetHTTP($url);
3141 if (!$text)
3142 return wfMsg('scarytranscludefailed', $url);
3143
3144 $dbw =& wfGetDB(DB_MASTER);
3145 $dbw->replace('transcache', array('tc_url'), array(
3146 'tc_url' => $url,
3147 'tc_time' => time(),
3148 'tc_contents' => $text));
3149 return $text;
3150 }
3151
3152
3153 /**
3154 * Triple brace replacement -- used for template arguments
3155 * @private
3156 */
3157 function argSubstitution( $matches ) {
3158 $arg = trim( $matches['title'] );
3159 $text = $matches['text'];
3160 $inputArgs = end( $this->mArgStack );
3161
3162 if ( array_key_exists( $arg, $inputArgs ) ) {
3163 $text = $inputArgs[$arg];
3164 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
3165 $text = $matches['parts'][0];
3166 }
3167
3168 return $text;
3169 }
3170
3171 /**
3172 * Returns true if the function is allowed to include this entity
3173 * @private
3174 */
3175 function incrementIncludeCount( $dbk ) {
3176 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
3177 $this->mIncludeCount[$dbk] = 0;
3178 }
3179 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
3180 return true;
3181 } else {
3182 return false;
3183 }
3184 }
3185
3186 /**
3187 * Detect __NOGALLERY__ magic word and set a placeholder
3188 */
3189 function stripNoGallery( &$text ) {
3190 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3191 # do not add TOC
3192 $mw = MagicWord::get( MAG_NOGALLERY );
3193 $this->mOutput->mNoGallery = $mw->matchAndRemove( $text ) ;
3194 }
3195
3196 /**
3197 * Detect __TOC__ magic word and set a placeholder
3198 */
3199 function stripToc( $text ) {
3200 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3201 # do not add TOC
3202 $mw = MagicWord::get( MAG_NOTOC );
3203 if( $mw->matchAndRemove( $text ) ) {
3204 $this->mShowToc = false;
3205 }
3206
3207 $mw = MagicWord::get( MAG_TOC );
3208 if( $mw->match( $text ) ) {
3209 $this->mShowToc = true;
3210 $this->mForceTocPosition = true;
3211
3212 // Set a placeholder. At the end we'll fill it in with the TOC.
3213 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3214
3215 // Only keep the first one.
3216 $text = $mw->replace( '', $text );
3217 }
3218 return $text;
3219 }
3220
3221 /**
3222 * This function accomplishes several tasks:
3223 * 1) Auto-number headings if that option is enabled
3224 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3225 * 3) Add a Table of contents on the top for users who have enabled the option
3226 * 4) Auto-anchor headings
3227 *
3228 * It loops through all headlines, collects the necessary data, then splits up the
3229 * string and re-inserts the newly formatted headlines.
3230 *
3231 * @param string $text
3232 * @param boolean $isMain
3233 * @private
3234 */
3235 function formatHeadings( $text, $isMain=true ) {
3236 global $wgMaxTocLevel, $wgContLang;
3237
3238 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3239 if( !$this->mTitle->userCanEdit() ) {
3240 $showEditLink = 0;
3241 } else {
3242 $showEditLink = $this->mOptions->getEditSection();
3243 }
3244
3245 # Inhibit editsection links if requested in the page
3246 $esw =& MagicWord::get( MAG_NOEDITSECTION );
3247 if( $esw->matchAndRemove( $text ) ) {
3248 $showEditLink = 0;
3249 }
3250
3251 # Get all headlines for numbering them and adding funky stuff like [edit]
3252 # links - this is for later, but we need the number of headlines right now
3253 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3254
3255 # if there are fewer than 4 headlines in the article, do not show TOC
3256 # unless it's been explicitly enabled.
3257 $enoughToc = $this->mShowToc &&
3258 (($numMatches >= 4) || $this->mForceTocPosition);
3259
3260 # Allow user to stipulate that a page should have a "new section"
3261 # link added via __NEWSECTIONLINK__
3262 $mw =& MagicWord::get( MAG_NEWSECTIONLINK );
3263 if( $mw->matchAndRemove( $text ) )
3264 $this->mOutput->setNewSection( true );
3265
3266 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3267 # override above conditions and always show TOC above first header
3268 $mw =& MagicWord::get( MAG_FORCETOC );
3269 if ($mw->matchAndRemove( $text ) ) {
3270 $this->mShowToc = true;
3271 $enoughToc = true;
3272 }
3273
3274 # Never ever show TOC if no headers
3275 if( $numMatches < 1 ) {
3276 $enoughToc = false;
3277 }
3278
3279 # We need this to perform operations on the HTML
3280 $sk =& $this->mOptions->getSkin();
3281
3282 # headline counter
3283 $headlineCount = 0;
3284 $sectionCount = 0; # headlineCount excluding template sections
3285
3286 # Ugh .. the TOC should have neat indentation levels which can be
3287 # passed to the skin functions. These are determined here
3288 $toc = '';
3289 $full = '';
3290 $head = array();
3291 $sublevelCount = array();
3292 $levelCount = array();
3293 $toclevel = 0;
3294 $level = 0;
3295 $prevlevel = 0;
3296 $toclevel = 0;
3297 $prevtoclevel = 0;
3298
3299 foreach( $matches[3] as $headline ) {
3300 $istemplate = 0;
3301 $templatetitle = '';
3302 $templatesection = 0;
3303 $numbering = '';
3304
3305 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3306 $istemplate = 1;
3307 $templatetitle = base64_decode($mat[1]);
3308 $templatesection = 1 + (int)base64_decode($mat[2]);
3309 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3310 }
3311
3312 if( $toclevel ) {
3313 $prevlevel = $level;
3314 $prevtoclevel = $toclevel;
3315 }
3316 $level = $matches[1][$headlineCount];
3317
3318 if( $doNumberHeadings || $enoughToc ) {
3319
3320 if ( $level > $prevlevel ) {
3321 # Increase TOC level
3322 $toclevel++;
3323 $sublevelCount[$toclevel] = 0;
3324 if( $toclevel<$wgMaxTocLevel ) {
3325 $toc .= $sk->tocIndent();
3326 }
3327 }
3328 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3329 # Decrease TOC level, find level to jump to
3330
3331 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3332 # Can only go down to level 1
3333 $toclevel = 1;
3334 } else {
3335 for ($i = $toclevel; $i > 0; $i--) {
3336 if ( $levelCount[$i] == $level ) {
3337 # Found last matching level
3338 $toclevel = $i;
3339 break;
3340 }
3341 elseif ( $levelCount[$i] < $level ) {
3342 # Found first matching level below current level
3343 $toclevel = $i + 1;
3344 break;
3345 }
3346 }
3347 }
3348 if( $toclevel<$wgMaxTocLevel ) {
3349 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3350 }
3351 }
3352 else {
3353 # No change in level, end TOC line
3354 if( $toclevel<$wgMaxTocLevel ) {
3355 $toc .= $sk->tocLineEnd();
3356 }
3357 }
3358
3359 $levelCount[$toclevel] = $level;
3360
3361 # count number of headlines for each level
3362 @$sublevelCount[$toclevel]++;
3363 $dot = 0;
3364 for( $i = 1; $i <= $toclevel; $i++ ) {
3365 if( !empty( $sublevelCount[$i] ) ) {
3366 if( $dot ) {
3367 $numbering .= '.';
3368 }
3369 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3370 $dot = 1;
3371 }
3372 }
3373 }
3374
3375 # The canonized header is a version of the header text safe to use for links
3376 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3377 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
3378 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
3379
3380 # Remove link placeholders by the link text.
3381 # <!--LINK number-->
3382 # turns into
3383 # link text with suffix
3384 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3385 "\$this->mLinkHolders['texts'][\$1]",
3386 $canonized_headline );
3387 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3388 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3389 $canonized_headline );
3390
3391 # strip out HTML
3392 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3393 $tocline = trim( $canonized_headline );
3394 # Save headline for section edit hint before it's escaped
3395 $headline_hint = trim( $canonized_headline );
3396 $canonized_headline = Sanitizer::escapeId( $tocline );
3397 $refers[$headlineCount] = $canonized_headline;
3398
3399 # count how many in assoc. array so we can track dupes in anchors
3400 @$refers[$canonized_headline]++;
3401 $refcount[$headlineCount]=$refers[$canonized_headline];
3402
3403 # Don't number the heading if it is the only one (looks silly)
3404 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3405 # the two are different if the line contains a link
3406 $headline=$numbering . ' ' . $headline;
3407 }
3408
3409 # Create the anchor for linking from the TOC to the section
3410 $anchor = $canonized_headline;
3411 if($refcount[$headlineCount] > 1 ) {
3412 $anchor .= '_' . $refcount[$headlineCount];
3413 }
3414 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3415 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3416 }
3417 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3418 if ( empty( $head[$headlineCount] ) ) {
3419 $head[$headlineCount] = '';
3420 }
3421 if( $istemplate )
3422 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3423 else
3424 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3425 }
3426
3427 # give headline the correct <h#> tag
3428 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3429
3430 $headlineCount++;
3431 if( !$istemplate )
3432 $sectionCount++;
3433 }
3434
3435 if( $enoughToc ) {
3436 if( $toclevel<$wgMaxTocLevel ) {
3437 $toc .= $sk->tocUnindent( $toclevel - 1 );
3438 }
3439 $toc = $sk->tocList( $toc );
3440 }
3441
3442 # split up and insert constructed headlines
3443
3444 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3445 $i = 0;
3446
3447 foreach( $blocks as $block ) {
3448 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3449 # This is the [edit] link that appears for the top block of text when
3450 # section editing is enabled
3451
3452 # Disabled because it broke block formatting
3453 # For example, a bullet point in the top line
3454 # $full .= $sk->editSectionLink(0);
3455 }
3456 $full .= $block;
3457 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3458 # Top anchor now in skin
3459 $full = $full.$toc;
3460 }
3461
3462 if( !empty( $head[$i] ) ) {
3463 $full .= $head[$i];
3464 }
3465 $i++;
3466 }
3467 if( $this->mForceTocPosition ) {
3468 return str_replace( '<!--MWTOC-->', $toc, $full );
3469 } else {
3470 return $full;
3471 }
3472 }
3473
3474 /**
3475 * Return an HTML link for the "ISBN 123456" text
3476 * @private
3477 */
3478 function magicISBN( $text ) {
3479 $fname = 'Parser::magicISBN';
3480 wfProfileIn( $fname );
3481
3482 $a = split( 'ISBN ', ' '.$text );
3483 if ( count ( $a ) < 2 ) {
3484 wfProfileOut( $fname );
3485 return $text;
3486 }
3487 $text = substr( array_shift( $a ), 1);
3488 $valid = '0123456789-Xx';
3489
3490 foreach ( $a as $x ) {
3491 # hack: don't replace inside thumbnail title/alt
3492 # attributes
3493 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3494 $text .= "ISBN $x";
3495 continue;
3496 }
3497
3498 $isbn = $blank = '' ;
3499 while ( ' ' == $x{0} ) {
3500 $blank .= ' ';
3501 $x = substr( $x, 1 );
3502 }
3503 if ( $x == '' ) { # blank isbn
3504 $text .= "ISBN $blank";
3505 continue;
3506 }
3507 while ( strstr( $valid, $x{0} ) != false ) {
3508 $isbn .= $x{0};
3509 $x = substr( $x, 1 );
3510 }
3511 $num = str_replace( '-', '', $isbn );
3512 $num = str_replace( ' ', '', $num );
3513 $num = str_replace( 'x', 'X', $num );
3514
3515 if ( '' == $num ) {
3516 $text .= "ISBN $blank$x";
3517 } else {
3518 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
3519 $text .= '<a href="' .
3520 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3521 "\" class=\"internal\">ISBN $isbn</a>";
3522 $text .= $x;
3523 }
3524 }
3525 wfProfileOut( $fname );
3526 return $text;
3527 }
3528
3529 /**
3530 * Return an HTML link for the "RFC 1234" text
3531 *
3532 * @private
3533 * @param string $text Text to be processed
3534 * @param string $keyword Magic keyword to use (default RFC)
3535 * @param string $urlmsg Interface message to use (default rfcurl)
3536 * @return string
3537 */
3538 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3539
3540 $valid = '0123456789';
3541 $internal = false;
3542
3543 $a = split( $keyword, ' '.$text );
3544 if ( count ( $a ) < 2 ) {
3545 return $text;
3546 }
3547 $text = substr( array_shift( $a ), 1);
3548
3549 /* Check if keyword is preceed by [[.
3550 * This test is made here cause of the array_shift above
3551 * that prevent the test to be done in the foreach.
3552 */
3553 if ( substr( $text, -2 ) == '[[' ) {
3554 $internal = true;
3555 }
3556
3557 foreach ( $a as $x ) {
3558 /* token might be empty if we have RFC RFC 1234 */
3559 if ( $x=='' ) {
3560 $text.=$keyword;
3561 continue;
3562 }
3563
3564 # hack: don't replace inside thumbnail title/alt
3565 # attributes
3566 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3567 $text .= $keyword . $x;
3568 continue;
3569 }
3570
3571 $id = $blank = '' ;
3572
3573 /** remove and save whitespaces in $blank */
3574 while ( $x{0} == ' ' ) {
3575 $blank .= ' ';
3576 $x = substr( $x, 1 );
3577 }
3578
3579 /** remove and save the rfc number in $id */
3580 while ( strstr( $valid, $x{0} ) != false ) {
3581 $id .= $x{0};
3582 $x = substr( $x, 1 );
3583 }
3584
3585 if ( $id == '' ) {
3586 /* call back stripped spaces*/
3587 $text .= $keyword.$blank.$x;
3588 } elseif( $internal ) {
3589 /* normal link */
3590 $text .= $keyword.$id.$x;
3591 } else {
3592 /* build the external link*/
3593 $url = wfMsg( $urlmsg, $id);
3594 $sk =& $this->mOptions->getSkin();
3595 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3596 $text .= "<a href=\"{$url}\"{$la}>{$keyword}{$id}</a>{$x}";
3597 }
3598
3599 /* Check if the next RFC keyword is preceed by [[ */
3600 $internal = ( substr($x,-2) == '[[' );
3601 }
3602 return $text;
3603 }
3604
3605 /**
3606 * Transform wiki markup when saving a page by doing \r\n -> \n
3607 * conversion, substitting signatures, {{subst:}} templates, etc.
3608 *
3609 * @param string $text the text to transform
3610 * @param Title &$title the Title object for the current article
3611 * @param User &$user the User object describing the current user
3612 * @param ParserOptions $options parsing options
3613 * @param bool $clearState whether to clear the parser state first
3614 * @return string the altered wiki markup
3615 * @public
3616 */
3617 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3618 $this->mOptions = $options;
3619 $this->mTitle =& $title;
3620 $this->mOutputType = OT_WIKI;
3621
3622 if ( $clearState ) {
3623 $this->clearState();
3624 }
3625
3626 $stripState = false;
3627 $pairs = array(
3628 "\r\n" => "\n",
3629 );
3630 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3631 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3632 $text = $this->pstPass2( $text, $stripState, $user );
3633 $text = $this->unstrip( $text, $stripState );
3634 $text = $this->unstripNoWiki( $text, $stripState );
3635 return $text;
3636 }
3637
3638 /**
3639 * Pre-save transform helper function
3640 * @private
3641 */
3642 function pstPass2( $text, &$stripState, &$user ) {
3643 global $wgContLang, $wgLocaltimezone;
3644
3645 /* Note: This is the timestamp saved as hardcoded wikitext to
3646 * the database, we use $wgContLang here in order to give
3647 * everyone the same signature and use the default one rather
3648 * than the one selected in each user's preferences.
3649 */
3650 if ( isset( $wgLocaltimezone ) ) {
3651 $oldtz = getenv( 'TZ' );
3652 putenv( 'TZ='.$wgLocaltimezone );
3653 }
3654 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3655 ' (' . date( 'T' ) . ')';
3656 if ( isset( $wgLocaltimezone ) ) {
3657 putenv( 'TZ='.$oldtz );
3658 }
3659
3660 # Variable replacement
3661 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3662 $text = $this->replaceVariables( $text );
3663
3664 # Strip out <nowiki> etc. added via replaceVariables
3665 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3666
3667 # Signatures
3668 $sigText = $this->getUserSig( $user );
3669 $text = strtr( $text, array(
3670 '~~~~~' => $d,
3671 '~~~~' => "$sigText $d",
3672 '~~~' => $sigText
3673 ) );
3674
3675 # Context links: [[|name]] and [[name (context)|]]
3676 #
3677 global $wgLegalTitleChars;
3678 $tc = "[$wgLegalTitleChars]";
3679 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3680
3681 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3682 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3683
3684 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3685 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3686 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3687 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3688 $context = '';
3689 $t = $this->mTitle->getText();
3690 if ( preg_match( $conpat, $t, $m ) ) {
3691 $context = $m[2];
3692 }
3693 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3694 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3695 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3696
3697 if ( '' == $context ) {
3698 $text = preg_replace( $p2, '[[\\1]]', $text );
3699 } else {
3700 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3701 }
3702
3703 # Trim trailing whitespace
3704 # MAG_END (__END__) tag allows for trailing
3705 # whitespace to be deliberately included
3706 $text = rtrim( $text );
3707 $mw =& MagicWord::get( MAG_END );
3708 $mw->matchAndRemove( $text );
3709
3710 return $text;
3711 }
3712
3713 /**
3714 * Fetch the user's signature text, if any, and normalize to
3715 * validated, ready-to-insert wikitext.
3716 *
3717 * @param User $user
3718 * @return string
3719 * @private
3720 */
3721 function getUserSig( &$user ) {
3722 $username = $user->getName();
3723 $nickname = $user->getOption( 'nickname' );
3724 $nickname = $nickname === '' ? $username : $nickname;
3725
3726 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3727 # Sig. might contain markup; validate this
3728 if( $this->validateSig( $nickname ) !== false ) {
3729 # Validated; clean up (if needed) and return it
3730 return $this->cleanSig( $nickname, true );
3731 } else {
3732 # Failed to validate; fall back to the default
3733 $nickname = $username;
3734 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3735 }
3736 }
3737
3738 # If we're still here, make it a link to the user page
3739 $userpage = $user->getUserPage();
3740 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3741 }
3742
3743 /**
3744 * Check that the user's signature contains no bad XML
3745 *
3746 * @param string $text
3747 * @return mixed An expanded string, or false if invalid.
3748 */
3749 function validateSig( $text ) {
3750 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3751 }
3752
3753 /**
3754 * Clean up signature text
3755 *
3756 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3757 * 2) Substitute all transclusions
3758 *
3759 * @param string $text
3760 * @param $parsing Whether we're cleaning (preferences save) or parsing
3761 * @return string Signature text
3762 */
3763 function cleanSig( $text, $parsing = false ) {
3764 global $wgTitle;
3765 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI : OT_MSG );
3766
3767 $substWord = MagicWord::get( MAG_SUBST );
3768 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3769 $substText = '{{' . $substWord->getSynonym( 0 );
3770
3771 $text = preg_replace( $substRegex, $substText, $text );
3772 $text = preg_replace( '/~{3,5}/', '', $text );
3773 $text = $this->replaceVariables( $text );
3774
3775 $this->clearState();
3776 return $text;
3777 }
3778
3779 /**
3780 * Set up some variables which are usually set up in parse()
3781 * so that an external function can call some class members with confidence
3782 * @public
3783 */
3784 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3785 $this->mTitle =& $title;
3786 $this->mOptions = $options;
3787 $this->mOutputType = $outputType;
3788 if ( $clearState ) {
3789 $this->clearState();
3790 }
3791 }
3792
3793 /**
3794 * Transform a MediaWiki message by replacing magic variables.
3795 *
3796 * @param string $text the text to transform
3797 * @param ParserOptions $options options
3798 * @return string the text with variables substituted
3799 * @public
3800 */
3801 function transformMsg( $text, $options ) {
3802 global $wgTitle;
3803 static $executing = false;
3804
3805 $fname = "Parser::transformMsg";
3806
3807 # Guard against infinite recursion
3808 if ( $executing ) {
3809 return $text;
3810 }
3811 $executing = true;
3812
3813 wfProfileIn($fname);
3814
3815 $this->mTitle = $wgTitle;
3816 $this->mOptions = $options;
3817 $this->mOutputType = OT_MSG;
3818 $this->clearState();
3819 $text = $this->replaceVariables( $text );
3820
3821 $executing = false;
3822 wfProfileOut($fname);
3823 return $text;
3824 }
3825
3826 /**
3827 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3828 * The callback should have the following form:
3829 * function myParserHook( $text, $params, &$parser ) { ... }
3830 *
3831 * Transform and return $text. Use $parser for any required context, e.g. use
3832 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3833 *
3834 * @public
3835 *
3836 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3837 * @param mixed $callback The callback function (and object) to use for the tag
3838 *
3839 * @return The old value of the mTagHooks array associated with the hook
3840 */
3841 function setHook( $tag, $callback ) {
3842 $tag = strtolower( $tag );
3843 $oldVal = @$this->mTagHooks[$tag];
3844 $this->mTagHooks[$tag] = $callback;
3845
3846 return $oldVal;
3847 }
3848
3849 /**
3850 * Create a function, e.g. {{sum:1|2|3}}
3851 * The callback function should have the form:
3852 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3853 *
3854 * The callback may either return the text result of the function, or an array with the text
3855 * in element 0, and a number of flags in the other elements. The names of the flags are
3856 * specified in the keys. Valid flags are:
3857 * found The text returned is valid, stop processing the template. This
3858 * is on by default.
3859 * nowiki Wiki markup in the return value should be escaped
3860 * noparse Unsafe HTML tags should not be stripped, etc.
3861 * noargs Don't replace triple-brace arguments in the return value
3862 * isHTML The returned text is HTML, armour it against wikitext transformation
3863 *
3864 * @public
3865 *
3866 * @param string $name The function name. Function names are case-insensitive.
3867 * @param mixed $callback The callback function (and object) to use
3868 *
3869 * @return The old callback function for this name, if any
3870 */
3871 function setFunctionHook( $name, $callback ) {
3872 $name = strtolower( $name );
3873 $oldVal = @$this->mFunctionHooks[$name];
3874 $this->mFunctionHooks[$name] = $callback;
3875 return $oldVal;
3876 }
3877
3878 /**
3879 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3880 * Placeholders created in Skin::makeLinkObj()
3881 * Returns an array of links found, indexed by PDBK:
3882 * 0 - broken
3883 * 1 - normal link
3884 * 2 - stub
3885 * $options is a bit field, RLH_FOR_UPDATE to select for update
3886 */
3887 function replaceLinkHolders( &$text, $options = 0 ) {
3888 global $wgUser;
3889 global $wgOutputReplace;
3890
3891 $fname = 'Parser::replaceLinkHolders';
3892 wfProfileIn( $fname );
3893
3894 $pdbks = array();
3895 $colours = array();
3896 $sk =& $this->mOptions->getSkin();
3897 $linkCache =& LinkCache::singleton();
3898
3899 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3900 wfProfileIn( $fname.'-check' );
3901 $dbr =& wfGetDB( DB_SLAVE );
3902 $page = $dbr->tableName( 'page' );
3903 $threshold = $wgUser->getOption('stubthreshold');
3904
3905 # Sort by namespace
3906 asort( $this->mLinkHolders['namespaces'] );
3907
3908 # Generate query
3909 $query = false;
3910 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3911 # Make title object
3912 $title = $this->mLinkHolders['titles'][$key];
3913
3914 # Skip invalid entries.
3915 # Result will be ugly, but prevents crash.
3916 if ( is_null( $title ) ) {
3917 continue;
3918 }
3919 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3920
3921 # Check if it's a static known link, e.g. interwiki
3922 if ( $title->isAlwaysKnown() ) {
3923 $colours[$pdbk] = 1;
3924 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3925 $colours[$pdbk] = 1;
3926 $this->mOutput->addLink( $title, $id );
3927 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3928 $colours[$pdbk] = 0;
3929 } else {
3930 # Not in the link cache, add it to the query
3931 if ( !isset( $current ) ) {
3932 $current = $ns;
3933 $query = "SELECT page_id, page_namespace, page_title";
3934 if ( $threshold > 0 ) {
3935 $query .= ', page_len, page_is_redirect';
3936 }
3937 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3938 } elseif ( $current != $ns ) {
3939 $current = $ns;
3940 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3941 } else {
3942 $query .= ', ';
3943 }
3944
3945 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3946 }
3947 }
3948 if ( $query ) {
3949 $query .= '))';
3950 if ( $options & RLH_FOR_UPDATE ) {
3951 $query .= ' FOR UPDATE';
3952 }
3953
3954 $res = $dbr->query( $query, $fname );
3955
3956 # Fetch data and form into an associative array
3957 # non-existent = broken
3958 # 1 = known
3959 # 2 = stub
3960 while ( $s = $dbr->fetchObject($res) ) {
3961 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3962 $pdbk = $title->getPrefixedDBkey();
3963 $linkCache->addGoodLinkObj( $s->page_id, $title );
3964 $this->mOutput->addLink( $title, $s->page_id );
3965
3966 if ( $threshold > 0 ) {
3967 $size = $s->page_len;
3968 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3969 $colours[$pdbk] = 1;
3970 } else {
3971 $colours[$pdbk] = 2;
3972 }
3973 } else {
3974 $colours[$pdbk] = 1;
3975 }
3976 }
3977 }
3978 wfProfileOut( $fname.'-check' );
3979
3980 # Construct search and replace arrays
3981 wfProfileIn( $fname.'-construct' );
3982 $wgOutputReplace = array();
3983 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3984 $pdbk = $pdbks[$key];
3985 $searchkey = "<!--LINK $key-->";
3986 $title = $this->mLinkHolders['titles'][$key];
3987 if ( empty( $colours[$pdbk] ) ) {
3988 $linkCache->addBadLinkObj( $title );
3989 $colours[$pdbk] = 0;
3990 $this->mOutput->addLink( $title, 0 );
3991 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3992 $this->mLinkHolders['texts'][$key],
3993 $this->mLinkHolders['queries'][$key] );
3994 } elseif ( $colours[$pdbk] == 1 ) {
3995 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3996 $this->mLinkHolders['texts'][$key],
3997 $this->mLinkHolders['queries'][$key] );
3998 } elseif ( $colours[$pdbk] == 2 ) {
3999 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4000 $this->mLinkHolders['texts'][$key],
4001 $this->mLinkHolders['queries'][$key] );
4002 }
4003 }
4004 wfProfileOut( $fname.'-construct' );
4005
4006 # Do the thing
4007 wfProfileIn( $fname.'-replace' );
4008
4009 $text = preg_replace_callback(
4010 '/(<!--LINK .*?-->)/',
4011 "wfOutputReplaceMatches",
4012 $text);
4013
4014 wfProfileOut( $fname.'-replace' );
4015 }
4016
4017 # Now process interwiki link holders
4018 # This is quite a bit simpler than internal links
4019 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4020 wfProfileIn( $fname.'-interwiki' );
4021 # Make interwiki link HTML
4022 $wgOutputReplace = array();
4023 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4024 $title = $this->mInterwikiLinkHolders['titles'][$key];
4025 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4026 }
4027
4028 $text = preg_replace_callback(
4029 '/<!--IWLINK (.*?)-->/',
4030 "wfOutputReplaceMatches",
4031 $text );
4032 wfProfileOut( $fname.'-interwiki' );
4033 }
4034
4035 wfProfileOut( $fname );
4036 return $colours;
4037 }
4038
4039 /**
4040 * Replace <!--LINK--> link placeholders with plain text of links
4041 * (not HTML-formatted).
4042 * @param string $text
4043 * @return string
4044 */
4045 function replaceLinkHoldersText( $text ) {
4046 $fname = 'Parser::replaceLinkHoldersText';
4047 wfProfileIn( $fname );
4048
4049 $text = preg_replace_callback(
4050 '/<!--(LINK|IWLINK) (.*?)-->/',
4051 array( &$this, 'replaceLinkHoldersTextCallback' ),
4052 $text );
4053
4054 wfProfileOut( $fname );
4055 return $text;
4056 }
4057
4058 /**
4059 * @param array $matches
4060 * @return string
4061 * @private
4062 */
4063 function replaceLinkHoldersTextCallback( $matches ) {
4064 $type = $matches[1];
4065 $key = $matches[2];
4066 if( $type == 'LINK' ) {
4067 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4068 return $this->mLinkHolders['texts'][$key];
4069 }
4070 } elseif( $type == 'IWLINK' ) {
4071 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4072 return $this->mInterwikiLinkHolders['texts'][$key];
4073 }
4074 }
4075 return $matches[0];
4076 }
4077
4078 /**
4079 * Tag hook handler for 'pre'.
4080 */
4081 function renderPreTag( $text, $attribs, $parser ) {
4082 // Backwards-compatibility hack
4083 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4084
4085 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4086 return wfOpenElement( 'pre', $attribs ) .
4087 wfEscapeHTMLTagsOnly( $content ) .
4088 '</pre>';
4089 }
4090
4091 /**
4092 * Renders an image gallery from a text with one line per image.
4093 * text labels may be given by using |-style alternative text. E.g.
4094 * Image:one.jpg|The number "1"
4095 * Image:tree.jpg|A tree
4096 * given as text will return the HTML of a gallery with two images,
4097 * labeled 'The number "1"' and
4098 * 'A tree'.
4099 */
4100 function renderImageGallery( $text ) {
4101 $ig = new ImageGallery();
4102 $ig->setShowBytes( false );
4103 $ig->setShowFilename( false );
4104 $ig->setParsing();
4105 $lines = explode( "\n", $text );
4106
4107 foreach ( $lines as $line ) {
4108 # match lines like these:
4109 # Image:someimage.jpg|This is some image
4110 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4111 # Skip empty lines
4112 if ( count( $matches ) == 0 ) {
4113 continue;
4114 }
4115 $nt =& Title::newFromText( $matches[1] );
4116 if( is_null( $nt ) ) {
4117 # Bogus title. Ignore these so we don't bomb out later.
4118 continue;
4119 }
4120 if ( isset( $matches[3] ) ) {
4121 $label = $matches[3];
4122 } else {
4123 $label = '';
4124 }
4125
4126 $pout = $this->parse( $label,
4127 $this->mTitle,
4128 $this->mOptions,
4129 false, // Strip whitespace...?
4130 false // Don't clear state!
4131 );
4132 $html = $pout->getText();
4133
4134 $ig->add( new Image( $nt ), $html );
4135
4136 # Only add real images (bug #5586)
4137 if ( $nt->getNamespace() == NS_IMAGE ) {
4138 $this->mOutput->addImage( $nt->getDBkey() );
4139 }
4140 }
4141 return $ig->toHTML();
4142 }
4143
4144 /**
4145 * Parse image options text and use it to make an image
4146 */
4147 function makeImage( &$nt, $options ) {
4148 global $wgUseImageResize;
4149
4150 $align = '';
4151
4152 # Check if the options text is of the form "options|alt text"
4153 # Options are:
4154 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4155 # * left no resizing, just left align. label is used for alt= only
4156 # * right same, but right aligned
4157 # * none same, but not aligned
4158 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4159 # * center center the image
4160 # * framed Keep original image size, no magnify-button.
4161
4162 $part = explode( '|', $options);
4163
4164 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
4165 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
4166 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
4167 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
4168 $mwNone =& MagicWord::get( MAG_IMG_NONE );
4169 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
4170 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
4171 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
4172 $caption = '';
4173
4174 $width = $height = $framed = $thumb = false;
4175 $manual_thumb = '' ;
4176
4177 foreach( $part as $key => $val ) {
4178 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4179 $thumb=true;
4180 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4181 # use manually specified thumbnail
4182 $thumb=true;
4183 $manual_thumb = $match;
4184 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4185 # remember to set an alignment, don't render immediately
4186 $align = 'right';
4187 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4188 # remember to set an alignment, don't render immediately
4189 $align = 'left';
4190 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4191 # remember to set an alignment, don't render immediately
4192 $align = 'center';
4193 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4194 # remember to set an alignment, don't render immediately
4195 $align = 'none';
4196 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4197 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4198 # $match is the image width in pixels
4199 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4200 $width = intval( $m[1] );
4201 $height = intval( $m[2] );
4202 } else {
4203 $width = intval($match);
4204 }
4205 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4206 $framed=true;
4207 } else {
4208 $caption = $val;
4209 }
4210 }
4211 # Strip bad stuff out of the alt text
4212 $alt = $this->replaceLinkHoldersText( $caption );
4213
4214 # make sure there are no placeholders in thumbnail attributes
4215 # that are later expanded to html- so expand them now and
4216 # remove the tags
4217 $alt = $this->unstrip($alt, $this->mStripState);
4218 $alt = Sanitizer::stripAllTags( $alt );
4219
4220 # Linker does the rest
4221 $sk =& $this->mOptions->getSkin();
4222 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4223 }
4224
4225 /**
4226 * Set a flag in the output object indicating that the content is dynamic and
4227 * shouldn't be cached.
4228 */
4229 function disableCache() {
4230 wfDebug( "Parser output marked as uncacheable.\n" );
4231 $this->mOutput->mCacheTime = -1;
4232 }
4233
4234 /**#@+
4235 * Callback from the Sanitizer for expanding items found in HTML attribute
4236 * values, so they can be safely tested and escaped.
4237 * @param string $text
4238 * @param array $args
4239 * @return string
4240 * @private
4241 */
4242 function attributeStripCallback( &$text, $args ) {
4243 $text = $this->replaceVariables( $text, $args );
4244 $text = $this->unstripForHTML( $text );
4245 return $text;
4246 }
4247
4248 function unstripForHTML( $text ) {
4249 $text = $this->unstrip( $text, $this->mStripState );
4250 $text = $this->unstripNoWiki( $text, $this->mStripState );
4251 return $text;
4252 }
4253 /**#@-*/
4254
4255 /**#@+
4256 * Accessor/mutator
4257 */
4258 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4259 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4260 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4261 /**#@-*/
4262
4263 /**#@+
4264 * Accessor
4265 */
4266 function getTags() { return array_keys( $this->mTagHooks ); }
4267 /**#@-*/
4268
4269
4270 /**
4271 * Break wikitext input into sections, and either pull or replace
4272 * some particular section's text.
4273 *
4274 * External callers should use the getSection and replaceSection methods.
4275 *
4276 * @param $text Page wikitext
4277 * @param $section Numbered section. 0 pulls the text before the first
4278 * heading; other numbers will pull the given section
4279 * along with its lower-level subsections.
4280 * @param $mode One of "get" or "replace"
4281 * @param $newtext Replacement text for section data.
4282 * @return string for "get", the extracted section text.
4283 * for "replace", the whole page with the section replaced.
4284 */
4285 private function extractSections( $text, $section, $mode, $newtext='' ) {
4286 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4287 # comments to be stripped as well)
4288 $striparray = array();
4289
4290 $oldOutputType = $this->mOutputType;
4291 $oldOptions = $this->mOptions;
4292 $this->mOptions = new ParserOptions();
4293 $this->mOutputType = OT_WIKI;
4294
4295 $striptext = $this->strip( $text, $striparray, true );
4296
4297 $this->mOutputType = $oldOutputType;
4298 $this->mOptions = $oldOptions;
4299
4300 # now that we can be sure that no pseudo-sections are in the source,
4301 # split it up by section
4302 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4303 $comment = "(?:$uniq-!--.*?QINU)";
4304 $secs = preg_split(
4305 /*
4306 "/
4307 ^(
4308 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4309 (?:
4310 (=+) # Should this be limited to 6?
4311 .+? # Section title...
4312 \\2 # Ending = count must match start
4313 |
4314 ^
4315 <h([1-6])\b.*?>
4316 .*?
4317 <\/h\\3\s*>
4318 )
4319 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4320 )$
4321 /mix",
4322 */
4323 "/
4324 (
4325 ^
4326 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4327 (=+) # Should this be limited to 6?
4328 .+? # Section title...
4329 \\2 # Ending = count must match start
4330 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4331 $
4332 |
4333 <h([1-6])\b.*?>
4334 .*?
4335 <\/h\\3\s*>
4336 )
4337 /mix",
4338 $striptext, -1,
4339 PREG_SPLIT_DELIM_CAPTURE);
4340
4341 if( $mode == "get" ) {
4342 if( $section == 0 ) {
4343 // "Section 0" returns the content before any other section.
4344 $rv = $secs[0];
4345 } else {
4346 $rv = "";
4347 }
4348 } elseif( $mode == "replace" ) {
4349 if( $section == 0 ) {
4350 $rv = $newtext . "\n\n";
4351 $remainder = true;
4352 } else {
4353 $rv = $secs[0];
4354 $remainder = false;
4355 }
4356 }
4357 $count = 0;
4358 $sectionLevel = 0;
4359 for( $index = 1; $index < count( $secs ); ) {
4360 $headerLine = $secs[$index++];
4361 if( $secs[$index] ) {
4362 // A wiki header
4363 $headerLevel = strlen( $secs[$index++] );
4364 } else {
4365 // An HTML header
4366 $index++;
4367 $headerLevel = intval( $secs[$index++] );
4368 }
4369 $content = $secs[$index++];
4370
4371 $count++;
4372 if( $mode == "get" ) {
4373 if( $count == $section ) {
4374 $rv = $headerLine . $content;
4375 $sectionLevel = $headerLevel;
4376 } elseif( $count > $section ) {
4377 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4378 $rv .= $headerLine . $content;
4379 } else {
4380 // Broke out to a higher-level section
4381 break;
4382 }
4383 }
4384 } elseif( $mode == "replace" ) {
4385 if( $count < $section ) {
4386 $rv .= $headerLine . $content;
4387 } elseif( $count == $section ) {
4388 $rv .= $newtext . "\n\n";
4389 $sectionLevel = $headerLevel;
4390 } elseif( $count > $section ) {
4391 if( $headerLevel <= $sectionLevel ) {
4392 // Passed the section's sub-parts.
4393 $remainder = true;
4394 }
4395 if( $remainder ) {
4396 $rv .= $headerLine . $content;
4397 }
4398 }
4399 }
4400 }
4401 # reinsert stripped tags
4402 $rv = $this->unstrip( $rv, $striparray );
4403 $rv = $this->unstripNoWiki( $rv, $striparray );
4404 $rv = trim( $rv );
4405 return $rv;
4406 }
4407
4408 /**
4409 * This function returns the text of a section, specified by a number ($section).
4410 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4411 * the first section before any such heading (section 0).
4412 *
4413 * If a section contains subsections, these are also returned.
4414 *
4415 * @param $text String: text to look in
4416 * @param $section Integer: section number
4417 * @return string text of the requested section
4418 */
4419 function getSection( $text, $section ) {
4420 return $this->extractSections( $text, $section, "get" );
4421 }
4422
4423 function replaceSection( $oldtext, $section, $text ) {
4424 return $this->extractSections( $oldtext, $section, "replace", $text );
4425 }
4426
4427 }
4428
4429 /**
4430 * @todo document
4431 * @package MediaWiki
4432 */
4433 class ParserOutput
4434 {
4435 var $mText, # The output text
4436 $mLanguageLinks, # List of the full text of language links, in the order they appear
4437 $mCategories, # Map of category names to sort keys
4438 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4439 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4440 $mVersion, # Compatibility check
4441 $mTitleText, # title text of the chosen language variant
4442 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4443 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4444 $mImages, # DB keys of the images used, in the array key only
4445 $mExternalLinks, # External link URLs, in the key only
4446 $mHTMLtitle, # Display HTML title
4447 $mSubtitle, # Additional subtitle
4448 $mNewSection, # Show a new section link?
4449 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4450
4451 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4452 $containsOldMagic = false, $titletext = '' )
4453 {
4454 $this->mText = $text;
4455 $this->mLanguageLinks = $languageLinks;
4456 $this->mCategories = $categoryLinks;
4457 $this->mContainsOldMagic = $containsOldMagic;
4458 $this->mCacheTime = '';
4459 $this->mVersion = MW_PARSER_VERSION;
4460 $this->mTitleText = $titletext;
4461 $this->mLinks = array();
4462 $this->mTemplates = array();
4463 $this->mImages = array();
4464 $this->mExternalLinks = array();
4465 $this->mHTMLtitle = "" ;
4466 $this->mSubtitle = "" ;
4467 $this->mNewSection = false;
4468 $this->mNoGallery = false;
4469 }
4470
4471 function getText() { return $this->mText; }
4472 function &getLanguageLinks() { return $this->mLanguageLinks; }
4473 function getCategoryLinks() { return array_keys( $this->mCategories ); }
4474 function &getCategories() { return $this->mCategories; }
4475 function getCacheTime() { return $this->mCacheTime; }
4476 function getTitleText() { return $this->mTitleText; }
4477 function &getLinks() { return $this->mLinks; }
4478 function &getTemplates() { return $this->mTemplates; }
4479 function &getImages() { return $this->mImages; }
4480 function &getExternalLinks() { return $this->mExternalLinks; }
4481 function getNoGallery() { return $this->mNoGallery; }
4482
4483 function containsOldMagic() { return $this->mContainsOldMagic; }
4484 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
4485 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
4486 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
4487 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
4488 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
4489 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
4490
4491 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
4492 function addImage( $name ) { $this->mImages[$name] = 1; }
4493 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
4494 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
4495
4496 function setNewSection( $value ) {
4497 $this->mNewSection = (bool)$value;
4498 }
4499 function getNewSection() {
4500 return (bool)$this->mNewSection;
4501 }
4502
4503 function addLink( $title, $id ) {
4504 $ns = $title->getNamespace();
4505 $dbk = $title->getDBkey();
4506 if ( !isset( $this->mLinks[$ns] ) ) {
4507 $this->mLinks[$ns] = array();
4508 }
4509 $this->mLinks[$ns][$dbk] = $id;
4510 }
4511
4512 function addTemplate( $title, $id ) {
4513 $ns = $title->getNamespace();
4514 $dbk = $title->getDBkey();
4515 if ( !isset( $this->mTemplates[$ns] ) ) {
4516 $this->mTemplates[$ns] = array();
4517 }
4518 $this->mTemplates[$ns][$dbk] = $id;
4519 }
4520
4521 /**
4522 * Return true if this cached output object predates the global or
4523 * per-article cache invalidation timestamps, or if it comes from
4524 * an incompatible older version.
4525 *
4526 * @param string $touched the affected article's last touched timestamp
4527 * @return bool
4528 * @public
4529 */
4530 function expired( $touched ) {
4531 global $wgCacheEpoch;
4532 return $this->getCacheTime() == -1 || // parser says it's uncacheable
4533 $this->getCacheTime() < $touched ||
4534 $this->getCacheTime() <= $wgCacheEpoch ||
4535 !isset( $this->mVersion ) ||
4536 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
4537 }
4538 }
4539
4540 /**
4541 * Set options of the Parser
4542 * @todo document
4543 * @package MediaWiki
4544 */
4545 class ParserOptions
4546 {
4547 # All variables are private
4548 var $mUseTeX; # Use texvc to expand <math> tags
4549 var $mUseDynamicDates; # Use DateFormatter to format dates
4550 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4551 var $mAllowExternalImages; # Allow external images inline
4552 var $mAllowExternalImagesFrom; # If not, any exception?
4553 var $mSkin; # Reference to the preferred skin
4554 var $mDateFormat; # Date format index
4555 var $mEditSection; # Create "edit section" links
4556 var $mNumberHeadings; # Automatically number headings
4557 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4558 var $mTidy; # Ask for tidy cleanup
4559 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4560
4561 function getUseTeX() { return $this->mUseTeX; }
4562 function getUseDynamicDates() { return $this->mUseDynamicDates; }
4563 function getInterwikiMagic() { return $this->mInterwikiMagic; }
4564 function getAllowExternalImages() { return $this->mAllowExternalImages; }
4565 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
4566 function &getSkin() { return $this->mSkin; }
4567 function getDateFormat() { return $this->mDateFormat; }
4568 function getEditSection() { return $this->mEditSection; }
4569 function getNumberHeadings() { return $this->mNumberHeadings; }
4570 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
4571 function getTidy() { return $this->mTidy; }
4572 function getInterfaceMessage() { return $this->mInterfaceMessage; }
4573
4574 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
4575 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
4576 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
4577 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
4578 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
4579 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
4580 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
4581 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
4582 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
4583 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
4584 function setSkin( &$x ) { $this->mSkin =& $x; }
4585 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage, $x); }
4586
4587 function ParserOptions() {
4588 global $wgUser;
4589 $this->initialiseFromUser( $wgUser );
4590 }
4591
4592 /**
4593 * Get parser options
4594 * @static
4595 */
4596 function newFromUser( &$user ) {
4597 $popts = new ParserOptions;
4598 $popts->initialiseFromUser( $user );
4599 return $popts;
4600 }
4601
4602 /** Get user options */
4603 function initialiseFromUser( &$userInput ) {
4604 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4605 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4606 $fname = 'ParserOptions::initialiseFromUser';
4607 wfProfileIn( $fname );
4608 if ( !$userInput ) {
4609 $user = new User;
4610 $user->setLoaded( true );
4611 } else {
4612 $user =& $userInput;
4613 }
4614
4615 $this->mUseTeX = $wgUseTeX;
4616 $this->mUseDynamicDates = $wgUseDynamicDates;
4617 $this->mInterwikiMagic = $wgInterwikiMagic;
4618 $this->mAllowExternalImages = $wgAllowExternalImages;
4619 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
4620 wfProfileIn( $fname.'-skin' );
4621 $this->mSkin =& $user->getSkin();
4622 wfProfileOut( $fname.'-skin' );
4623 $this->mDateFormat = $user->getOption( 'date' );
4624 $this->mEditSection = true;
4625 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4626 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4627 $this->mTidy = false;
4628 $this->mInterfaceMessage = false;
4629 wfProfileOut( $fname );
4630 }
4631 }
4632
4633 /**
4634 * Callback function used by Parser::replaceLinkHolders()
4635 * to substitute link placeholders.
4636 */
4637 function &wfOutputReplaceMatches( $matches ) {
4638 global $wgOutputReplace;
4639 return $wgOutputReplace[$matches[1]];
4640 }
4641
4642 /**
4643 * Return the total number of articles
4644 */
4645 function wfNumberOfArticles() {
4646 global $wgNumberOfArticles;
4647
4648 wfLoadSiteStats();
4649 return $wgNumberOfArticles;
4650 }
4651
4652 /**
4653 * Return the number of files
4654 */
4655 function wfNumberOfFiles() {
4656 $fname = 'wfNumberOfFiles';
4657
4658 wfProfileIn( $fname );
4659 $dbr =& wfGetDB( DB_SLAVE );
4660 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4661 wfProfileOut( $fname );
4662
4663 return $numImages;
4664 }
4665
4666 /**
4667 * Return the number of user accounts
4668 * @return integer
4669 */
4670 function wfNumberOfUsers() {
4671 wfProfileIn( 'wfNumberOfUsers' );
4672 $dbr =& wfGetDB( DB_SLAVE );
4673 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4674 wfProfileOut( 'wfNumberOfUsers' );
4675 return (int)$count;
4676 }
4677
4678 /**
4679 * Return the total number of pages
4680 * @return integer
4681 */
4682 function wfNumberOfPages() {
4683 wfProfileIn( 'wfNumberOfPages' );
4684 $dbr =& wfGetDB( DB_SLAVE );
4685 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4686 wfProfileOut( 'wfNumberOfPages' );
4687 return (int)$count;
4688 }
4689
4690 /**
4691 * Return the total number of admins
4692 *
4693 * @return integer
4694 */
4695 function wfNumberOfAdmins() {
4696 static $admins = -1;
4697 wfProfileIn( 'wfNumberOfAdmins' );
4698 if( $admins == -1 ) {
4699 $dbr =& wfGetDB( DB_SLAVE );
4700 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4701 }
4702 wfProfileOut( 'wfNumberOfAdmins' );
4703 return (int)$admins;
4704 }
4705
4706 /**
4707 * Count the number of pages in a particular namespace
4708 *
4709 * @param $ns Namespace
4710 * @return integer
4711 */
4712 function wfPagesInNs( $ns ) {
4713 static $pageCount = array();
4714 wfProfileIn( 'wfPagesInNs' );
4715 if( !isset( $pageCount[$ns] ) ) {
4716 $dbr =& wfGetDB( DB_SLAVE );
4717 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4718 }
4719 wfProfileOut( 'wfPagesInNs' );
4720 return (int)$pageCount[$ns];
4721 }
4722
4723 /**
4724 * Get various statistics from the database
4725 * @private
4726 */
4727 function wfLoadSiteStats() {
4728 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4729 $fname = 'wfLoadSiteStats';
4730
4731 if ( -1 != $wgNumberOfArticles ) return;
4732 $dbr =& wfGetDB( DB_SLAVE );
4733 $s = $dbr->selectRow( 'site_stats',
4734 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4735 array( 'ss_row_id' => 1 ), $fname
4736 );
4737
4738 if ( $s === false ) {
4739 return;
4740 } else {
4741 $wgTotalViews = $s->ss_total_views;
4742 $wgTotalEdits = $s->ss_total_edits;
4743 $wgNumberOfArticles = $s->ss_good_articles;
4744 }
4745 }
4746
4747 /**
4748 * Escape html tags
4749 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4750 *
4751 * @param $in String: text that might contain HTML tags.
4752 * @return string Escaped string
4753 */
4754 function wfEscapeHTMLTagsOnly( $in ) {
4755 return str_replace(
4756 array( '"', '>', '<' ),
4757 array( '&quot;', '&gt;', '&lt;' ),
4758 $in );
4759 }
4760
4761 ?>