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