45ef8a14aa023ffd2f569dcb4f259e2da1417cb8
[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 # Escape any control characters introduced by the above step
1150 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1151
1152 # Process the trail (i.e. everything after this link up until start of the next link),
1153 # replacing any non-bracketed links
1154 $trail = $this->replaceFreeExternalLinks( $trail );
1155
1156 # Use the encoded URL
1157 # This means that users can paste URLs directly into the text
1158 # Funny characters like &ouml; aren't valid in URLs anyway
1159 # This was changed in August 2004
1160 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle->getNamespace() ) . $dtrail . $trail;
1161
1162 # Register link in the output object.
1163 # Replace unnecessary URL escape codes with the referenced character
1164 # This prevents spammers from hiding links from the filters
1165 $pasteurized = Parser::replaceUnusualEscapes( $url );
1166 $this->mOutput->addExternalLink( $pasteurized );
1167 }
1168
1169 wfProfileOut( $fname );
1170 return $s;
1171 }
1172
1173 /**
1174 * Replace anything that looks like a URL with a link
1175 * @private
1176 */
1177 function replaceFreeExternalLinks( $text ) {
1178 global $wgContLang;
1179 $fname = 'Parser::replaceFreeExternalLinks';
1180 wfProfileIn( $fname );
1181
1182 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1183 $s = array_shift( $bits );
1184 $i = 0;
1185
1186 $sk =& $this->mOptions->getSkin();
1187
1188 while ( $i < count( $bits ) ){
1189 $protocol = $bits[$i++];
1190 $remainder = $bits[$i++];
1191
1192 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1193 # Found some characters after the protocol that look promising
1194 $url = $protocol . $m[1];
1195 $trail = $m[2];
1196
1197 # special case: handle urls as url args:
1198 # http://www.example.com/foo?=http://www.example.com/bar
1199 if(strlen($trail) == 0 &&
1200 isset($bits[$i]) &&
1201 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1202 preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $bits[$i + 1], $m ))
1203 {
1204 # add protocol, arg
1205 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1206 $i += 2;
1207 $trail = $m[2];
1208 }
1209
1210 # The characters '<' and '>' (which were escaped by
1211 # removeHTMLtags()) should not be included in
1212 # URLs, per RFC 2396.
1213 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1214 $trail = substr($url, $m2[0][1]) . $trail;
1215 $url = substr($url, 0, $m2[0][1]);
1216 }
1217
1218 # Move trailing punctuation to $trail
1219 $sep = ',;\.:!?';
1220 # If there is no left bracket, then consider right brackets fair game too
1221 if ( strpos( $url, '(' ) === false ) {
1222 $sep .= ')';
1223 }
1224
1225 $numSepChars = strspn( strrev( $url ), $sep );
1226 if ( $numSepChars ) {
1227 $trail = substr( $url, -$numSepChars ) . $trail;
1228 $url = substr( $url, 0, -$numSepChars );
1229 }
1230
1231 # Normalize any HTML entities in input. They will be
1232 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1233 $url = Sanitizer::decodeCharReferences( $url );
1234
1235 # Escape any control characters introduced by the above step
1236 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1237
1238 # Is this an external image?
1239 $text = $this->maybeMakeExternalImage( $url );
1240 if ( $text === false ) {
1241 # Not an image, make a link
1242 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle->getNamespace() );
1243 # Register it in the output object...
1244 # Replace unnecessary URL escape codes with their equivalent characters
1245 $pasteurized = Parser::replaceUnusualEscapes( $url );
1246 $this->mOutput->addExternalLink( $pasteurized );
1247 }
1248 $s .= $text . $trail;
1249 } else {
1250 $s .= $protocol . $remainder;
1251 }
1252 }
1253 wfProfileOut( $fname );
1254 return $s;
1255 }
1256
1257 /**
1258 * Replace unusual URL escape codes with their equivalent characters
1259 * @param string
1260 * @return string
1261 * @static
1262 * @fixme This can merge genuinely required bits in the path or query string,
1263 * breaking legit URLs. A proper fix would treat the various parts of
1264 * the URL differently; as a workaround, just use the output for
1265 * statistical records, not for actual linking/output.
1266 */
1267 function replaceUnusualEscapes( $url ) {
1268 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1269 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1270 }
1271
1272 /**
1273 * Callback function used in replaceUnusualEscapes().
1274 * Replaces unusual URL escape codes with their equivalent character
1275 * @static
1276 * @private
1277 */
1278 function replaceUnusualEscapesCallback( $matches ) {
1279 $char = urldecode( $matches[0] );
1280 $ord = ord( $char );
1281 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1282 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1283 // No, shouldn't be escaped
1284 return $char;
1285 } else {
1286 // Yes, leave it escaped
1287 return $matches[0];
1288 }
1289 }
1290
1291 /**
1292 * make an image if it's allowed, either through the global
1293 * option or through the exception
1294 * @private
1295 */
1296 function maybeMakeExternalImage( $url ) {
1297 $sk =& $this->mOptions->getSkin();
1298 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1299 $imagesexception = !empty($imagesfrom);
1300 $text = false;
1301 if ( $this->mOptions->getAllowExternalImages()
1302 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1303 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1304 # Image found
1305 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1306 }
1307 }
1308 return $text;
1309 }
1310
1311 /**
1312 * Process [[ ]] wikilinks
1313 *
1314 * @private
1315 */
1316 function replaceInternalLinks( $s ) {
1317 global $wgContLang;
1318 static $fname = 'Parser::replaceInternalLinks' ;
1319
1320 wfProfileIn( $fname );
1321
1322 wfProfileIn( $fname.'-setup' );
1323 static $tc = FALSE;
1324 # the % is needed to support urlencoded titles as well
1325 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1326
1327 $sk =& $this->mOptions->getSkin();
1328
1329 #split the entire text string on occurences of [[
1330 $a = explode( '[[', ' ' . $s );
1331 #get the first element (all text up to first [[), and remove the space we added
1332 $s = array_shift( $a );
1333 $s = substr( $s, 1 );
1334
1335 # Match a link having the form [[namespace:link|alternate]]trail
1336 static $e1 = FALSE;
1337 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1338 # Match cases where there is no "]]", which might still be images
1339 static $e1_img = FALSE;
1340 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1341 # Match the end of a line for a word that's not followed by whitespace,
1342 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1343 $e2 = wfMsgForContent( 'linkprefix' );
1344
1345 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1346
1347 if( is_null( $this->mTitle ) ) {
1348 throw new MWException( 'nooo' );
1349 }
1350 $nottalk = !$this->mTitle->isTalkPage();
1351
1352 if ( $useLinkPrefixExtension ) {
1353 if ( preg_match( $e2, $s, $m ) ) {
1354 $first_prefix = $m[2];
1355 } else {
1356 $first_prefix = false;
1357 }
1358 } else {
1359 $prefix = '';
1360 }
1361
1362 $selflink = $this->mTitle->getPrefixedText();
1363 wfProfileOut( $fname.'-setup' );
1364
1365 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1366 $useSubpages = $this->areSubpagesAllowed();
1367
1368 # Loop for each link
1369 for ($k = 0; isset( $a[$k] ); $k++) {
1370 $line = $a[$k];
1371 if ( $useLinkPrefixExtension ) {
1372 wfProfileIn( $fname.'-prefixhandling' );
1373 if ( preg_match( $e2, $s, $m ) ) {
1374 $prefix = $m[2];
1375 $s = $m[1];
1376 } else {
1377 $prefix='';
1378 }
1379 # first link
1380 if($first_prefix) {
1381 $prefix = $first_prefix;
1382 $first_prefix = false;
1383 }
1384 wfProfileOut( $fname.'-prefixhandling' );
1385 }
1386
1387 $might_be_img = false;
1388
1389 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1390 $text = $m[2];
1391 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1392 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1393 # the real problem is with the $e1 regex
1394 # See bug 1300.
1395 #
1396 # Still some problems for cases where the ] is meant to be outside punctuation,
1397 # and no image is in sight. See bug 2095.
1398 #
1399 if( $text !== '' &&
1400 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1401 strpos($text, '[') !== false
1402 )
1403 {
1404 $text .= ']'; # so that replaceExternalLinks($text) works later
1405 $m[3] = $n[1];
1406 }
1407 # fix up urlencoded title texts
1408 if(preg_match('/%/', $m[1] ))
1409 # Should anchors '#' also be rejected?
1410 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1411 $trail = $m[3];
1412 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1413 $might_be_img = true;
1414 $text = $m[2];
1415 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1416 $trail = "";
1417 } else { # Invalid form; output directly
1418 $s .= $prefix . '[[' . $line ;
1419 continue;
1420 }
1421
1422 # Don't allow internal links to pages containing
1423 # PROTO: where PROTO is a valid URL protocol; these
1424 # should be external links.
1425 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1426 $s .= $prefix . '[[' . $line ;
1427 continue;
1428 }
1429
1430 # Make subpage if necessary
1431 if( $useSubpages ) {
1432 $link = $this->maybeDoSubpageLink( $m[1], $text );
1433 } else {
1434 $link = $m[1];
1435 }
1436
1437 $noforce = (substr($m[1], 0, 1) != ':');
1438 if (!$noforce) {
1439 # Strip off leading ':'
1440 $link = substr($link, 1);
1441 }
1442
1443 $nt = Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1444 if( !$nt ) {
1445 $s .= $prefix . '[[' . $line;
1446 continue;
1447 }
1448
1449 #check other language variants of the link
1450 #if the article does not exist
1451 if( $checkVariantLink
1452 && $nt->getArticleID() == 0 ) {
1453 $wgContLang->findVariantLink($link, $nt);
1454 }
1455
1456 $ns = $nt->getNamespace();
1457 $iw = $nt->getInterWiki();
1458
1459 if ($might_be_img) { # if this is actually an invalid link
1460 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1461 $found = false;
1462 while (isset ($a[$k+1]) ) {
1463 #look at the next 'line' to see if we can close it there
1464 $spliced = array_splice( $a, $k + 1, 1 );
1465 $next_line = array_shift( $spliced );
1466 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1467 # the first ]] closes the inner link, the second the image
1468 $found = true;
1469 $text .= '[[' . $m[1];
1470 $trail = $m[2];
1471 break;
1472 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1473 #if there's exactly one ]] that's fine, we'll keep looking
1474 $text .= '[[' . $m[0];
1475 } else {
1476 #if $next_line is invalid too, we need look no further
1477 $text .= '[[' . $next_line;
1478 break;
1479 }
1480 }
1481 if ( !$found ) {
1482 # we couldn't find the end of this imageLink, so output it raw
1483 #but don't ignore what might be perfectly normal links in the text we've examined
1484 $text = $this->replaceInternalLinks($text);
1485 $s .= $prefix . '[[' . $link . '|' . $text;
1486 # note: no $trail, because without an end, there *is* no trail
1487 continue;
1488 }
1489 } else { #it's not an image, so output it raw
1490 $s .= $prefix . '[[' . $link . '|' . $text;
1491 # note: no $trail, because without an end, there *is* no trail
1492 continue;
1493 }
1494 }
1495
1496 $wasblank = ( '' == $text );
1497 if( $wasblank ) $text = $link;
1498
1499
1500 # Link not escaped by : , create the various objects
1501 if( $noforce ) {
1502
1503 # Interwikis
1504 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1505 $this->mOutput->addLanguageLink( $nt->getFullText() );
1506 $s = rtrim($s . "\n");
1507 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1508 continue;
1509 }
1510
1511 if ( $ns == NS_IMAGE ) {
1512 wfProfileIn( "$fname-image" );
1513 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1514 # recursively parse links inside the image caption
1515 # actually, this will parse them in any other parameters, too,
1516 # but it might be hard to fix that, and it doesn't matter ATM
1517 $text = $this->replaceExternalLinks($text);
1518 $text = $this->replaceInternalLinks($text);
1519
1520 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1521 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1522 $this->mOutput->addImage( $nt->getDBkey() );
1523
1524 wfProfileOut( "$fname-image" );
1525 continue;
1526 }
1527 wfProfileOut( "$fname-image" );
1528
1529 }
1530
1531 if ( $ns == NS_CATEGORY ) {
1532 wfProfileIn( "$fname-category" );
1533 $s = rtrim($s . "\n"); # bug 87
1534
1535 if ( $wasblank ) {
1536 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1537 $sortkey = $this->mTitle->getText();
1538 } else {
1539 $sortkey = $this->mTitle->getPrefixedText();
1540 }
1541 } else {
1542 $sortkey = $text;
1543 }
1544 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1545 $sortkey = str_replace( "\n", '', $sortkey );
1546 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1547 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1548
1549 /**
1550 * Strip the whitespace Category links produce, see bug 87
1551 * @todo We might want to use trim($tmp, "\n") here.
1552 */
1553 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1554
1555 wfProfileOut( "$fname-category" );
1556 continue;
1557 }
1558 }
1559
1560 if( ( $nt->getPrefixedText() === $selflink ) &&
1561 ( $nt->getFragment() === '' ) ) {
1562 # Self-links are handled specially; generally de-link and change to bold.
1563 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1564 continue;
1565 }
1566
1567 # Special and Media are pseudo-namespaces; no pages actually exist in them
1568 if( $ns == NS_MEDIA ) {
1569 $link = $sk->makeMediaLinkObj( $nt, $text );
1570 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1571 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1572 $this->mOutput->addImage( $nt->getDBkey() );
1573 continue;
1574 } elseif( $ns == NS_SPECIAL ) {
1575 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1576 continue;
1577 } elseif( $ns == NS_IMAGE ) {
1578 $img = Image::newFromTitle( $nt );
1579 if( $img->exists() ) {
1580 // Force a blue link if the file exists; may be a remote
1581 // upload on the shared repository, and we want to see its
1582 // auto-generated page.
1583 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1584 continue;
1585 }
1586 }
1587 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1588 }
1589 wfProfileOut( $fname );
1590 return $s;
1591 }
1592
1593 /**
1594 * Make a link placeholder. The text returned can be later resolved to a real link with
1595 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1596 * parsing of interwiki links, and secondly to allow all extistence checks and
1597 * article length checks (for stub links) to be bundled into a single query.
1598 *
1599 */
1600 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1601 if ( ! is_object($nt) ) {
1602 # Fail gracefully
1603 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1604 } else {
1605 # Separate the link trail from the rest of the link
1606 list( $inside, $trail ) = Linker::splitTrail( $trail );
1607
1608 if ( $nt->isExternal() ) {
1609 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1610 $this->mInterwikiLinkHolders['titles'][] = $nt;
1611 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1612 } else {
1613 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1614 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1615 $this->mLinkHolders['queries'][] = $query;
1616 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1617 $this->mLinkHolders['titles'][] = $nt;
1618
1619 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1620 }
1621 }
1622 return $retVal;
1623 }
1624
1625 /**
1626 * Render a forced-blue link inline; protect against double expansion of
1627 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1628 * Since this little disaster has to split off the trail text to avoid
1629 * breaking URLs in the following text without breaking trails on the
1630 * wiki links, it's been made into a horrible function.
1631 *
1632 * @param Title $nt
1633 * @param string $text
1634 * @param string $query
1635 * @param string $trail
1636 * @param string $prefix
1637 * @return string HTML-wikitext mix oh yuck
1638 */
1639 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1640 list( $inside, $trail ) = Linker::splitTrail( $trail );
1641 $sk =& $this->mOptions->getSkin();
1642 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1643 return $this->armorLinks( $link ) . $trail;
1644 }
1645
1646 /**
1647 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1648 * going to go through further parsing steps before inline URL expansion.
1649 *
1650 * In particular this is important when using action=render, which causes
1651 * full URLs to be included.
1652 *
1653 * Oh man I hate our multi-layer parser!
1654 *
1655 * @param string more-or-less HTML
1656 * @return string less-or-more HTML with NOPARSE bits
1657 */
1658 function armorLinks( $text ) {
1659 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1660 "{$this->mUniqPrefix}NOPARSE$1", $text );
1661 }
1662
1663 /**
1664 * Return true if subpage links should be expanded on this page.
1665 * @return bool
1666 */
1667 function areSubpagesAllowed() {
1668 # Some namespaces don't allow subpages
1669 global $wgNamespacesWithSubpages;
1670 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1671 }
1672
1673 /**
1674 * Handle link to subpage if necessary
1675 * @param string $target the source of the link
1676 * @param string &$text the link text, modified as necessary
1677 * @return string the full name of the link
1678 * @private
1679 */
1680 function maybeDoSubpageLink($target, &$text) {
1681 # Valid link forms:
1682 # Foobar -- normal
1683 # :Foobar -- override special treatment of prefix (images, language links)
1684 # /Foobar -- convert to CurrentPage/Foobar
1685 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1686 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1687 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1688
1689 $fname = 'Parser::maybeDoSubpageLink';
1690 wfProfileIn( $fname );
1691 $ret = $target; # default return value is no change
1692
1693 # Some namespaces don't allow subpages,
1694 # so only perform processing if subpages are allowed
1695 if( $this->areSubpagesAllowed() ) {
1696 # Look at the first character
1697 if( $target != '' && $target{0} == '/' ) {
1698 # / at end means we don't want the slash to be shown
1699 if( substr( $target, -1, 1 ) == '/' ) {
1700 $target = substr( $target, 1, -1 );
1701 $noslash = $target;
1702 } else {
1703 $noslash = substr( $target, 1 );
1704 }
1705
1706 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1707 if( '' === $text ) {
1708 $text = $target;
1709 } # this might be changed for ugliness reasons
1710 } else {
1711 # check for .. subpage backlinks
1712 $dotdotcount = 0;
1713 $nodotdot = $target;
1714 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1715 ++$dotdotcount;
1716 $nodotdot = substr( $nodotdot, 3 );
1717 }
1718 if($dotdotcount > 0) {
1719 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1720 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1721 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1722 # / at the end means don't show full path
1723 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1724 $nodotdot = substr( $nodotdot, 0, -1 );
1725 if( '' === $text ) {
1726 $text = $nodotdot;
1727 }
1728 }
1729 $nodotdot = trim( $nodotdot );
1730 if( $nodotdot != '' ) {
1731 $ret .= '/' . $nodotdot;
1732 }
1733 }
1734 }
1735 }
1736 }
1737
1738 wfProfileOut( $fname );
1739 return $ret;
1740 }
1741
1742 /**#@+
1743 * Used by doBlockLevels()
1744 * @private
1745 */
1746 /* private */ function closeParagraph() {
1747 $result = '';
1748 if ( '' != $this->mLastSection ) {
1749 $result = '</' . $this->mLastSection . ">\n";
1750 }
1751 $this->mInPre = false;
1752 $this->mLastSection = '';
1753 return $result;
1754 }
1755 # getCommon() returns the length of the longest common substring
1756 # of both arguments, starting at the beginning of both.
1757 #
1758 /* private */ function getCommon( $st1, $st2 ) {
1759 $fl = strlen( $st1 );
1760 $shorter = strlen( $st2 );
1761 if ( $fl < $shorter ) { $shorter = $fl; }
1762
1763 for ( $i = 0; $i < $shorter; ++$i ) {
1764 if ( $st1{$i} != $st2{$i} ) { break; }
1765 }
1766 return $i;
1767 }
1768 # These next three functions open, continue, and close the list
1769 # element appropriate to the prefix character passed into them.
1770 #
1771 /* private */ function openList( $char ) {
1772 $result = $this->closeParagraph();
1773
1774 if ( '*' == $char ) { $result .= '<ul><li>'; }
1775 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1776 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1777 else if ( ';' == $char ) {
1778 $result .= '<dl><dt>';
1779 $this->mDTopen = true;
1780 }
1781 else { $result = '<!-- ERR 1 -->'; }
1782
1783 return $result;
1784 }
1785
1786 /* private */ function nextItem( $char ) {
1787 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1788 else if ( ':' == $char || ';' == $char ) {
1789 $close = '</dd>';
1790 if ( $this->mDTopen ) { $close = '</dt>'; }
1791 if ( ';' == $char ) {
1792 $this->mDTopen = true;
1793 return $close . '<dt>';
1794 } else {
1795 $this->mDTopen = false;
1796 return $close . '<dd>';
1797 }
1798 }
1799 return '<!-- ERR 2 -->';
1800 }
1801
1802 /* private */ function closeList( $char ) {
1803 if ( '*' == $char ) { $text = '</li></ul>'; }
1804 else if ( '#' == $char ) { $text = '</li></ol>'; }
1805 else if ( ':' == $char ) {
1806 if ( $this->mDTopen ) {
1807 $this->mDTopen = false;
1808 $text = '</dt></dl>';
1809 } else {
1810 $text = '</dd></dl>';
1811 }
1812 }
1813 else { return '<!-- ERR 3 -->'; }
1814 return $text."\n";
1815 }
1816 /**#@-*/
1817
1818 /**
1819 * Make lists from lines starting with ':', '*', '#', etc.
1820 *
1821 * @private
1822 * @return string the lists rendered as HTML
1823 */
1824 function doBlockLevels( $text, $linestart ) {
1825 $fname = 'Parser::doBlockLevels';
1826 wfProfileIn( $fname );
1827
1828 # Parsing through the text line by line. The main thing
1829 # happening here is handling of block-level elements p, pre,
1830 # and making lists from lines starting with * # : etc.
1831 #
1832 $textLines = explode( "\n", $text );
1833
1834 $lastPrefix = $output = '';
1835 $this->mDTopen = $inBlockElem = false;
1836 $prefixLength = 0;
1837 $paragraphStack = false;
1838
1839 if ( !$linestart ) {
1840 $output .= array_shift( $textLines );
1841 }
1842 foreach ( $textLines as $oLine ) {
1843 $lastPrefixLength = strlen( $lastPrefix );
1844 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1845 $preOpenMatch = preg_match('/<pre/i', $oLine );
1846 if ( !$this->mInPre ) {
1847 # Multiple prefixes may abut each other for nested lists.
1848 $prefixLength = strspn( $oLine, '*#:;' );
1849 $pref = substr( $oLine, 0, $prefixLength );
1850
1851 # eh?
1852 $pref2 = str_replace( ';', ':', $pref );
1853 $t = substr( $oLine, $prefixLength );
1854 $this->mInPre = !empty($preOpenMatch);
1855 } else {
1856 # Don't interpret any other prefixes in preformatted text
1857 $prefixLength = 0;
1858 $pref = $pref2 = '';
1859 $t = $oLine;
1860 }
1861
1862 # List generation
1863 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1864 # Same as the last item, so no need to deal with nesting or opening stuff
1865 $output .= $this->nextItem( substr( $pref, -1 ) );
1866 $paragraphStack = false;
1867
1868 if ( substr( $pref, -1 ) == ';') {
1869 # The one nasty exception: definition lists work like this:
1870 # ; title : definition text
1871 # So we check for : in the remainder text to split up the
1872 # title and definition, without b0rking links.
1873 $term = $t2 = '';
1874 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1875 $t = $t2;
1876 $output .= $term . $this->nextItem( ':' );
1877 }
1878 }
1879 } elseif( $prefixLength || $lastPrefixLength ) {
1880 # Either open or close a level...
1881 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1882 $paragraphStack = false;
1883
1884 while( $commonPrefixLength < $lastPrefixLength ) {
1885 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1886 --$lastPrefixLength;
1887 }
1888 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1889 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1890 }
1891 while ( $prefixLength > $commonPrefixLength ) {
1892 $char = substr( $pref, $commonPrefixLength, 1 );
1893 $output .= $this->openList( $char );
1894
1895 if ( ';' == $char ) {
1896 # FIXME: This is dupe of code above
1897 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1898 $t = $t2;
1899 $output .= $term . $this->nextItem( ':' );
1900 }
1901 }
1902 ++$commonPrefixLength;
1903 }
1904 $lastPrefix = $pref2;
1905 }
1906 if( 0 == $prefixLength ) {
1907 wfProfileIn( "$fname-paragraph" );
1908 # No prefix (not in list)--go to paragraph mode
1909 // XXX: use a stack for nestable elements like span, table and div
1910 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
1911 $closematch = preg_match(
1912 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1913 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
1914 if ( $openmatch or $closematch ) {
1915 $paragraphStack = false;
1916 # TODO bug 5718: paragraph closed
1917 $output .= $this->closeParagraph();
1918 if ( $preOpenMatch and !$preCloseMatch ) {
1919 $this->mInPre = true;
1920 }
1921 if ( $closematch ) {
1922 $inBlockElem = false;
1923 } else {
1924 $inBlockElem = true;
1925 }
1926 } else if ( !$inBlockElem && !$this->mInPre ) {
1927 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1928 // pre
1929 if ($this->mLastSection != 'pre') {
1930 $paragraphStack = false;
1931 $output .= $this->closeParagraph().'<pre>';
1932 $this->mLastSection = 'pre';
1933 }
1934 $t = substr( $t, 1 );
1935 } else {
1936 // paragraph
1937 if ( '' == trim($t) ) {
1938 if ( $paragraphStack ) {
1939 $output .= $paragraphStack.'<br />';
1940 $paragraphStack = false;
1941 $this->mLastSection = 'p';
1942 } else {
1943 if ($this->mLastSection != 'p' ) {
1944 $output .= $this->closeParagraph();
1945 $this->mLastSection = '';
1946 $paragraphStack = '<p>';
1947 } else {
1948 $paragraphStack = '</p><p>';
1949 }
1950 }
1951 } else {
1952 if ( $paragraphStack ) {
1953 $output .= $paragraphStack;
1954 $paragraphStack = false;
1955 $this->mLastSection = 'p';
1956 } else if ($this->mLastSection != 'p') {
1957 $output .= $this->closeParagraph().'<p>';
1958 $this->mLastSection = 'p';
1959 }
1960 }
1961 }
1962 }
1963 wfProfileOut( "$fname-paragraph" );
1964 }
1965 // somewhere above we forget to get out of pre block (bug 785)
1966 if($preCloseMatch && $this->mInPre) {
1967 $this->mInPre = false;
1968 }
1969 if ($paragraphStack === false) {
1970 $output .= $t."\n";
1971 }
1972 }
1973 while ( $prefixLength ) {
1974 $output .= $this->closeList( $pref2{$prefixLength-1} );
1975 --$prefixLength;
1976 }
1977 if ( '' != $this->mLastSection ) {
1978 $output .= '</' . $this->mLastSection . '>';
1979 $this->mLastSection = '';
1980 }
1981
1982 wfProfileOut( $fname );
1983 return $output;
1984 }
1985
1986 /**
1987 * Split up a string on ':', ignoring any occurences inside tags
1988 * to prevent illegal overlapping.
1989 * @param string $str the string to split
1990 * @param string &$before set to everything before the ':'
1991 * @param string &$after set to everything after the ':'
1992 * return string the position of the ':', or false if none found
1993 */
1994 function findColonNoLinks($str, &$before, &$after) {
1995 $fname = 'Parser::findColonNoLinks';
1996 wfProfileIn( $fname );
1997
1998 $pos = strpos( $str, ':' );
1999 if( $pos === false ) {
2000 // Nothing to find!
2001 wfProfileOut( $fname );
2002 return false;
2003 }
2004
2005 $lt = strpos( $str, '<' );
2006 if( $lt === false || $lt > $pos ) {
2007 // Easy; no tag nesting to worry about
2008 $before = substr( $str, 0, $pos );
2009 $after = substr( $str, $pos+1 );
2010 wfProfileOut( $fname );
2011 return $pos;
2012 }
2013
2014 // Ugly state machine to walk through avoiding tags.
2015 $state = MW_COLON_STATE_TEXT;
2016 $stack = 0;
2017 $len = strlen( $str );
2018 for( $i = 0; $i < $len; $i++ ) {
2019 $c = $str{$i};
2020
2021 switch( $state ) {
2022 // (Using the number is a performance hack for common cases)
2023 case 0: // MW_COLON_STATE_TEXT:
2024 switch( $c ) {
2025 case "<":
2026 // Could be either a <start> tag or an </end> tag
2027 $state = MW_COLON_STATE_TAGSTART;
2028 break;
2029 case ":":
2030 if( $stack == 0 ) {
2031 // We found it!
2032 $before = substr( $str, 0, $i );
2033 $after = substr( $str, $i + 1 );
2034 wfProfileOut( $fname );
2035 return $i;
2036 }
2037 // Embedded in a tag; don't break it.
2038 break;
2039 default:
2040 // Skip ahead looking for something interesting
2041 $colon = strpos( $str, ':', $i );
2042 if( $colon === false ) {
2043 // Nothing else interesting
2044 wfProfileOut( $fname );
2045 return false;
2046 }
2047 $lt = strpos( $str, '<', $i );
2048 if( $stack === 0 ) {
2049 if( $lt === false || $colon < $lt ) {
2050 // We found it!
2051 $before = substr( $str, 0, $colon );
2052 $after = substr( $str, $colon + 1 );
2053 wfProfileOut( $fname );
2054 return $i;
2055 }
2056 }
2057 if( $lt === false ) {
2058 // Nothing else interesting to find; abort!
2059 // We're nested, but there's no close tags left. Abort!
2060 break 2;
2061 }
2062 // Skip ahead to next tag start
2063 $i = $lt;
2064 $state = MW_COLON_STATE_TAGSTART;
2065 }
2066 break;
2067 case 1: // MW_COLON_STATE_TAG:
2068 // In a <tag>
2069 switch( $c ) {
2070 case ">":
2071 $stack++;
2072 $state = MW_COLON_STATE_TEXT;
2073 break;
2074 case "/":
2075 // Slash may be followed by >?
2076 $state = MW_COLON_STATE_TAGSLASH;
2077 break;
2078 default:
2079 // ignore
2080 }
2081 break;
2082 case 2: // MW_COLON_STATE_TAGSTART:
2083 switch( $c ) {
2084 case "/":
2085 $state = MW_COLON_STATE_CLOSETAG;
2086 break;
2087 case "!":
2088 $state = MW_COLON_STATE_COMMENT;
2089 break;
2090 case ">":
2091 // Illegal early close? This shouldn't happen D:
2092 $state = MW_COLON_STATE_TEXT;
2093 break;
2094 default:
2095 $state = MW_COLON_STATE_TAG;
2096 }
2097 break;
2098 case 3: // MW_COLON_STATE_CLOSETAG:
2099 // In a </tag>
2100 if( $c == ">" ) {
2101 $stack--;
2102 if( $stack < 0 ) {
2103 wfDebug( "Invalid input in $fname; too many close tags\n" );
2104 wfProfileOut( $fname );
2105 return false;
2106 }
2107 $state = MW_COLON_STATE_TEXT;
2108 }
2109 break;
2110 case MW_COLON_STATE_TAGSLASH:
2111 if( $c == ">" ) {
2112 // Yes, a self-closed tag <blah/>
2113 $state = MW_COLON_STATE_TEXT;
2114 } else {
2115 // Probably we're jumping the gun, and this is an attribute
2116 $state = MW_COLON_STATE_TAG;
2117 }
2118 break;
2119 case 5: // MW_COLON_STATE_COMMENT:
2120 if( $c == "-" ) {
2121 $state = MW_COLON_STATE_COMMENTDASH;
2122 }
2123 break;
2124 case MW_COLON_STATE_COMMENTDASH:
2125 if( $c == "-" ) {
2126 $state = MW_COLON_STATE_COMMENTDASHDASH;
2127 } else {
2128 $state = MW_COLON_STATE_COMMENT;
2129 }
2130 break;
2131 case MW_COLON_STATE_COMMENTDASHDASH:
2132 if( $c == ">" ) {
2133 $state = MW_COLON_STATE_TEXT;
2134 } else {
2135 $state = MW_COLON_STATE_COMMENT;
2136 }
2137 break;
2138 default:
2139 throw new MWException( "State machine error in $fname" );
2140 }
2141 }
2142 if( $stack > 0 ) {
2143 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2144 return false;
2145 }
2146 wfProfileOut( $fname );
2147 return false;
2148 }
2149
2150 /**
2151 * Return value of a magic variable (like PAGENAME)
2152 *
2153 * @private
2154 */
2155 function getVariableValue( $index ) {
2156 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2157
2158 /**
2159 * Some of these require message or data lookups and can be
2160 * expensive to check many times.
2161 */
2162 static $varCache = array();
2163 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2164 if ( isset( $varCache[$index] ) )
2165 return $varCache[$index];
2166
2167 $ts = time();
2168 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2169
2170 switch ( $index ) {
2171 case MAG_CURRENTMONTH:
2172 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2173 case MAG_CURRENTMONTHNAME:
2174 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2175 case MAG_CURRENTMONTHNAMEGEN:
2176 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2177 case MAG_CURRENTMONTHABBREV:
2178 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2179 case MAG_CURRENTDAY:
2180 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2181 case MAG_CURRENTDAY2:
2182 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2183 case MAG_PAGENAME:
2184 return $this->mTitle->getText();
2185 case MAG_PAGENAMEE:
2186 return $this->mTitle->getPartialURL();
2187 case MAG_FULLPAGENAME:
2188 return $this->mTitle->getPrefixedText();
2189 case MAG_FULLPAGENAMEE:
2190 return $this->mTitle->getPrefixedURL();
2191 case MAG_SUBPAGENAME:
2192 return $this->mTitle->getSubpageText();
2193 case MAG_SUBPAGENAMEE:
2194 return $this->mTitle->getSubpageUrlForm();
2195 case MAG_BASEPAGENAME:
2196 return $this->mTitle->getBaseText();
2197 case MAG_BASEPAGENAMEE:
2198 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2199 case MAG_TALKPAGENAME:
2200 if( $this->mTitle->canTalk() ) {
2201 $talkPage = $this->mTitle->getTalkPage();
2202 return $talkPage->getPrefixedText();
2203 } else {
2204 return '';
2205 }
2206 case MAG_TALKPAGENAMEE:
2207 if( $this->mTitle->canTalk() ) {
2208 $talkPage = $this->mTitle->getTalkPage();
2209 return $talkPage->getPrefixedUrl();
2210 } else {
2211 return '';
2212 }
2213 case MAG_SUBJECTPAGENAME:
2214 $subjPage = $this->mTitle->getSubjectPage();
2215 return $subjPage->getPrefixedText();
2216 case MAG_SUBJECTPAGENAMEE:
2217 $subjPage = $this->mTitle->getSubjectPage();
2218 return $subjPage->getPrefixedUrl();
2219 case MAG_REVISIONID:
2220 return $this->mRevisionId;
2221 case MAG_NAMESPACE:
2222 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2223 case MAG_NAMESPACEE:
2224 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2225 case MAG_TALKSPACE:
2226 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2227 case MAG_TALKSPACEE:
2228 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2229 case MAG_SUBJECTSPACE:
2230 return $this->mTitle->getSubjectNsText();
2231 case MAG_SUBJECTSPACEE:
2232 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2233 case MAG_CURRENTDAYNAME:
2234 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
2235 case MAG_CURRENTYEAR:
2236 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2237 case MAG_CURRENTTIME:
2238 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2239 case MAG_CURRENTWEEK:
2240 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2241 // int to remove the padding
2242 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2243 case MAG_CURRENTDOW:
2244 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2245 case MAG_NUMBEROFARTICLES:
2246 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2247 case MAG_NUMBEROFFILES:
2248 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2249 case MAG_NUMBEROFUSERS:
2250 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2251 case MAG_NUMBEROFPAGES:
2252 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2253 case MAG_NUMBEROFADMINS:
2254 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfAdmins() );
2255 case MAG_CURRENTTIMESTAMP:
2256 return $varCache[$index] = wfTimestampNow();
2257 case MAG_CURRENTVERSION:
2258 global $wgVersion;
2259 return $wgVersion;
2260 case MAG_SITENAME:
2261 return $wgSitename;
2262 case MAG_SERVER:
2263 return $wgServer;
2264 case MAG_SERVERNAME:
2265 return $wgServerName;
2266 case MAG_SCRIPTPATH:
2267 return $wgScriptPath;
2268 case MAG_DIRECTIONMARK:
2269 return $wgContLang->getDirMark();
2270 case MAG_CONTENTLANGUAGE:
2271 global $wgContLanguageCode;
2272 return $wgContLanguageCode;
2273 default:
2274 $ret = null;
2275 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2276 return $ret;
2277 else
2278 return null;
2279 }
2280 }
2281
2282 /**
2283 * initialise the magic variables (like CURRENTMONTHNAME)
2284 *
2285 * @private
2286 */
2287 function initialiseVariables() {
2288 $fname = 'Parser::initialiseVariables';
2289 wfProfileIn( $fname );
2290 global $wgVariableIDs;
2291 $this->mVariables = array();
2292 foreach ( $wgVariableIDs as $id ) {
2293 $mw =& MagicWord::get( $id );
2294 $mw->addToArray( $this->mVariables, $id );
2295 }
2296 wfProfileOut( $fname );
2297 }
2298
2299 /**
2300 * parse any parentheses in format ((title|part|part))
2301 * and call callbacks to get a replacement text for any found piece
2302 *
2303 * @param string $text The text to parse
2304 * @param array $callbacks rules in form:
2305 * '{' => array( # opening parentheses
2306 * 'end' => '}', # closing parentheses
2307 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2308 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2309 * )
2310 * )
2311 * @private
2312 */
2313 function replace_callback ($text, $callbacks) {
2314 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2315 $lastOpeningBrace = -1; # last not closed parentheses
2316
2317 for ($i = 0; $i < strlen($text); $i++) {
2318 # check for any opening brace
2319 $rule = null;
2320 $nextPos = -1;
2321 foreach ($callbacks as $key => $value) {
2322 $pos = strpos ($text, $key, $i);
2323 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
2324 $rule = $value;
2325 $nextPos = $pos;
2326 }
2327 }
2328
2329 if ($lastOpeningBrace >= 0) {
2330 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2331
2332 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2333 $rule = null;
2334 $nextPos = $pos;
2335 }
2336
2337 $pos = strpos ($text, '|', $i);
2338
2339 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2340 $rule = null;
2341 $nextPos = $pos;
2342 }
2343 }
2344
2345 if ($nextPos == -1)
2346 break;
2347
2348 $i = $nextPos;
2349
2350 # found openning brace, lets add it to parentheses stack
2351 if (null != $rule) {
2352 $piece = array('brace' => $text[$i],
2353 'braceEnd' => $rule['end'],
2354 'count' => 1,
2355 'title' => '',
2356 'parts' => null);
2357
2358 # count openning brace characters
2359 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2360 $piece['count']++;
2361 $i++;
2362 }
2363
2364 $piece['startAt'] = $i+1;
2365 $piece['partStart'] = $i+1;
2366
2367 # we need to add to stack only if openning brace count is enough for any given rule
2368 foreach ($rule['cb'] as $cnt => $fn) {
2369 if ($piece['count'] >= $cnt) {
2370 $lastOpeningBrace ++;
2371 $openingBraceStack[$lastOpeningBrace] = $piece;
2372 break;
2373 }
2374 }
2375
2376 continue;
2377 }
2378 else if ($lastOpeningBrace >= 0) {
2379 # first check if it is a closing brace
2380 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2381 # lets check if it is enough characters for closing brace
2382 $count = 1;
2383 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2384 $count++;
2385
2386 # if there are more closing parentheses than opening ones, we parse less
2387 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2388 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2389
2390 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2391 $matchingCount = 0;
2392 $matchingCallback = null;
2393 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2394 if ($count >= $cnt && $matchingCount < $cnt) {
2395 $matchingCount = $cnt;
2396 $matchingCallback = $fn;
2397 }
2398 }
2399
2400 if ($matchingCount == 0) {
2401 $i += $count - 1;
2402 continue;
2403 }
2404
2405 # lets set a title or last part (if '|' was found)
2406 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2407 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2408 else
2409 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2410
2411 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2412 $pieceEnd = $i + $matchingCount;
2413
2414 if( is_callable( $matchingCallback ) ) {
2415 $cbArgs = array (
2416 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2417 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2418 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2419 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2420 );
2421 # finally we can call a user callback and replace piece of text
2422 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2423 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2424 $i = $pieceStart + strlen($replaceWith) - 1;
2425 }
2426 else {
2427 # null value for callback means that parentheses should be parsed, but not replaced
2428 $i += $matchingCount - 1;
2429 }
2430
2431 # reset last openning parentheses, but keep it in case there are unused characters
2432 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2433 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2434 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2435 'title' => '',
2436 'parts' => null,
2437 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2438 $openingBraceStack[$lastOpeningBrace--] = null;
2439
2440 if ($matchingCount < $piece['count']) {
2441 $piece['count'] -= $matchingCount;
2442 $piece['startAt'] -= $matchingCount;
2443 $piece['partStart'] = $piece['startAt'];
2444 # do we still qualify for any callback with remaining count?
2445 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2446 if ($piece['count'] >= $cnt) {
2447 $lastOpeningBrace ++;
2448 $openingBraceStack[$lastOpeningBrace] = $piece;
2449 break;
2450 }
2451 }
2452 }
2453 continue;
2454 }
2455
2456 # lets set a title if it is a first separator, or next part otherwise
2457 if ($text[$i] == '|') {
2458 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2459 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2460 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2461 }
2462 else
2463 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2464
2465 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2466 }
2467 }
2468 }
2469
2470 return $text;
2471 }
2472
2473 /**
2474 * Replace magic variables, templates, and template arguments
2475 * with the appropriate text. Templates are substituted recursively,
2476 * taking care to avoid infinite loops.
2477 *
2478 * Note that the substitution depends on value of $mOutputType:
2479 * OT_WIKI: only {{subst:}} templates
2480 * OT_MSG: only magic variables
2481 * OT_HTML: all templates and magic variables
2482 *
2483 * @param string $tex The text to transform
2484 * @param array $args Key-value pairs representing template parameters to substitute
2485 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2486 * @private
2487 */
2488 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2489 # Prevent too big inclusions
2490 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2491 return $text;
2492 }
2493
2494 $fname = 'Parser::replaceVariables';
2495 wfProfileIn( $fname );
2496
2497 # This function is called recursively. To keep track of arguments we need a stack:
2498 array_push( $this->mArgStack, $args );
2499
2500 $braceCallbacks = array();
2501 if ( !$argsOnly ) {
2502 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2503 }
2504 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2505 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2506 }
2507 $callbacks = array();
2508 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2509 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2510 $text = $this->replace_callback ($text, $callbacks);
2511
2512 array_pop( $this->mArgStack );
2513
2514 wfProfileOut( $fname );
2515 return $text;
2516 }
2517
2518 /**
2519 * Replace magic variables
2520 * @private
2521 */
2522 function variableSubstitution( $matches ) {
2523 $fname = 'Parser::variableSubstitution';
2524 $varname = $matches[1];
2525 wfProfileIn( $fname );
2526 if ( !$this->mVariables ) {
2527 $this->initialiseVariables();
2528 }
2529 $skip = false;
2530 if ( $this->mOutputType == OT_WIKI ) {
2531 # Do only magic variables prefixed by SUBST
2532 $mwSubst =& MagicWord::get( MAG_SUBST );
2533 if (!$mwSubst->matchStartAndRemove( $varname ))
2534 $skip = true;
2535 # Note that if we don't substitute the variable below,
2536 # we don't remove the {{subst:}} magic word, in case
2537 # it is a template rather than a magic variable.
2538 }
2539 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2540 $id = $this->mVariables[$varname];
2541 $text = $this->getVariableValue( $id );
2542 $this->mOutput->mContainsOldMagic = true;
2543 } else {
2544 $text = $matches[0];
2545 }
2546 wfProfileOut( $fname );
2547 return $text;
2548 }
2549
2550 # Split template arguments
2551 function getTemplateArgs( $argsString ) {
2552 if ( $argsString === '' ) {
2553 return array();
2554 }
2555
2556 $args = explode( '|', substr( $argsString, 1 ) );
2557
2558 # If any of the arguments contains a '[[' but no ']]', it needs to be
2559 # merged with the next arg because the '|' character between belongs
2560 # to the link syntax and not the template parameter syntax.
2561 $argc = count($args);
2562
2563 for ( $i = 0; $i < $argc-1; $i++ ) {
2564 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2565 $args[$i] .= '|'.$args[$i+1];
2566 array_splice($args, $i+1, 1);
2567 $i--;
2568 $argc--;
2569 }
2570 }
2571
2572 return $args;
2573 }
2574
2575 /**
2576 * Return the text of a template, after recursively
2577 * replacing any variables or templates within the template.
2578 *
2579 * @param array $piece The parts of the template
2580 * $piece['text']: matched text
2581 * $piece['title']: the title, i.e. the part before the |
2582 * $piece['parts']: the parameter array
2583 * @return string the text of the template
2584 * @private
2585 */
2586 function braceSubstitution( $piece ) {
2587 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2588 $fname = 'Parser::braceSubstitution';
2589 wfProfileIn( $fname );
2590
2591 # Flags
2592 $found = false; # $text has been filled
2593 $nowiki = false; # wiki markup in $text should be escaped
2594 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2595 $noargs = false; # Don't replace triple-brace arguments in $text
2596 $replaceHeadings = false; # Make the edit section links go to the template not the article
2597 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2598 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2599
2600 # Title object, where $text came from
2601 $title = NULL;
2602
2603 $linestart = '';
2604
2605 # $part1 is the bit before the first |, and must contain only title characters
2606 # $args is a list of arguments, starting from index 0, not including $part1
2607
2608 $part1 = $piece['title'];
2609 # If the third subpattern matched anything, it will start with |
2610
2611 if (null == $piece['parts']) {
2612 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2613 if ($replaceWith != $piece['text']) {
2614 $text = $replaceWith;
2615 $found = true;
2616 $noparse = true;
2617 $noargs = true;
2618 }
2619 }
2620
2621 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2622 $argc = count( $args );
2623
2624 # SUBST
2625 if ( !$found ) {
2626 $mwSubst =& MagicWord::get( MAG_SUBST );
2627 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2628 # One of two possibilities is true:
2629 # 1) Found SUBST but not in the PST phase
2630 # 2) Didn't find SUBST and in the PST phase
2631 # In either case, return without further processing
2632 $text = $piece['text'];
2633 $found = true;
2634 $noparse = true;
2635 $noargs = true;
2636 }
2637 }
2638
2639 # MSG, MSGNW, INT and RAW
2640 if ( !$found ) {
2641 # Check for MSGNW:
2642 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2643 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2644 $nowiki = true;
2645 } else {
2646 # Remove obsolete MSG:
2647 $mwMsg =& MagicWord::get( MAG_MSG );
2648 $mwMsg->matchStartAndRemove( $part1 );
2649 }
2650
2651 # Check for RAW:
2652 $mwRaw =& MagicWord::get( MAG_RAW );
2653 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2654 $forceRawInterwiki = true;
2655 }
2656
2657 # Check if it is an internal message
2658 $mwInt =& MagicWord::get( MAG_INT );
2659 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2660 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2661 $text = $linestart . wfMsgReal( $part1, $args, true );
2662 $found = true;
2663 }
2664 }
2665 }
2666
2667 # NS
2668 if ( !$found ) {
2669 # Check for NS: (namespace expansion)
2670 $mwNs = MagicWord::get( MAG_NS );
2671 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2672 if ( intval( $part1 ) || $part1 == "0" ) {
2673 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2674 $found = true;
2675 } else {
2676 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2677 if ( !is_null( $index ) ) {
2678 $text = $linestart . $wgContLang->getNsText( $index );
2679 $found = true;
2680 }
2681 }
2682 }
2683 }
2684
2685 # URLENCODE
2686 if( !$found ) {
2687 $urlencode =& MagicWord::get( MAG_URLENCODE );
2688 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2689 $text = $linestart . urlencode( $part1 );
2690 $found = true;
2691 }
2692 }
2693
2694 # LCFIRST, UCFIRST, LC and UC
2695 if ( !$found ) {
2696 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2697 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2698 $lc =& MagicWord::get( MAG_LC );
2699 $uc =& MagicWord::get( MAG_UC );
2700 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2701 $text = $linestart . $wgContLang->lcfirst( $part1 );
2702 $found = true;
2703 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2704 $text = $linestart . $wgContLang->ucfirst( $part1 );
2705 $found = true;
2706 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2707 $text = $linestart . $wgContLang->lc( $part1 );
2708 $found = true;
2709 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2710 $text = $linestart . $wgContLang->uc( $part1 );
2711 $found = true;
2712 }
2713 }
2714
2715 # LOCALURL and FULLURL
2716 if ( !$found ) {
2717 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2718 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2719 $mwFull =& MagicWord::get( MAG_FULLURL );
2720 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2721
2722
2723 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2724 $func = 'getLocalURL';
2725 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2726 $func = 'escapeLocalURL';
2727 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2728 $func = 'getFullURL';
2729 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2730 $func = 'escapeFullURL';
2731 } else {
2732 $func = false;
2733 }
2734
2735 if ( $func !== false ) {
2736 $title = Title::newFromText( $part1 );
2737 # Due to order of execution of a lot of bits, the values might be encoded
2738 # before arriving here; if that's true, then the title can't be created
2739 # and the variable will fail. If we can't get a decent title from the first
2740 # attempt, url-decode and try for a second.
2741 if( is_null( $title ) )
2742 $title = Title::newFromUrl( urldecode( $part1 ) );
2743 if ( !is_null( $title ) ) {
2744 if ( $argc > 0 ) {
2745 $text = $linestart . $title->$func( $args[0] );
2746 } else {
2747 $text = $linestart . $title->$func();
2748 }
2749 $found = true;
2750 }
2751 }
2752 }
2753
2754 $lang = $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
2755 # GRAMMAR
2756 if ( !$found && $argc == 1 ) {
2757 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2758 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2759 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2760 $found = true;
2761 }
2762 }
2763
2764 # PLURAL
2765 if ( !$found && $argc >= 2 ) {
2766 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2767 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2768 while ( count($args) < 5 ) { $args[] = $args[count($args)-1]; }
2769 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1],
2770 $args[2], $args[3], $args[4]);
2771 $found = true;
2772 }
2773 }
2774
2775 # DISPLAYTITLE
2776 if ( !$found && $argc == 1 && $wgAllowDisplayTitle ) {
2777 $mwDT =& MagicWord::get( MAG_DISPLAYTITLE );
2778 if ( $mwDT->matchStartAndRemove( $part1 ) ) {
2779
2780 # Set title in parser output object
2781 $param = $args[0];
2782 $parserOptions = new ParserOptions;
2783 $local_parser = new Parser ();
2784 $t2 = $local_parser->parse ( $param, $this->mTitle, $parserOptions, false );
2785 $this->mOutput->mHTMLtitle = $t2->GetText();
2786
2787 # Add subtitle
2788 $t = $this->mTitle->getPrefixedText();
2789 $this->mOutput->mSubtitle .= wfMsg('displaytitle', $t);
2790 $text = "" ;
2791 $found = true ;
2792 }
2793 }
2794
2795 # NUMBEROFPAGES, NUMBEROFUSERS, NUMBEROFARTICLES, and NUMBEROFFILES
2796 if( !$found ) {
2797 $mwWordsToCheck = array( MAG_NUMBEROFPAGES => 'wfNumberOfPages',
2798 MAG_NUMBEROFUSERS => 'wfNumberOfUsers',
2799 MAG_NUMBEROFARTICLES => 'wfNumberOfArticles',
2800 MAG_NUMBEROFFILES => 'wfNumberOfFiles',
2801 MAG_NUMBEROFADMINS => 'wfNumberOfAdmins' );
2802 foreach( $mwWordsToCheck as $word => $func ) {
2803 $mwCurrentWord =& MagicWord::get( $word );
2804 if( $mwCurrentWord->matchStartAndRemove( $part1 ) ) {
2805 $mwRawSuffix =& MagicWord::get( MAG_RAWSUFFIX );
2806 if( isset( $args[0] ) && $mwRawSuffix->match( $args[0] ) ) {
2807 # Raw and unformatted
2808 $text = $linestart . call_user_func( $func );
2809 } else {
2810 # Formatted according to the content default
2811 $text = $linestart . $wgContLang->formatNum( call_user_func( $func ) );
2812 }
2813 $found = true;
2814 }
2815 }
2816 }
2817
2818 # PAGESINNAMESPACE
2819 if( !$found ) {
2820 $mwPagesInNs =& MagicWord::get( MAG_PAGESINNAMESPACE );
2821 if( $mwPagesInNs->matchStartAndRemove( $part1 ) ) {
2822 $found = true;
2823 $count = wfPagesInNs( intval( $part1 ) );
2824 $mwRawSuffix =& MagicWord::get( MAG_RAWSUFFIX );
2825 if( isset( $args[0] ) && $mwRawSuffix->match( $args[0] ) ) {
2826 $text = $linestart . $count;
2827 } else {
2828 $text = $linestart . $wgContLang->formatNum( $count );
2829 }
2830 }
2831 }
2832
2833 # #LANGUAGE:
2834 if( !$found ) {
2835 $mwLanguage =& MagicWord::get( MAG_LANGUAGE );
2836 if( $mwLanguage->matchStartAndRemove( $part1 ) ) {
2837 $lang = $wgContLang->getLanguageName( strtolower( $part1 ) );
2838 $text = $linestart . ( $lang != '' ? $lang : $part1 );
2839 $found = true;
2840 }
2841 }
2842
2843 # Extensions
2844 if ( !$found && substr( $part1, 0, 1 ) == '#' ) {
2845 $colonPos = strpos( $part1, ':' );
2846 if ( $colonPos !== false ) {
2847 $function = strtolower( substr( $part1, 1, $colonPos - 1 ) );
2848 if ( isset( $this->mFunctionHooks[$function] ) ) {
2849 $funcArgs = array_map( 'trim', $args );
2850 $funcArgs = array_merge( array( &$this, trim( substr( $part1, $colonPos + 1 ) ) ), $funcArgs );
2851 $result = call_user_func_array( $this->mFunctionHooks[$function], $funcArgs );
2852 $found = true;
2853
2854 // The text is usually already parsed, doesn't need triple-brace tags expanded, etc.
2855 //$noargs = true;
2856 //$noparse = true;
2857
2858 if ( is_array( $result ) ) {
2859 $text = $linestart . $result[0];
2860 unset( $result[0] );
2861
2862 // Extract flags into the local scope
2863 // This allows callers to set flags such as nowiki, noparse, found, etc.
2864 extract( $result );
2865 } else {
2866 $text = $linestart . $result;
2867 }
2868 }
2869 }
2870 }
2871
2872 # Template table test
2873
2874 # Did we encounter this template already? If yes, it is in the cache
2875 # and we need to check for loops.
2876 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
2877 $found = true;
2878
2879 # Infinite loop test
2880 if ( isset( $this->mTemplatePath[$part1] ) ) {
2881 $noparse = true;
2882 $noargs = true;
2883 $found = true;
2884 $text = $linestart .
2885 '{{' . $part1 . '}}' .
2886 '<!-- WARNING: template loop detected -->';
2887 wfDebug( "$fname: template loop broken at '$part1'\n" );
2888 } else {
2889 # set $text to cached message.
2890 $text = $linestart . $this->mTemplates[$piece['title']];
2891 }
2892 }
2893
2894 # Load from database
2895 $lastPathLevel = $this->mTemplatePath;
2896 if ( !$found ) {
2897 $ns = NS_TEMPLATE;
2898 # declaring $subpage directly in the function call
2899 # does not work correctly with references and breaks
2900 # {{/subpage}}-style inclusions
2901 $subpage = '';
2902 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2903 if ($subpage !== '') {
2904 $ns = $this->mTitle->getNamespace();
2905 }
2906 $title = Title::newFromText( $part1, $ns );
2907
2908
2909 if ( !is_null( $title ) ) {
2910 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
2911 # Check for language variants if the template is not found
2912 if($checkVariantLink && $title->getArticleID() == 0){
2913 $wgContLang->findVariantLink($part1, $title);
2914 }
2915
2916 if ( !$title->isExternal() ) {
2917 # Check for excessive inclusion
2918 $dbk = $title->getPrefixedDBkey();
2919 if ( $this->incrementIncludeCount( $dbk ) ) {
2920 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->mOutputType != OT_WIKI ) {
2921 $text = SpecialPage::capturePath( $title );
2922 if ( is_string( $text ) ) {
2923 $found = true;
2924 $noparse = true;
2925 $noargs = true;
2926 $isHTML = true;
2927 $this->disableCache();
2928 }
2929 } else {
2930 $articleContent = $this->fetchTemplate( $title );
2931 if ( $articleContent !== false ) {
2932 $found = true;
2933 $text = $articleContent;
2934 $replaceHeadings = true;
2935 }
2936 }
2937 }
2938
2939 # If the title is valid but undisplayable, make a link to it
2940 if ( $this->mOutputType == OT_HTML && !$found ) {
2941 $text = '[['.$title->getPrefixedText().']]';
2942 $found = true;
2943 }
2944 } elseif ( $title->isTrans() ) {
2945 // Interwiki transclusion
2946 if ( $this->mOutputType == OT_HTML && !$forceRawInterwiki ) {
2947 $text = $this->interwikiTransclude( $title, 'render' );
2948 $isHTML = true;
2949 $noparse = true;
2950 } else {
2951 $text = $this->interwikiTransclude( $title, 'raw' );
2952 $replaceHeadings = true;
2953 }
2954 $found = true;
2955 }
2956
2957 # Template cache array insertion
2958 # Use the original $piece['title'] not the mangled $part1, so that
2959 # modifiers such as RAW: produce separate cache entries
2960 if( $found ) {
2961 if( $isHTML ) {
2962 // A special page; don't store it in the template cache.
2963 } else {
2964 $this->mTemplates[$piece['title']] = $text;
2965 }
2966 $text = $linestart . $text;
2967 }
2968 }
2969 }
2970
2971 # Recursive parsing, escaping and link table handling
2972 # Only for HTML output
2973 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2974 $text = wfEscapeWikiText( $text );
2975 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found ) {
2976 if ( $noargs ) {
2977 $assocArgs = array();
2978 } else {
2979 # Clean up argument array
2980 $assocArgs = array();
2981 $index = 1;
2982 foreach( $args as $arg ) {
2983 $eqpos = strpos( $arg, '=' );
2984 if ( $eqpos === false ) {
2985 $assocArgs[$index++] = $arg;
2986 } else {
2987 $name = trim( substr( $arg, 0, $eqpos ) );
2988 $value = trim( substr( $arg, $eqpos+1 ) );
2989 if ( $value === false ) {
2990 $value = '';
2991 }
2992 if ( $name !== false ) {
2993 $assocArgs[$name] = $value;
2994 }
2995 }
2996 }
2997
2998 # Add a new element to the templace recursion path
2999 $this->mTemplatePath[$part1] = 1;
3000 }
3001
3002 if ( !$noparse ) {
3003 # If there are any <onlyinclude> tags, only include them
3004 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
3005 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
3006 $text = '';
3007 foreach ($m[1] as $piece)
3008 $text .= $piece;
3009 }
3010 # Remove <noinclude> sections and <includeonly> tags
3011 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
3012 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
3013
3014 if( $this->mOutputType == OT_HTML ) {
3015 # Strip <nowiki>, <pre>, etc.
3016 $text = $this->strip( $text, $this->mStripState );
3017 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
3018 }
3019 $text = $this->replaceVariables( $text, $assocArgs );
3020
3021 # If the template begins with a table or block-level
3022 # element, it should be treated as beginning a new line.
3023 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
3024 $text = "\n" . $text;
3025 }
3026 } elseif ( !$noargs ) {
3027 # $noparse and !$noargs
3028 # Just replace the arguments, not any double-brace items
3029 # This is used for rendered interwiki transclusion
3030 $text = $this->replaceVariables( $text, $assocArgs, true );
3031 }
3032 }
3033 # Prune lower levels off the recursion check path
3034 $this->mTemplatePath = $lastPathLevel;
3035
3036 if ( !$found ) {
3037 wfProfileOut( $fname );
3038 return $piece['text'];
3039 } else {
3040 if ( $isHTML ) {
3041 # Replace raw HTML by a placeholder
3042 # Add a blank line preceding, to prevent it from mucking up
3043 # immediately preceding headings
3044 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
3045 } else {
3046 # replace ==section headers==
3047 # XXX this needs to go away once we have a better parser.
3048 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
3049 if( !is_null( $title ) )
3050 $encodedname = base64_encode($title->getPrefixedDBkey());
3051 else
3052 $encodedname = base64_encode("");
3053 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3054 PREG_SPLIT_DELIM_CAPTURE);
3055 $text = '';
3056 $nsec = 0;
3057 for( $i = 0; $i < count($m); $i += 2 ) {
3058 $text .= $m[$i];
3059 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
3060 $hl = $m[$i + 1];
3061 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3062 $text .= $hl;
3063 continue;
3064 }
3065 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3066 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3067 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3068
3069 $nsec++;
3070 }
3071 }
3072 }
3073 }
3074
3075 # Prune lower levels off the recursion check path
3076 $this->mTemplatePath = $lastPathLevel;
3077
3078 if ( !$found ) {
3079 wfProfileOut( $fname );
3080 return $piece['text'];
3081 } else {
3082 wfProfileOut( $fname );
3083 return $text;
3084 }
3085 }
3086
3087 /**
3088 * Fetch the unparsed text of a template and register a reference to it.
3089 */
3090 function fetchTemplate( $title ) {
3091 $text = false;
3092 // Loop to fetch the article, with up to 1 redirect
3093 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3094 $rev = Revision::newFromTitle( $title );
3095 $this->mOutput->addTemplate( $title, $title->getArticleID() );
3096 if ( !$rev ) {
3097 break;
3098 }
3099 $text = $rev->getText();
3100 if ( $text === false ) {
3101 break;
3102 }
3103 // Redirect?
3104 $title = Title::newFromRedirect( $text );
3105 }
3106 return $text;
3107 }
3108
3109 /**
3110 * Transclude an interwiki link.
3111 */
3112 function interwikiTransclude( $title, $action ) {
3113 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3114
3115 if (!$wgEnableScaryTranscluding)
3116 return wfMsg('scarytranscludedisabled');
3117
3118 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3119 // But we'll handle it generally anyway
3120 if ( $title->getNamespace() ) {
3121 // Use the canonical namespace, which should work anywhere
3122 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3123 } else {
3124 $articleName = $title->getDBkey();
3125 }
3126
3127 $url = str_replace('$1', urlencode($articleName), Title::getInterwikiLink($title->getInterwiki()));
3128 $url .= "?action=$action";
3129 if (strlen($url) > 255)
3130 return wfMsg('scarytranscludetoolong');
3131 return $this->fetchScaryTemplateMaybeFromCache($url);
3132 }
3133
3134 function fetchScaryTemplateMaybeFromCache($url) {
3135 global $wgTranscludeCacheExpiry;
3136 $dbr =& wfGetDB(DB_SLAVE);
3137 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3138 array('tc_url' => $url));
3139 if ($obj) {
3140 $time = $obj->tc_time;
3141 $text = $obj->tc_contents;
3142 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3143 return $text;
3144 }
3145 }
3146
3147 $text = wfGetHTTP($url);
3148 if (!$text)
3149 return wfMsg('scarytranscludefailed', $url);
3150
3151 $dbw =& wfGetDB(DB_MASTER);
3152 $dbw->replace('transcache', array('tc_url'), array(
3153 'tc_url' => $url,
3154 'tc_time' => time(),
3155 'tc_contents' => $text));
3156 return $text;
3157 }
3158
3159
3160 /**
3161 * Triple brace replacement -- used for template arguments
3162 * @private
3163 */
3164 function argSubstitution( $matches ) {
3165 $arg = trim( $matches['title'] );
3166 $text = $matches['text'];
3167 $inputArgs = end( $this->mArgStack );
3168
3169 if ( array_key_exists( $arg, $inputArgs ) ) {
3170 $text = $inputArgs[$arg];
3171 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
3172 $text = $matches['parts'][0];
3173 }
3174
3175 return $text;
3176 }
3177
3178 /**
3179 * Returns true if the function is allowed to include this entity
3180 * @private
3181 */
3182 function incrementIncludeCount( $dbk ) {
3183 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
3184 $this->mIncludeCount[$dbk] = 0;
3185 }
3186 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
3187 return true;
3188 } else {
3189 return false;
3190 }
3191 }
3192
3193 /**
3194 * Detect __NOGALLERY__ magic word and set a placeholder
3195 */
3196 function stripNoGallery( &$text ) {
3197 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3198 # do not add TOC
3199 $mw = MagicWord::get( MAG_NOGALLERY );
3200 $this->mOutput->mNoGallery = $mw->matchAndRemove( $text ) ;
3201 }
3202
3203 /**
3204 * Detect __TOC__ magic word and set a placeholder
3205 */
3206 function stripToc( $text ) {
3207 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3208 # do not add TOC
3209 $mw = MagicWord::get( MAG_NOTOC );
3210 if( $mw->matchAndRemove( $text ) ) {
3211 $this->mShowToc = false;
3212 }
3213
3214 $mw = MagicWord::get( MAG_TOC );
3215 if( $mw->match( $text ) ) {
3216 $this->mShowToc = true;
3217 $this->mForceTocPosition = true;
3218
3219 // Set a placeholder. At the end we'll fill it in with the TOC.
3220 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3221
3222 // Only keep the first one.
3223 $text = $mw->replace( '', $text );
3224 }
3225 return $text;
3226 }
3227
3228 /**
3229 * This function accomplishes several tasks:
3230 * 1) Auto-number headings if that option is enabled
3231 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3232 * 3) Add a Table of contents on the top for users who have enabled the option
3233 * 4) Auto-anchor headings
3234 *
3235 * It loops through all headlines, collects the necessary data, then splits up the
3236 * string and re-inserts the newly formatted headlines.
3237 *
3238 * @param string $text
3239 * @param boolean $isMain
3240 * @private
3241 */
3242 function formatHeadings( $text, $isMain=true ) {
3243 global $wgMaxTocLevel, $wgContLang;
3244
3245 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3246 if( !$this->mTitle->userCanEdit() ) {
3247 $showEditLink = 0;
3248 } else {
3249 $showEditLink = $this->mOptions->getEditSection();
3250 }
3251
3252 # Inhibit editsection links if requested in the page
3253 $esw =& MagicWord::get( MAG_NOEDITSECTION );
3254 if( $esw->matchAndRemove( $text ) ) {
3255 $showEditLink = 0;
3256 }
3257
3258 # Get all headlines for numbering them and adding funky stuff like [edit]
3259 # links - this is for later, but we need the number of headlines right now
3260 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3261
3262 # if there are fewer than 4 headlines in the article, do not show TOC
3263 # unless it's been explicitly enabled.
3264 $enoughToc = $this->mShowToc &&
3265 (($numMatches >= 4) || $this->mForceTocPosition);
3266
3267 # Allow user to stipulate that a page should have a "new section"
3268 # link added via __NEWSECTIONLINK__
3269 $mw =& MagicWord::get( MAG_NEWSECTIONLINK );
3270 if( $mw->matchAndRemove( $text ) )
3271 $this->mOutput->setNewSection( true );
3272
3273 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3274 # override above conditions and always show TOC above first header
3275 $mw =& MagicWord::get( MAG_FORCETOC );
3276 if ($mw->matchAndRemove( $text ) ) {
3277 $this->mShowToc = true;
3278 $enoughToc = true;
3279 }
3280
3281 # Never ever show TOC if no headers
3282 if( $numMatches < 1 ) {
3283 $enoughToc = false;
3284 }
3285
3286 # We need this to perform operations on the HTML
3287 $sk =& $this->mOptions->getSkin();
3288
3289 # headline counter
3290 $headlineCount = 0;
3291 $sectionCount = 0; # headlineCount excluding template sections
3292
3293 # Ugh .. the TOC should have neat indentation levels which can be
3294 # passed to the skin functions. These are determined here
3295 $toc = '';
3296 $full = '';
3297 $head = array();
3298 $sublevelCount = array();
3299 $levelCount = array();
3300 $toclevel = 0;
3301 $level = 0;
3302 $prevlevel = 0;
3303 $toclevel = 0;
3304 $prevtoclevel = 0;
3305
3306 foreach( $matches[3] as $headline ) {
3307 $istemplate = 0;
3308 $templatetitle = '';
3309 $templatesection = 0;
3310 $numbering = '';
3311
3312 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3313 $istemplate = 1;
3314 $templatetitle = base64_decode($mat[1]);
3315 $templatesection = 1 + (int)base64_decode($mat[2]);
3316 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3317 }
3318
3319 if( $toclevel ) {
3320 $prevlevel = $level;
3321 $prevtoclevel = $toclevel;
3322 }
3323 $level = $matches[1][$headlineCount];
3324
3325 if( $doNumberHeadings || $enoughToc ) {
3326
3327 if ( $level > $prevlevel ) {
3328 # Increase TOC level
3329 $toclevel++;
3330 $sublevelCount[$toclevel] = 0;
3331 if( $toclevel<$wgMaxTocLevel ) {
3332 $toc .= $sk->tocIndent();
3333 }
3334 }
3335 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3336 # Decrease TOC level, find level to jump to
3337
3338 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3339 # Can only go down to level 1
3340 $toclevel = 1;
3341 } else {
3342 for ($i = $toclevel; $i > 0; $i--) {
3343 if ( $levelCount[$i] == $level ) {
3344 # Found last matching level
3345 $toclevel = $i;
3346 break;
3347 }
3348 elseif ( $levelCount[$i] < $level ) {
3349 # Found first matching level below current level
3350 $toclevel = $i + 1;
3351 break;
3352 }
3353 }
3354 }
3355 if( $toclevel<$wgMaxTocLevel ) {
3356 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3357 }
3358 }
3359 else {
3360 # No change in level, end TOC line
3361 if( $toclevel<$wgMaxTocLevel ) {
3362 $toc .= $sk->tocLineEnd();
3363 }
3364 }
3365
3366 $levelCount[$toclevel] = $level;
3367
3368 # count number of headlines for each level
3369 @$sublevelCount[$toclevel]++;
3370 $dot = 0;
3371 for( $i = 1; $i <= $toclevel; $i++ ) {
3372 if( !empty( $sublevelCount[$i] ) ) {
3373 if( $dot ) {
3374 $numbering .= '.';
3375 }
3376 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3377 $dot = 1;
3378 }
3379 }
3380 }
3381
3382 # The canonized header is a version of the header text safe to use for links
3383 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3384 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
3385 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
3386
3387 # Remove link placeholders by the link text.
3388 # <!--LINK number-->
3389 # turns into
3390 # link text with suffix
3391 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3392 "\$this->mLinkHolders['texts'][\$1]",
3393 $canonized_headline );
3394 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3395 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3396 $canonized_headline );
3397
3398 # strip out HTML
3399 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3400 $tocline = trim( $canonized_headline );
3401 # Save headline for section edit hint before it's escaped
3402 $headline_hint = trim( $canonized_headline );
3403 $canonized_headline = Sanitizer::escapeId( $tocline );
3404 $refers[$headlineCount] = $canonized_headline;
3405
3406 # count how many in assoc. array so we can track dupes in anchors
3407 @$refers[$canonized_headline]++;
3408 $refcount[$headlineCount]=$refers[$canonized_headline];
3409
3410 # Don't number the heading if it is the only one (looks silly)
3411 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3412 # the two are different if the line contains a link
3413 $headline=$numbering . ' ' . $headline;
3414 }
3415
3416 # Create the anchor for linking from the TOC to the section
3417 $anchor = $canonized_headline;
3418 if($refcount[$headlineCount] > 1 ) {
3419 $anchor .= '_' . $refcount[$headlineCount];
3420 }
3421 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3422 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3423 }
3424 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3425 if ( empty( $head[$headlineCount] ) ) {
3426 $head[$headlineCount] = '';
3427 }
3428 if( $istemplate )
3429 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3430 else
3431 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3432 }
3433
3434 # give headline the correct <h#> tag
3435 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3436
3437 $headlineCount++;
3438 if( !$istemplate )
3439 $sectionCount++;
3440 }
3441
3442 if( $enoughToc ) {
3443 if( $toclevel<$wgMaxTocLevel ) {
3444 $toc .= $sk->tocUnindent( $toclevel - 1 );
3445 }
3446 $toc = $sk->tocList( $toc );
3447 }
3448
3449 # split up and insert constructed headlines
3450
3451 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3452 $i = 0;
3453
3454 foreach( $blocks as $block ) {
3455 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3456 # This is the [edit] link that appears for the top block of text when
3457 # section editing is enabled
3458
3459 # Disabled because it broke block formatting
3460 # For example, a bullet point in the top line
3461 # $full .= $sk->editSectionLink(0);
3462 }
3463 $full .= $block;
3464 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3465 # Top anchor now in skin
3466 $full = $full.$toc;
3467 }
3468
3469 if( !empty( $head[$i] ) ) {
3470 $full .= $head[$i];
3471 }
3472 $i++;
3473 }
3474 if( $this->mForceTocPosition ) {
3475 return str_replace( '<!--MWTOC-->', $toc, $full );
3476 } else {
3477 return $full;
3478 }
3479 }
3480
3481 /**
3482 * Return an HTML link for the "ISBN 123456" text
3483 * @private
3484 */
3485 function magicISBN( $text ) {
3486 $fname = 'Parser::magicISBN';
3487 wfProfileIn( $fname );
3488
3489 $a = split( 'ISBN ', ' '.$text );
3490 if ( count ( $a ) < 2 ) {
3491 wfProfileOut( $fname );
3492 return $text;
3493 }
3494 $text = substr( array_shift( $a ), 1);
3495 $valid = '0123456789-Xx';
3496
3497 foreach ( $a as $x ) {
3498 # hack: don't replace inside thumbnail title/alt
3499 # attributes
3500 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3501 $text .= "ISBN $x";
3502 continue;
3503 }
3504
3505 $isbn = $blank = '' ;
3506 while ( ' ' == $x{0} ) {
3507 $blank .= ' ';
3508 $x = substr( $x, 1 );
3509 }
3510 if ( $x == '' ) { # blank isbn
3511 $text .= "ISBN $blank";
3512 continue;
3513 }
3514 while ( strstr( $valid, $x{0} ) != false ) {
3515 $isbn .= $x{0};
3516 $x = substr( $x, 1 );
3517 }
3518 $num = str_replace( '-', '', $isbn );
3519 $num = str_replace( ' ', '', $num );
3520 $num = str_replace( 'x', 'X', $num );
3521
3522 if ( '' == $num ) {
3523 $text .= "ISBN $blank$x";
3524 } else {
3525 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
3526 $text .= '<a href="' .
3527 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3528 "\" class=\"internal\">ISBN $isbn</a>";
3529 $text .= $x;
3530 }
3531 }
3532 wfProfileOut( $fname );
3533 return $text;
3534 }
3535
3536 /**
3537 * Return an HTML link for the "RFC 1234" text
3538 *
3539 * @private
3540 * @param string $text Text to be processed
3541 * @param string $keyword Magic keyword to use (default RFC)
3542 * @param string $urlmsg Interface message to use (default rfcurl)
3543 * @return string
3544 */
3545 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3546
3547 $valid = '0123456789';
3548 $internal = false;
3549
3550 $a = split( $keyword, ' '.$text );
3551 if ( count ( $a ) < 2 ) {
3552 return $text;
3553 }
3554 $text = substr( array_shift( $a ), 1);
3555
3556 /* Check if keyword is preceed by [[.
3557 * This test is made here cause of the array_shift above
3558 * that prevent the test to be done in the foreach.
3559 */
3560 if ( substr( $text, -2 ) == '[[' ) {
3561 $internal = true;
3562 }
3563
3564 foreach ( $a as $x ) {
3565 /* token might be empty if we have RFC RFC 1234 */
3566 if ( $x=='' ) {
3567 $text.=$keyword;
3568 continue;
3569 }
3570
3571 # hack: don't replace inside thumbnail title/alt
3572 # attributes
3573 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3574 $text .= $keyword . $x;
3575 continue;
3576 }
3577
3578 $id = $blank = '' ;
3579
3580 /** remove and save whitespaces in $blank */
3581 while ( $x{0} == ' ' ) {
3582 $blank .= ' ';
3583 $x = substr( $x, 1 );
3584 }
3585
3586 /** remove and save the rfc number in $id */
3587 while ( strstr( $valid, $x{0} ) != false ) {
3588 $id .= $x{0};
3589 $x = substr( $x, 1 );
3590 }
3591
3592 if ( $id == '' ) {
3593 /* call back stripped spaces*/
3594 $text .= $keyword.$blank.$x;
3595 } elseif( $internal ) {
3596 /* normal link */
3597 $text .= $keyword.$id.$x;
3598 } else {
3599 /* build the external link*/
3600 $url = wfMsg( $urlmsg, $id);
3601 $sk =& $this->mOptions->getSkin();
3602 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3603 $text .= "<a href=\"{$url}\"{$la}>{$keyword}{$id}</a>{$x}";
3604 }
3605
3606 /* Check if the next RFC keyword is preceed by [[ */
3607 $internal = ( substr($x,-2) == '[[' );
3608 }
3609 return $text;
3610 }
3611
3612 /**
3613 * Transform wiki markup when saving a page by doing \r\n -> \n
3614 * conversion, substitting signatures, {{subst:}} templates, etc.
3615 *
3616 * @param string $text the text to transform
3617 * @param Title &$title the Title object for the current article
3618 * @param User &$user the User object describing the current user
3619 * @param ParserOptions $options parsing options
3620 * @param bool $clearState whether to clear the parser state first
3621 * @return string the altered wiki markup
3622 * @public
3623 */
3624 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3625 $this->mOptions = $options;
3626 $this->mTitle =& $title;
3627 $this->mOutputType = OT_WIKI;
3628
3629 if ( $clearState ) {
3630 $this->clearState();
3631 }
3632
3633 $stripState = false;
3634 $pairs = array(
3635 "\r\n" => "\n",
3636 );
3637 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3638 $text = $this->strip( $text, $stripState, true, array( 'gallery' ) );
3639 $text = $this->pstPass2( $text, $stripState, $user );
3640 $text = $this->unstrip( $text, $stripState );
3641 $text = $this->unstripNoWiki( $text, $stripState );
3642 return $text;
3643 }
3644
3645 /**
3646 * Pre-save transform helper function
3647 * @private
3648 */
3649 function pstPass2( $text, &$stripState, &$user ) {
3650 global $wgContLang, $wgLocaltimezone;
3651
3652 /* Note: This is the timestamp saved as hardcoded wikitext to
3653 * the database, we use $wgContLang here in order to give
3654 * everyone the same signature and use the default one rather
3655 * than the one selected in each user's preferences.
3656 */
3657 if ( isset( $wgLocaltimezone ) ) {
3658 $oldtz = getenv( 'TZ' );
3659 putenv( 'TZ='.$wgLocaltimezone );
3660 }
3661 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3662 ' (' . date( 'T' ) . ')';
3663 if ( isset( $wgLocaltimezone ) ) {
3664 putenv( 'TZ='.$oldtz );
3665 }
3666
3667 # Variable replacement
3668 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3669 $text = $this->replaceVariables( $text );
3670
3671 # Strip out <nowiki> etc. added via replaceVariables
3672 $text = $this->strip( $text, $stripState, false, array( 'gallery' ) );
3673
3674 # Signatures
3675 $sigText = $this->getUserSig( $user );
3676 $text = strtr( $text, array(
3677 '~~~~~' => $d,
3678 '~~~~' => "$sigText $d",
3679 '~~~' => $sigText
3680 ) );
3681
3682 # Context links: [[|name]] and [[name (context)|]]
3683 #
3684 global $wgLegalTitleChars;
3685 $tc = "[$wgLegalTitleChars]";
3686 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3687
3688 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3689 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3690
3691 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3692 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3693 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3694 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3695 $context = '';
3696 $t = $this->mTitle->getText();
3697 if ( preg_match( $conpat, $t, $m ) ) {
3698 $context = $m[2];
3699 }
3700 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3701 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3702 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3703
3704 if ( '' == $context ) {
3705 $text = preg_replace( $p2, '[[\\1]]', $text );
3706 } else {
3707 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3708 }
3709
3710 # Trim trailing whitespace
3711 # MAG_END (__END__) tag allows for trailing
3712 # whitespace to be deliberately included
3713 $text = rtrim( $text );
3714 $mw =& MagicWord::get( MAG_END );
3715 $mw->matchAndRemove( $text );
3716
3717 return $text;
3718 }
3719
3720 /**
3721 * Fetch the user's signature text, if any, and normalize to
3722 * validated, ready-to-insert wikitext.
3723 *
3724 * @param User $user
3725 * @return string
3726 * @private
3727 */
3728 function getUserSig( &$user ) {
3729 $username = $user->getName();
3730 $nickname = $user->getOption( 'nickname' );
3731 $nickname = $nickname === '' ? $username : $nickname;
3732
3733 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3734 # Sig. might contain markup; validate this
3735 if( $this->validateSig( $nickname ) !== false ) {
3736 # Validated; clean up (if needed) and return it
3737 return $this->cleanSig( $nickname, true );
3738 } else {
3739 # Failed to validate; fall back to the default
3740 $nickname = $username;
3741 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3742 }
3743 }
3744
3745 # If we're still here, make it a link to the user page
3746 $userpage = $user->getUserPage();
3747 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3748 }
3749
3750 /**
3751 * Check that the user's signature contains no bad XML
3752 *
3753 * @param string $text
3754 * @return mixed An expanded string, or false if invalid.
3755 */
3756 function validateSig( $text ) {
3757 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3758 }
3759
3760 /**
3761 * Clean up signature text
3762 *
3763 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3764 * 2) Substitute all transclusions
3765 *
3766 * @param string $text
3767 * @param $parsing Whether we're cleaning (preferences save) or parsing
3768 * @return string Signature text
3769 */
3770 function cleanSig( $text, $parsing = false ) {
3771 global $wgTitle;
3772 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI : OT_MSG );
3773
3774 $substWord = MagicWord::get( MAG_SUBST );
3775 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3776 $substText = '{{' . $substWord->getSynonym( 0 );
3777
3778 $text = preg_replace( $substRegex, $substText, $text );
3779 $text = preg_replace( '/~{3,5}/', '', $text );
3780 $text = $this->replaceVariables( $text );
3781
3782 $this->clearState();
3783 return $text;
3784 }
3785
3786 /**
3787 * Set up some variables which are usually set up in parse()
3788 * so that an external function can call some class members with confidence
3789 * @public
3790 */
3791 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3792 $this->mTitle =& $title;
3793 $this->mOptions = $options;
3794 $this->mOutputType = $outputType;
3795 if ( $clearState ) {
3796 $this->clearState();
3797 }
3798 }
3799
3800 /**
3801 * Transform a MediaWiki message by replacing magic variables.
3802 *
3803 * @param string $text the text to transform
3804 * @param ParserOptions $options options
3805 * @return string the text with variables substituted
3806 * @public
3807 */
3808 function transformMsg( $text, $options ) {
3809 global $wgTitle;
3810 static $executing = false;
3811
3812 $fname = "Parser::transformMsg";
3813
3814 # Guard against infinite recursion
3815 if ( $executing ) {
3816 return $text;
3817 }
3818 $executing = true;
3819
3820 wfProfileIn($fname);
3821
3822 $this->mTitle = $wgTitle;
3823 $this->mOptions = $options;
3824 $this->mOutputType = OT_MSG;
3825 $this->clearState();
3826 $text = $this->replaceVariables( $text );
3827
3828 $executing = false;
3829 wfProfileOut($fname);
3830 return $text;
3831 }
3832
3833 /**
3834 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3835 * The callback should have the following form:
3836 * function myParserHook( $text, $params, &$parser ) { ... }
3837 *
3838 * Transform and return $text. Use $parser for any required context, e.g. use
3839 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3840 *
3841 * @public
3842 *
3843 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3844 * @param mixed $callback The callback function (and object) to use for the tag
3845 *
3846 * @return The old value of the mTagHooks array associated with the hook
3847 */
3848 function setHook( $tag, $callback ) {
3849 $tag = strtolower( $tag );
3850 $oldVal = @$this->mTagHooks[$tag];
3851 $this->mTagHooks[$tag] = $callback;
3852
3853 return $oldVal;
3854 }
3855
3856 /**
3857 * Create a function, e.g. {{sum:1|2|3}}
3858 * The callback function should have the form:
3859 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3860 *
3861 * The callback may either return the text result of the function, or an array with the text
3862 * in element 0, and a number of flags in the other elements. The names of the flags are
3863 * specified in the keys. Valid flags are:
3864 * found The text returned is valid, stop processing the template. This
3865 * is on by default.
3866 * nowiki Wiki markup in the return value should be escaped
3867 * noparse Unsafe HTML tags should not be stripped, etc.
3868 * noargs Don't replace triple-brace arguments in the return value
3869 * isHTML The returned text is HTML, armour it against wikitext transformation
3870 *
3871 * @public
3872 *
3873 * @param string $name The function name. Function names are case-insensitive.
3874 * @param mixed $callback The callback function (and object) to use
3875 *
3876 * @return The old callback function for this name, if any
3877 */
3878 function setFunctionHook( $name, $callback ) {
3879 $name = strtolower( $name );
3880 $oldVal = @$this->mFunctionHooks[$name];
3881 $this->mFunctionHooks[$name] = $callback;
3882 return $oldVal;
3883 }
3884
3885 /**
3886 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3887 * Placeholders created in Skin::makeLinkObj()
3888 * Returns an array of links found, indexed by PDBK:
3889 * 0 - broken
3890 * 1 - normal link
3891 * 2 - stub
3892 * $options is a bit field, RLH_FOR_UPDATE to select for update
3893 */
3894 function replaceLinkHolders( &$text, $options = 0 ) {
3895 global $wgUser;
3896 global $wgOutputReplace;
3897
3898 $fname = 'Parser::replaceLinkHolders';
3899 wfProfileIn( $fname );
3900
3901 $pdbks = array();
3902 $colours = array();
3903 $sk =& $this->mOptions->getSkin();
3904 $linkCache =& LinkCache::singleton();
3905
3906 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3907 wfProfileIn( $fname.'-check' );
3908 $dbr =& wfGetDB( DB_SLAVE );
3909 $page = $dbr->tableName( 'page' );
3910 $threshold = $wgUser->getOption('stubthreshold');
3911
3912 # Sort by namespace
3913 asort( $this->mLinkHolders['namespaces'] );
3914
3915 # Generate query
3916 $query = false;
3917 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3918 # Make title object
3919 $title = $this->mLinkHolders['titles'][$key];
3920
3921 # Skip invalid entries.
3922 # Result will be ugly, but prevents crash.
3923 if ( is_null( $title ) ) {
3924 continue;
3925 }
3926 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3927
3928 # Check if it's a static known link, e.g. interwiki
3929 if ( $title->isAlwaysKnown() ) {
3930 $colours[$pdbk] = 1;
3931 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3932 $colours[$pdbk] = 1;
3933 $this->mOutput->addLink( $title, $id );
3934 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3935 $colours[$pdbk] = 0;
3936 } else {
3937 # Not in the link cache, add it to the query
3938 if ( !isset( $current ) ) {
3939 $current = $ns;
3940 $query = "SELECT page_id, page_namespace, page_title";
3941 if ( $threshold > 0 ) {
3942 $query .= ', page_len, page_is_redirect';
3943 }
3944 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3945 } elseif ( $current != $ns ) {
3946 $current = $ns;
3947 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3948 } else {
3949 $query .= ', ';
3950 }
3951
3952 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3953 }
3954 }
3955 if ( $query ) {
3956 $query .= '))';
3957 if ( $options & RLH_FOR_UPDATE ) {
3958 $query .= ' FOR UPDATE';
3959 }
3960
3961 $res = $dbr->query( $query, $fname );
3962
3963 # Fetch data and form into an associative array
3964 # non-existent = broken
3965 # 1 = known
3966 # 2 = stub
3967 while ( $s = $dbr->fetchObject($res) ) {
3968 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3969 $pdbk = $title->getPrefixedDBkey();
3970 $linkCache->addGoodLinkObj( $s->page_id, $title );
3971 $this->mOutput->addLink( $title, $s->page_id );
3972
3973 if ( $threshold > 0 ) {
3974 $size = $s->page_len;
3975 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3976 $colours[$pdbk] = 1;
3977 } else {
3978 $colours[$pdbk] = 2;
3979 }
3980 } else {
3981 $colours[$pdbk] = 1;
3982 }
3983 }
3984 }
3985 wfProfileOut( $fname.'-check' );
3986
3987 # Construct search and replace arrays
3988 wfProfileIn( $fname.'-construct' );
3989 $wgOutputReplace = array();
3990 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3991 $pdbk = $pdbks[$key];
3992 $searchkey = "<!--LINK $key-->";
3993 $title = $this->mLinkHolders['titles'][$key];
3994 if ( empty( $colours[$pdbk] ) ) {
3995 $linkCache->addBadLinkObj( $title );
3996 $colours[$pdbk] = 0;
3997 $this->mOutput->addLink( $title, 0 );
3998 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3999 $this->mLinkHolders['texts'][$key],
4000 $this->mLinkHolders['queries'][$key] );
4001 } elseif ( $colours[$pdbk] == 1 ) {
4002 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
4003 $this->mLinkHolders['texts'][$key],
4004 $this->mLinkHolders['queries'][$key] );
4005 } elseif ( $colours[$pdbk] == 2 ) {
4006 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
4007 $this->mLinkHolders['texts'][$key],
4008 $this->mLinkHolders['queries'][$key] );
4009 }
4010 }
4011 wfProfileOut( $fname.'-construct' );
4012
4013 # Do the thing
4014 wfProfileIn( $fname.'-replace' );
4015
4016 $text = preg_replace_callback(
4017 '/(<!--LINK .*?-->)/',
4018 "wfOutputReplaceMatches",
4019 $text);
4020
4021 wfProfileOut( $fname.'-replace' );
4022 }
4023
4024 # Now process interwiki link holders
4025 # This is quite a bit simpler than internal links
4026 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4027 wfProfileIn( $fname.'-interwiki' );
4028 # Make interwiki link HTML
4029 $wgOutputReplace = array();
4030 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4031 $title = $this->mInterwikiLinkHolders['titles'][$key];
4032 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
4033 }
4034
4035 $text = preg_replace_callback(
4036 '/<!--IWLINK (.*?)-->/',
4037 "wfOutputReplaceMatches",
4038 $text );
4039 wfProfileOut( $fname.'-interwiki' );
4040 }
4041
4042 wfProfileOut( $fname );
4043 return $colours;
4044 }
4045
4046 /**
4047 * Replace <!--LINK--> link placeholders with plain text of links
4048 * (not HTML-formatted).
4049 * @param string $text
4050 * @return string
4051 */
4052 function replaceLinkHoldersText( $text ) {
4053 $fname = 'Parser::replaceLinkHoldersText';
4054 wfProfileIn( $fname );
4055
4056 $text = preg_replace_callback(
4057 '/<!--(LINK|IWLINK) (.*?)-->/',
4058 array( &$this, 'replaceLinkHoldersTextCallback' ),
4059 $text );
4060
4061 wfProfileOut( $fname );
4062 return $text;
4063 }
4064
4065 /**
4066 * @param array $matches
4067 * @return string
4068 * @private
4069 */
4070 function replaceLinkHoldersTextCallback( $matches ) {
4071 $type = $matches[1];
4072 $key = $matches[2];
4073 if( $type == 'LINK' ) {
4074 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4075 return $this->mLinkHolders['texts'][$key];
4076 }
4077 } elseif( $type == 'IWLINK' ) {
4078 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4079 return $this->mInterwikiLinkHolders['texts'][$key];
4080 }
4081 }
4082 return $matches[0];
4083 }
4084
4085 /**
4086 * Tag hook handler for 'pre'.
4087 */
4088 function renderPreTag( $text, $attribs, $parser ) {
4089 // Backwards-compatibility hack
4090 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4091
4092 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4093 return wfOpenElement( 'pre', $attribs ) .
4094 wfEscapeHTMLTagsOnly( $content ) .
4095 '</pre>';
4096 }
4097
4098 /**
4099 * Renders an image gallery from a text with one line per image.
4100 * text labels may be given by using |-style alternative text. E.g.
4101 * Image:one.jpg|The number "1"
4102 * Image:tree.jpg|A tree
4103 * given as text will return the HTML of a gallery with two images,
4104 * labeled 'The number "1"' and
4105 * 'A tree'.
4106 */
4107 function renderImageGallery( $text ) {
4108 $ig = new ImageGallery();
4109 $ig->setShowBytes( false );
4110 $ig->setShowFilename( false );
4111 $ig->setParsing();
4112 $lines = explode( "\n", $text );
4113
4114 foreach ( $lines as $line ) {
4115 # match lines like these:
4116 # Image:someimage.jpg|This is some image
4117 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4118 # Skip empty lines
4119 if ( count( $matches ) == 0 ) {
4120 continue;
4121 }
4122 $nt =& Title::newFromText( $matches[1] );
4123 if( is_null( $nt ) ) {
4124 # Bogus title. Ignore these so we don't bomb out later.
4125 continue;
4126 }
4127 if ( isset( $matches[3] ) ) {
4128 $label = $matches[3];
4129 } else {
4130 $label = '';
4131 }
4132
4133 $pout = $this->parse( $label,
4134 $this->mTitle,
4135 $this->mOptions,
4136 false, // Strip whitespace...?
4137 false // Don't clear state!
4138 );
4139 $html = $pout->getText();
4140
4141 $ig->add( new Image( $nt ), $html );
4142
4143 # Only add real images (bug #5586)
4144 if ( $nt->getNamespace() == NS_IMAGE ) {
4145 $this->mOutput->addImage( $nt->getDBkey() );
4146 }
4147 }
4148 return $ig->toHTML();
4149 }
4150
4151 /**
4152 * Parse image options text and use it to make an image
4153 */
4154 function makeImage( &$nt, $options ) {
4155 global $wgUseImageResize;
4156
4157 $align = '';
4158
4159 # Check if the options text is of the form "options|alt text"
4160 # Options are:
4161 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4162 # * left no resizing, just left align. label is used for alt= only
4163 # * right same, but right aligned
4164 # * none same, but not aligned
4165 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4166 # * center center the image
4167 # * framed Keep original image size, no magnify-button.
4168
4169 $part = explode( '|', $options);
4170
4171 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
4172 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
4173 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
4174 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
4175 $mwNone =& MagicWord::get( MAG_IMG_NONE );
4176 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
4177 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
4178 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
4179 $caption = '';
4180
4181 $width = $height = $framed = $thumb = false;
4182 $manual_thumb = '' ;
4183
4184 foreach( $part as $key => $val ) {
4185 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4186 $thumb=true;
4187 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4188 # use manually specified thumbnail
4189 $thumb=true;
4190 $manual_thumb = $match;
4191 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4192 # remember to set an alignment, don't render immediately
4193 $align = 'right';
4194 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4195 # remember to set an alignment, don't render immediately
4196 $align = 'left';
4197 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4198 # remember to set an alignment, don't render immediately
4199 $align = 'center';
4200 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4201 # remember to set an alignment, don't render immediately
4202 $align = 'none';
4203 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4204 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4205 # $match is the image width in pixels
4206 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4207 $width = intval( $m[1] );
4208 $height = intval( $m[2] );
4209 } else {
4210 $width = intval($match);
4211 }
4212 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4213 $framed=true;
4214 } else {
4215 $caption = $val;
4216 }
4217 }
4218 # Strip bad stuff out of the alt text
4219 $alt = $this->replaceLinkHoldersText( $caption );
4220
4221 # make sure there are no placeholders in thumbnail attributes
4222 # that are later expanded to html- so expand them now and
4223 # remove the tags
4224 $alt = $this->unstrip($alt, $this->mStripState);
4225 $alt = Sanitizer::stripAllTags( $alt );
4226
4227 # Linker does the rest
4228 $sk =& $this->mOptions->getSkin();
4229 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4230 }
4231
4232 /**
4233 * Set a flag in the output object indicating that the content is dynamic and
4234 * shouldn't be cached.
4235 */
4236 function disableCache() {
4237 wfDebug( "Parser output marked as uncacheable.\n" );
4238 $this->mOutput->mCacheTime = -1;
4239 }
4240
4241 /**#@+
4242 * Callback from the Sanitizer for expanding items found in HTML attribute
4243 * values, so they can be safely tested and escaped.
4244 * @param string $text
4245 * @param array $args
4246 * @return string
4247 * @private
4248 */
4249 function attributeStripCallback( &$text, $args ) {
4250 $text = $this->replaceVariables( $text, $args );
4251 $text = $this->unstripForHTML( $text );
4252 return $text;
4253 }
4254
4255 function unstripForHTML( $text ) {
4256 $text = $this->unstrip( $text, $this->mStripState );
4257 $text = $this->unstripNoWiki( $text, $this->mStripState );
4258 return $text;
4259 }
4260 /**#@-*/
4261
4262 /**#@+
4263 * Accessor/mutator
4264 */
4265 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4266 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4267 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4268 /**#@-*/
4269
4270 /**#@+
4271 * Accessor
4272 */
4273 function getTags() { return array_keys( $this->mTagHooks ); }
4274 /**#@-*/
4275
4276
4277 /**
4278 * Break wikitext input into sections, and either pull or replace
4279 * some particular section's text.
4280 *
4281 * External callers should use the getSection and replaceSection methods.
4282 *
4283 * @param $text Page wikitext
4284 * @param $section Numbered section. 0 pulls the text before the first
4285 * heading; other numbers will pull the given section
4286 * along with its lower-level subsections.
4287 * @param $mode One of "get" or "replace"
4288 * @param $newtext Replacement text for section data.
4289 * @return string for "get", the extracted section text.
4290 * for "replace", the whole page with the section replaced.
4291 */
4292 private function extractSections( $text, $section, $mode, $newtext='' ) {
4293 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4294 # comments to be stripped as well)
4295 $striparray = array();
4296
4297 $oldOutputType = $this->mOutputType;
4298 $oldOptions = $this->mOptions;
4299 $this->mOptions = new ParserOptions();
4300 $this->mOutputType = OT_WIKI;
4301
4302 $striptext = $this->strip( $text, $striparray, true );
4303
4304 $this->mOutputType = $oldOutputType;
4305 $this->mOptions = $oldOptions;
4306
4307 # now that we can be sure that no pseudo-sections are in the source,
4308 # split it up by section
4309 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4310 $comment = "(?:$uniq-!--.*?QINU)";
4311 $secs = preg_split(
4312 /*
4313 "/
4314 ^(
4315 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4316 (?:
4317 (=+) # Should this be limited to 6?
4318 .+? # Section title...
4319 \\2 # Ending = count must match start
4320 |
4321 ^
4322 <h([1-6])\b.*?>
4323 .*?
4324 <\/h\\3\s*>
4325 )
4326 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4327 )$
4328 /mix",
4329 */
4330 "/
4331 (
4332 ^
4333 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4334 (=+) # Should this be limited to 6?
4335 .+? # Section title...
4336 \\2 # Ending = count must match start
4337 (?:$comment|<\/?noinclude>|[ \\t]+)* # Trailing whitespace ok
4338 $
4339 |
4340 <h([1-6])\b.*?>
4341 .*?
4342 <\/h\\3\s*>
4343 )
4344 /mix",
4345 $striptext, -1,
4346 PREG_SPLIT_DELIM_CAPTURE);
4347
4348 if( $mode == "get" ) {
4349 if( $section == 0 ) {
4350 // "Section 0" returns the content before any other section.
4351 $rv = $secs[0];
4352 } else {
4353 $rv = "";
4354 }
4355 } elseif( $mode == "replace" ) {
4356 if( $section == 0 ) {
4357 $rv = $newtext . "\n\n";
4358 $remainder = true;
4359 } else {
4360 $rv = $secs[0];
4361 $remainder = false;
4362 }
4363 }
4364 $count = 0;
4365 $sectionLevel = 0;
4366 for( $index = 1; $index < count( $secs ); ) {
4367 $headerLine = $secs[$index++];
4368 if( $secs[$index] ) {
4369 // A wiki header
4370 $headerLevel = strlen( $secs[$index++] );
4371 } else {
4372 // An HTML header
4373 $index++;
4374 $headerLevel = intval( $secs[$index++] );
4375 }
4376 $content = $secs[$index++];
4377
4378 $count++;
4379 if( $mode == "get" ) {
4380 if( $count == $section ) {
4381 $rv = $headerLine . $content;
4382 $sectionLevel = $headerLevel;
4383 } elseif( $count > $section ) {
4384 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4385 $rv .= $headerLine . $content;
4386 } else {
4387 // Broke out to a higher-level section
4388 break;
4389 }
4390 }
4391 } elseif( $mode == "replace" ) {
4392 if( $count < $section ) {
4393 $rv .= $headerLine . $content;
4394 } elseif( $count == $section ) {
4395 $rv .= $newtext . "\n\n";
4396 $sectionLevel = $headerLevel;
4397 } elseif( $count > $section ) {
4398 if( $headerLevel <= $sectionLevel ) {
4399 // Passed the section's sub-parts.
4400 $remainder = true;
4401 }
4402 if( $remainder ) {
4403 $rv .= $headerLine . $content;
4404 }
4405 }
4406 }
4407 }
4408 # reinsert stripped tags
4409 $rv = $this->unstrip( $rv, $striparray );
4410 $rv = $this->unstripNoWiki( $rv, $striparray );
4411 $rv = trim( $rv );
4412 return $rv;
4413 }
4414
4415 /**
4416 * This function returns the text of a section, specified by a number ($section).
4417 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4418 * the first section before any such heading (section 0).
4419 *
4420 * If a section contains subsections, these are also returned.
4421 *
4422 * @param $text String: text to look in
4423 * @param $section Integer: section number
4424 * @return string text of the requested section
4425 */
4426 function getSection( $text, $section ) {
4427 return $this->extractSections( $text, $section, "get" );
4428 }
4429
4430 function replaceSection( $oldtext, $section, $text ) {
4431 return $this->extractSections( $oldtext, $section, "replace", $text );
4432 }
4433
4434 }
4435
4436 /**
4437 * @todo document
4438 * @package MediaWiki
4439 */
4440 class ParserOutput
4441 {
4442 var $mText, # The output text
4443 $mLanguageLinks, # List of the full text of language links, in the order they appear
4444 $mCategories, # Map of category names to sort keys
4445 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4446 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4447 $mVersion, # Compatibility check
4448 $mTitleText, # title text of the chosen language variant
4449 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4450 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4451 $mImages, # DB keys of the images used, in the array key only
4452 $mExternalLinks, # External link URLs, in the key only
4453 $mHTMLtitle, # Display HTML title
4454 $mSubtitle, # Additional subtitle
4455 $mNewSection, # Show a new section link?
4456 $mNoGallery; # No gallery on category page? (__NOGALLERY__)
4457
4458 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4459 $containsOldMagic = false, $titletext = '' )
4460 {
4461 $this->mText = $text;
4462 $this->mLanguageLinks = $languageLinks;
4463 $this->mCategories = $categoryLinks;
4464 $this->mContainsOldMagic = $containsOldMagic;
4465 $this->mCacheTime = '';
4466 $this->mVersion = MW_PARSER_VERSION;
4467 $this->mTitleText = $titletext;
4468 $this->mLinks = array();
4469 $this->mTemplates = array();
4470 $this->mImages = array();
4471 $this->mExternalLinks = array();
4472 $this->mHTMLtitle = "" ;
4473 $this->mSubtitle = "" ;
4474 $this->mNewSection = false;
4475 $this->mNoGallery = false;
4476 }
4477
4478 function getText() { return $this->mText; }
4479 function &getLanguageLinks() { return $this->mLanguageLinks; }
4480 function getCategoryLinks() { return array_keys( $this->mCategories ); }
4481 function &getCategories() { return $this->mCategories; }
4482 function getCacheTime() { return $this->mCacheTime; }
4483 function getTitleText() { return $this->mTitleText; }
4484 function &getLinks() { return $this->mLinks; }
4485 function &getTemplates() { return $this->mTemplates; }
4486 function &getImages() { return $this->mImages; }
4487 function &getExternalLinks() { return $this->mExternalLinks; }
4488 function getNoGallery() { return $this->mNoGallery; }
4489
4490 function containsOldMagic() { return $this->mContainsOldMagic; }
4491 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
4492 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
4493 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
4494 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
4495 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
4496 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
4497
4498 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
4499 function addImage( $name ) { $this->mImages[$name] = 1; }
4500 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
4501 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
4502
4503 function setNewSection( $value ) {
4504 $this->mNewSection = (bool)$value;
4505 }
4506 function getNewSection() {
4507 return (bool)$this->mNewSection;
4508 }
4509
4510 function addLink( $title, $id ) {
4511 $ns = $title->getNamespace();
4512 $dbk = $title->getDBkey();
4513 if ( !isset( $this->mLinks[$ns] ) ) {
4514 $this->mLinks[$ns] = array();
4515 }
4516 $this->mLinks[$ns][$dbk] = $id;
4517 }
4518
4519 function addTemplate( $title, $id ) {
4520 $ns = $title->getNamespace();
4521 $dbk = $title->getDBkey();
4522 if ( !isset( $this->mTemplates[$ns] ) ) {
4523 $this->mTemplates[$ns] = array();
4524 }
4525 $this->mTemplates[$ns][$dbk] = $id;
4526 }
4527
4528 /**
4529 * Return true if this cached output object predates the global or
4530 * per-article cache invalidation timestamps, or if it comes from
4531 * an incompatible older version.
4532 *
4533 * @param string $touched the affected article's last touched timestamp
4534 * @return bool
4535 * @public
4536 */
4537 function expired( $touched ) {
4538 global $wgCacheEpoch;
4539 return $this->getCacheTime() == -1 || // parser says it's uncacheable
4540 $this->getCacheTime() < $touched ||
4541 $this->getCacheTime() <= $wgCacheEpoch ||
4542 !isset( $this->mVersion ) ||
4543 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
4544 }
4545 }
4546
4547 /**
4548 * Set options of the Parser
4549 * @todo document
4550 * @package MediaWiki
4551 */
4552 class ParserOptions
4553 {
4554 # All variables are private
4555 var $mUseTeX; # Use texvc to expand <math> tags
4556 var $mUseDynamicDates; # Use DateFormatter to format dates
4557 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4558 var $mAllowExternalImages; # Allow external images inline
4559 var $mAllowExternalImagesFrom; # If not, any exception?
4560 var $mSkin; # Reference to the preferred skin
4561 var $mDateFormat; # Date format index
4562 var $mEditSection; # Create "edit section" links
4563 var $mNumberHeadings; # Automatically number headings
4564 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4565 var $mTidy; # Ask for tidy cleanup
4566 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4567
4568 function getUseTeX() { return $this->mUseTeX; }
4569 function getUseDynamicDates() { return $this->mUseDynamicDates; }
4570 function getInterwikiMagic() { return $this->mInterwikiMagic; }
4571 function getAllowExternalImages() { return $this->mAllowExternalImages; }
4572 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
4573 function &getSkin() { return $this->mSkin; }
4574 function getDateFormat() { return $this->mDateFormat; }
4575 function getEditSection() { return $this->mEditSection; }
4576 function getNumberHeadings() { return $this->mNumberHeadings; }
4577 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
4578 function getTidy() { return $this->mTidy; }
4579 function getInterfaceMessage() { return $this->mInterfaceMessage; }
4580
4581 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
4582 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
4583 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
4584 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
4585 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
4586 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
4587 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
4588 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
4589 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
4590 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
4591 function setSkin( &$x ) { $this->mSkin =& $x; }
4592 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage, $x); }
4593
4594 function ParserOptions() {
4595 global $wgUser;
4596 $this->initialiseFromUser( $wgUser );
4597 }
4598
4599 /**
4600 * Get parser options
4601 * @static
4602 */
4603 function newFromUser( &$user ) {
4604 $popts = new ParserOptions;
4605 $popts->initialiseFromUser( $user );
4606 return $popts;
4607 }
4608
4609 /** Get user options */
4610 function initialiseFromUser( &$userInput ) {
4611 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4612 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4613 $fname = 'ParserOptions::initialiseFromUser';
4614 wfProfileIn( $fname );
4615 if ( !$userInput ) {
4616 $user = new User;
4617 $user->setLoaded( true );
4618 } else {
4619 $user =& $userInput;
4620 }
4621
4622 $this->mUseTeX = $wgUseTeX;
4623 $this->mUseDynamicDates = $wgUseDynamicDates;
4624 $this->mInterwikiMagic = $wgInterwikiMagic;
4625 $this->mAllowExternalImages = $wgAllowExternalImages;
4626 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
4627 wfProfileIn( $fname.'-skin' );
4628 $this->mSkin =& $user->getSkin();
4629 wfProfileOut( $fname.'-skin' );
4630 $this->mDateFormat = $user->getOption( 'date' );
4631 $this->mEditSection = true;
4632 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4633 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4634 $this->mTidy = false;
4635 $this->mInterfaceMessage = false;
4636 wfProfileOut( $fname );
4637 }
4638 }
4639
4640 /**
4641 * Callback function used by Parser::replaceLinkHolders()
4642 * to substitute link placeholders.
4643 */
4644 function &wfOutputReplaceMatches( $matches ) {
4645 global $wgOutputReplace;
4646 return $wgOutputReplace[$matches[1]];
4647 }
4648
4649 /**
4650 * Return the total number of articles
4651 */
4652 function wfNumberOfArticles() {
4653 global $wgNumberOfArticles;
4654
4655 wfLoadSiteStats();
4656 return $wgNumberOfArticles;
4657 }
4658
4659 /**
4660 * Return the number of files
4661 */
4662 function wfNumberOfFiles() {
4663 $fname = 'wfNumberOfFiles';
4664
4665 wfProfileIn( $fname );
4666 $dbr =& wfGetDB( DB_SLAVE );
4667 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4668 wfProfileOut( $fname );
4669
4670 return $numImages;
4671 }
4672
4673 /**
4674 * Return the number of user accounts
4675 * @return integer
4676 */
4677 function wfNumberOfUsers() {
4678 wfProfileIn( 'wfNumberOfUsers' );
4679 $dbr =& wfGetDB( DB_SLAVE );
4680 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4681 wfProfileOut( 'wfNumberOfUsers' );
4682 return (int)$count;
4683 }
4684
4685 /**
4686 * Return the total number of pages
4687 * @return integer
4688 */
4689 function wfNumberOfPages() {
4690 wfProfileIn( 'wfNumberOfPages' );
4691 $dbr =& wfGetDB( DB_SLAVE );
4692 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4693 wfProfileOut( 'wfNumberOfPages' );
4694 return (int)$count;
4695 }
4696
4697 /**
4698 * Return the total number of admins
4699 *
4700 * @return integer
4701 */
4702 function wfNumberOfAdmins() {
4703 static $admins = -1;
4704 wfProfileIn( 'wfNumberOfAdmins' );
4705 if( $admins == -1 ) {
4706 $dbr =& wfGetDB( DB_SLAVE );
4707 $admins = $dbr->selectField( 'user_groups', 'COUNT(*)', array( 'ug_group' => 'sysop' ), 'wfNumberOfAdmins' );
4708 }
4709 wfProfileOut( 'wfNumberOfAdmins' );
4710 return (int)$admins;
4711 }
4712
4713 /**
4714 * Count the number of pages in a particular namespace
4715 *
4716 * @param $ns Namespace
4717 * @return integer
4718 */
4719 function wfPagesInNs( $ns ) {
4720 static $pageCount = array();
4721 wfProfileIn( 'wfPagesInNs' );
4722 if( !isset( $pageCount[$ns] ) ) {
4723 $dbr =& wfGetDB( DB_SLAVE );
4724 $pageCount[$ns] = $dbr->selectField( 'page', 'COUNT(*)', array( 'page_namespace' => $ns ), 'wfPagesInNs' );
4725 }
4726 wfProfileOut( 'wfPagesInNs' );
4727 return (int)$pageCount[$ns];
4728 }
4729
4730 /**
4731 * Get various statistics from the database
4732 * @private
4733 */
4734 function wfLoadSiteStats() {
4735 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4736 $fname = 'wfLoadSiteStats';
4737
4738 if ( -1 != $wgNumberOfArticles ) return;
4739 $dbr =& wfGetDB( DB_SLAVE );
4740 $s = $dbr->selectRow( 'site_stats',
4741 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4742 array( 'ss_row_id' => 1 ), $fname
4743 );
4744
4745 if ( $s === false ) {
4746 return;
4747 } else {
4748 $wgTotalViews = $s->ss_total_views;
4749 $wgTotalEdits = $s->ss_total_edits;
4750 $wgNumberOfArticles = $s->ss_good_articles;
4751 }
4752 }
4753
4754 /**
4755 * Escape html tags
4756 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4757 *
4758 * @param $in String: text that might contain HTML tags.
4759 * @return string Escaped string
4760 */
4761 function wfEscapeHTMLTagsOnly( $in ) {
4762 return str_replace(
4763 array( '"', '>', '<' ),
4764 array( '&quot;', '&gt;', '&lt;' ),
4765 $in );
4766 }
4767
4768 ?>