Some more microoptimizations on the new definition list code. Now only about 4x slowe...
[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|<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)/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 $this->mTemplates[$piece['title']] = $text;
2922 $text = $linestart . $text;
2923 }
2924 }
2925 }
2926
2927 # Recursive parsing, escaping and link table handling
2928 # Only for HTML output
2929 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2930 $text = wfEscapeWikiText( $text );
2931 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found ) {
2932 if ( $noargs ) {
2933 $assocArgs = array();
2934 } else {
2935 # Clean up argument array
2936 $assocArgs = array();
2937 $index = 1;
2938 foreach( $args as $arg ) {
2939 $eqpos = strpos( $arg, '=' );
2940 if ( $eqpos === false ) {
2941 $assocArgs[$index++] = $arg;
2942 } else {
2943 $name = trim( substr( $arg, 0, $eqpos ) );
2944 $value = trim( substr( $arg, $eqpos+1 ) );
2945 if ( $value === false ) {
2946 $value = '';
2947 }
2948 if ( $name !== false ) {
2949 $assocArgs[$name] = $value;
2950 }
2951 }
2952 }
2953
2954 # Add a new element to the templace recursion path
2955 $this->mTemplatePath[$part1] = 1;
2956 }
2957
2958 if ( !$noparse ) {
2959 # If there are any <onlyinclude> tags, only include them
2960 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2961 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2962 $text = '';
2963 foreach ($m[1] as $piece)
2964 $text .= $piece;
2965 }
2966 # Remove <noinclude> sections and <includeonly> tags
2967 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2968 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2969
2970 if( $this->mOutputType == OT_HTML ) {
2971 # Strip <nowiki>, <pre>, etc.
2972 $text = $this->strip( $text, $this->mStripState );
2973 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2974 }
2975 $text = $this->replaceVariables( $text, $assocArgs );
2976
2977 # If the template begins with a table or block-level
2978 # element, it should be treated as beginning a new line.
2979 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2980 $text = "\n" . $text;
2981 }
2982 } elseif ( !$noargs ) {
2983 # $noparse and !$noargs
2984 # Just replace the arguments, not any double-brace items
2985 # This is used for rendered interwiki transclusion
2986 $text = $this->replaceVariables( $text, $assocArgs, true );
2987 }
2988 }
2989 # Prune lower levels off the recursion check path
2990 $this->mTemplatePath = $lastPathLevel;
2991
2992 if ( !$found ) {
2993 wfProfileOut( $fname );
2994 return $piece['text'];
2995 } else {
2996 if ( $isHTML ) {
2997 # Replace raw HTML by a placeholder
2998 # Add a blank line preceding, to prevent it from mucking up
2999 # immediately preceding headings
3000 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
3001 } else {
3002 # replace ==section headers==
3003 # XXX this needs to go away once we have a better parser.
3004 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
3005 if( !is_null( $title ) )
3006 $encodedname = base64_encode($title->getPrefixedDBkey());
3007 else
3008 $encodedname = base64_encode("");
3009 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
3010 PREG_SPLIT_DELIM_CAPTURE);
3011 $text = '';
3012 $nsec = 0;
3013 for( $i = 0; $i < count($m); $i += 2 ) {
3014 $text .= $m[$i];
3015 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
3016 $hl = $m[$i + 1];
3017 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
3018 $text .= $hl;
3019 continue;
3020 }
3021 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
3022 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
3023 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
3024
3025 $nsec++;
3026 }
3027 }
3028 }
3029 }
3030
3031 # Prune lower levels off the recursion check path
3032 $this->mTemplatePath = $lastPathLevel;
3033
3034 if ( !$found ) {
3035 wfProfileOut( $fname );
3036 return $piece['text'];
3037 } else {
3038 wfProfileOut( $fname );
3039 return $text;
3040 }
3041 }
3042
3043 /**
3044 * Fetch the unparsed text of a template and register a reference to it.
3045 */
3046 function fetchTemplate( $title ) {
3047 $text = false;
3048 // Loop to fetch the article, with up to 1 redirect
3049 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3050 $rev = Revision::newFromTitle( $title );
3051 $this->mOutput->addTemplate( $title, $title->getArticleID() );
3052 if ( !$rev ) {
3053 break;
3054 }
3055 $text = $rev->getText();
3056 if ( $text === false ) {
3057 break;
3058 }
3059 // Redirect?
3060 $title = Title::newFromRedirect( $text );
3061 }
3062 return $text;
3063 }
3064
3065 /**
3066 * Transclude an interwiki link.
3067 */
3068 function interwikiTransclude( $title, $action ) {
3069 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
3070
3071 if (!$wgEnableScaryTranscluding)
3072 return wfMsg('scarytranscludedisabled');
3073
3074 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
3075 // But we'll handle it generally anyway
3076 if ( $title->getNamespace() ) {
3077 // Use the canonical namespace, which should work anywhere
3078 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
3079 } else {
3080 $articleName = $title->getDBkey();
3081 }
3082
3083 $url = str_replace('$1', urlencode($articleName), Title::getInterwikiLink($title->getInterwiki()));
3084 $url .= "?action=$action";
3085 if (strlen($url) > 255)
3086 return wfMsg('scarytranscludetoolong');
3087 return $this->fetchScaryTemplateMaybeFromCache($url);
3088 }
3089
3090 function fetchScaryTemplateMaybeFromCache($url) {
3091 global $wgTranscludeCacheExpiry;
3092 $dbr =& wfGetDB(DB_SLAVE);
3093 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3094 array('tc_url' => $url));
3095 if ($obj) {
3096 $time = $obj->tc_time;
3097 $text = $obj->tc_contents;
3098 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3099 return $text;
3100 }
3101 }
3102
3103 $text = wfGetHTTP($url);
3104 if (!$text)
3105 return wfMsg('scarytranscludefailed', $url);
3106
3107 $dbw =& wfGetDB(DB_MASTER);
3108 $dbw->replace('transcache', array('tc_url'), array(
3109 'tc_url' => $url,
3110 'tc_time' => time(),
3111 'tc_contents' => $text));
3112 return $text;
3113 }
3114
3115
3116 /**
3117 * Triple brace replacement -- used for template arguments
3118 * @private
3119 */
3120 function argSubstitution( $matches ) {
3121 $arg = trim( $matches['title'] );
3122 $text = $matches['text'];
3123 $inputArgs = end( $this->mArgStack );
3124
3125 if ( array_key_exists( $arg, $inputArgs ) ) {
3126 $text = $inputArgs[$arg];
3127 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
3128 $text = $matches['parts'][0];
3129 }
3130
3131 return $text;
3132 }
3133
3134 /**
3135 * Returns true if the function is allowed to include this entity
3136 * @private
3137 */
3138 function incrementIncludeCount( $dbk ) {
3139 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
3140 $this->mIncludeCount[$dbk] = 0;
3141 }
3142 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
3143 return true;
3144 } else {
3145 return false;
3146 }
3147 }
3148
3149 /**
3150 * Detect __TOC__ magic word and set a placeholder
3151 */
3152 function stripToc( $text ) {
3153 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3154 # do not add TOC
3155 $mw = MagicWord::get( MAG_NOTOC );
3156 if( $mw->matchAndRemove( $text ) ) {
3157 $this->mShowToc = false;
3158 }
3159
3160 $mw = MagicWord::get( MAG_TOC );
3161 if( $mw->match( $text ) ) {
3162 $this->mShowToc = true;
3163 $this->mForceTocPosition = true;
3164
3165 // Set a placeholder. At the end we'll fill it in with the TOC.
3166 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3167
3168 // Only keep the first one.
3169 $text = $mw->replace( '', $text );
3170 }
3171 return $text;
3172 }
3173
3174 /**
3175 * This function accomplishes several tasks:
3176 * 1) Auto-number headings if that option is enabled
3177 * 2) Add an [edit] link to sections for logged in users who have enabled the option
3178 * 3) Add a Table of contents on the top for users who have enabled the option
3179 * 4) Auto-anchor headings
3180 *
3181 * It loops through all headlines, collects the necessary data, then splits up the
3182 * string and re-inserts the newly formatted headlines.
3183 *
3184 * @param string $text
3185 * @param boolean $isMain
3186 * @private
3187 */
3188 function formatHeadings( $text, $isMain=true ) {
3189 global $wgMaxTocLevel, $wgContLang;
3190
3191 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3192 if( !$this->mTitle->userCanEdit() ) {
3193 $showEditLink = 0;
3194 } else {
3195 $showEditLink = $this->mOptions->getEditSection();
3196 }
3197
3198 # Inhibit editsection links if requested in the page
3199 $esw =& MagicWord::get( MAG_NOEDITSECTION );
3200 if( $esw->matchAndRemove( $text ) ) {
3201 $showEditLink = 0;
3202 }
3203
3204 # Get all headlines for numbering them and adding funky stuff like [edit]
3205 # links - this is for later, but we need the number of headlines right now
3206 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
3207
3208 # if there are fewer than 4 headlines in the article, do not show TOC
3209 # unless it's been explicitly enabled.
3210 $enoughToc = $this->mShowToc &&
3211 (($numMatches >= 4) || $this->mForceTocPosition);
3212
3213 # Allow user to stipulate that a page should have a "new section"
3214 # link added via __NEWSECTIONLINK__
3215 $mw =& MagicWord::get( MAG_NEWSECTIONLINK );
3216 if( $mw->matchAndRemove( $text ) )
3217 $this->mOutput->setNewSection( true );
3218
3219 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3220 # override above conditions and always show TOC above first header
3221 $mw =& MagicWord::get( MAG_FORCETOC );
3222 if ($mw->matchAndRemove( $text ) ) {
3223 $this->mShowToc = true;
3224 $enoughToc = true;
3225 }
3226
3227 # Never ever show TOC if no headers
3228 if( $numMatches < 1 ) {
3229 $enoughToc = false;
3230 }
3231
3232 # We need this to perform operations on the HTML
3233 $sk =& $this->mOptions->getSkin();
3234
3235 # headline counter
3236 $headlineCount = 0;
3237 $sectionCount = 0; # headlineCount excluding template sections
3238
3239 # Ugh .. the TOC should have neat indentation levels which can be
3240 # passed to the skin functions. These are determined here
3241 $toc = '';
3242 $full = '';
3243 $head = array();
3244 $sublevelCount = array();
3245 $levelCount = array();
3246 $toclevel = 0;
3247 $level = 0;
3248 $prevlevel = 0;
3249 $toclevel = 0;
3250 $prevtoclevel = 0;
3251
3252 foreach( $matches[3] as $headline ) {
3253 $istemplate = 0;
3254 $templatetitle = '';
3255 $templatesection = 0;
3256 $numbering = '';
3257
3258 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
3259 $istemplate = 1;
3260 $templatetitle = base64_decode($mat[1]);
3261 $templatesection = 1 + (int)base64_decode($mat[2]);
3262 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
3263 }
3264
3265 if( $toclevel ) {
3266 $prevlevel = $level;
3267 $prevtoclevel = $toclevel;
3268 }
3269 $level = $matches[1][$headlineCount];
3270
3271 if( $doNumberHeadings || $enoughToc ) {
3272
3273 if ( $level > $prevlevel ) {
3274 # Increase TOC level
3275 $toclevel++;
3276 $sublevelCount[$toclevel] = 0;
3277 if( $toclevel<$wgMaxTocLevel ) {
3278 $toc .= $sk->tocIndent();
3279 }
3280 }
3281 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3282 # Decrease TOC level, find level to jump to
3283
3284 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3285 # Can only go down to level 1
3286 $toclevel = 1;
3287 } else {
3288 for ($i = $toclevel; $i > 0; $i--) {
3289 if ( $levelCount[$i] == $level ) {
3290 # Found last matching level
3291 $toclevel = $i;
3292 break;
3293 }
3294 elseif ( $levelCount[$i] < $level ) {
3295 # Found first matching level below current level
3296 $toclevel = $i + 1;
3297 break;
3298 }
3299 }
3300 }
3301 if( $toclevel<$wgMaxTocLevel ) {
3302 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3303 }
3304 }
3305 else {
3306 # No change in level, end TOC line
3307 if( $toclevel<$wgMaxTocLevel ) {
3308 $toc .= $sk->tocLineEnd();
3309 }
3310 }
3311
3312 $levelCount[$toclevel] = $level;
3313
3314 # count number of headlines for each level
3315 @$sublevelCount[$toclevel]++;
3316 $dot = 0;
3317 for( $i = 1; $i <= $toclevel; $i++ ) {
3318 if( !empty( $sublevelCount[$i] ) ) {
3319 if( $dot ) {
3320 $numbering .= '.';
3321 }
3322 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3323 $dot = 1;
3324 }
3325 }
3326 }
3327
3328 # The canonized header is a version of the header text safe to use for links
3329 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3330 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
3331 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
3332
3333 # Remove link placeholders by the link text.
3334 # <!--LINK number-->
3335 # turns into
3336 # link text with suffix
3337 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3338 "\$this->mLinkHolders['texts'][\$1]",
3339 $canonized_headline );
3340 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3341 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3342 $canonized_headline );
3343
3344 # strip out HTML
3345 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3346 $tocline = trim( $canonized_headline );
3347 # Save headline for section edit hint before it's escaped
3348 $headline_hint = trim( $canonized_headline );
3349 $canonized_headline = Sanitizer::escapeId( $tocline );
3350 $refers[$headlineCount] = $canonized_headline;
3351
3352 # count how many in assoc. array so we can track dupes in anchors
3353 @$refers[$canonized_headline]++;
3354 $refcount[$headlineCount]=$refers[$canonized_headline];
3355
3356 # Don't number the heading if it is the only one (looks silly)
3357 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3358 # the two are different if the line contains a link
3359 $headline=$numbering . ' ' . $headline;
3360 }
3361
3362 # Create the anchor for linking from the TOC to the section
3363 $anchor = $canonized_headline;
3364 if($refcount[$headlineCount] > 1 ) {
3365 $anchor .= '_' . $refcount[$headlineCount];
3366 }
3367 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3368 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3369 }
3370 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3371 if ( empty( $head[$headlineCount] ) ) {
3372 $head[$headlineCount] = '';
3373 }
3374 if( $istemplate )
3375 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3376 else
3377 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1, $headline_hint);
3378 }
3379
3380 # give headline the correct <h#> tag
3381 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3382
3383 $headlineCount++;
3384 if( !$istemplate )
3385 $sectionCount++;
3386 }
3387
3388 if( $enoughToc ) {
3389 if( $toclevel<$wgMaxTocLevel ) {
3390 $toc .= $sk->tocUnindent( $toclevel - 1 );
3391 }
3392 $toc = $sk->tocList( $toc );
3393 }
3394
3395 # split up and insert constructed headlines
3396
3397 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3398 $i = 0;
3399
3400 foreach( $blocks as $block ) {
3401 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3402 # This is the [edit] link that appears for the top block of text when
3403 # section editing is enabled
3404
3405 # Disabled because it broke block formatting
3406 # For example, a bullet point in the top line
3407 # $full .= $sk->editSectionLink(0);
3408 }
3409 $full .= $block;
3410 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3411 # Top anchor now in skin
3412 $full = $full.$toc;
3413 }
3414
3415 if( !empty( $head[$i] ) ) {
3416 $full .= $head[$i];
3417 }
3418 $i++;
3419 }
3420 if( $this->mForceTocPosition ) {
3421 return str_replace( '<!--MWTOC-->', $toc, $full );
3422 } else {
3423 return $full;
3424 }
3425 }
3426
3427 /**
3428 * Return an HTML link for the "ISBN 123456" text
3429 * @private
3430 */
3431 function magicISBN( $text ) {
3432 $fname = 'Parser::magicISBN';
3433 wfProfileIn( $fname );
3434
3435 $a = split( 'ISBN ', ' '.$text );
3436 if ( count ( $a ) < 2 ) {
3437 wfProfileOut( $fname );
3438 return $text;
3439 }
3440 $text = substr( array_shift( $a ), 1);
3441 $valid = '0123456789-Xx';
3442
3443 foreach ( $a as $x ) {
3444 # hack: don't replace inside thumbnail title/alt
3445 # attributes
3446 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3447 $text .= "ISBN $x";
3448 continue;
3449 }
3450
3451 $isbn = $blank = '' ;
3452 while ( ' ' == $x{0} ) {
3453 $blank .= ' ';
3454 $x = substr( $x, 1 );
3455 }
3456 if ( $x == '' ) { # blank isbn
3457 $text .= "ISBN $blank";
3458 continue;
3459 }
3460 while ( strstr( $valid, $x{0} ) != false ) {
3461 $isbn .= $x{0};
3462 $x = substr( $x, 1 );
3463 }
3464 $num = str_replace( '-', '', $isbn );
3465 $num = str_replace( ' ', '', $num );
3466 $num = str_replace( 'x', 'X', $num );
3467
3468 if ( '' == $num ) {
3469 $text .= "ISBN $blank$x";
3470 } else {
3471 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
3472 $text .= '<a href="' .
3473 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3474 "\" class=\"internal\">ISBN $isbn</a>";
3475 $text .= $x;
3476 }
3477 }
3478 wfProfileOut( $fname );
3479 return $text;
3480 }
3481
3482 /**
3483 * Return an HTML link for the "RFC 1234" text
3484 *
3485 * @private
3486 * @param string $text Text to be processed
3487 * @param string $keyword Magic keyword to use (default RFC)
3488 * @param string $urlmsg Interface message to use (default rfcurl)
3489 * @return string
3490 */
3491 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3492
3493 $valid = '0123456789';
3494 $internal = false;
3495
3496 $a = split( $keyword, ' '.$text );
3497 if ( count ( $a ) < 2 ) {
3498 return $text;
3499 }
3500 $text = substr( array_shift( $a ), 1);
3501
3502 /* Check if keyword is preceed by [[.
3503 * This test is made here cause of the array_shift above
3504 * that prevent the test to be done in the foreach.
3505 */
3506 if ( substr( $text, -2 ) == '[[' ) {
3507 $internal = true;
3508 }
3509
3510 foreach ( $a as $x ) {
3511 /* token might be empty if we have RFC RFC 1234 */
3512 if ( $x=='' ) {
3513 $text.=$keyword;
3514 continue;
3515 }
3516
3517 # hack: don't replace inside thumbnail title/alt
3518 # attributes
3519 if(preg_match('/<[^>]+(alt|title)="[^">]*$/', $text)) {
3520 $text .= $keyword . $x;
3521 continue;
3522 }
3523
3524 $id = $blank = '' ;
3525
3526 /** remove and save whitespaces in $blank */
3527 while ( $x{0} == ' ' ) {
3528 $blank .= ' ';
3529 $x = substr( $x, 1 );
3530 }
3531
3532 /** remove and save the rfc number in $id */
3533 while ( strstr( $valid, $x{0} ) != false ) {
3534 $id .= $x{0};
3535 $x = substr( $x, 1 );
3536 }
3537
3538 if ( $id == '' ) {
3539 /* call back stripped spaces*/
3540 $text .= $keyword.$blank.$x;
3541 } elseif( $internal ) {
3542 /* normal link */
3543 $text .= $keyword.$id.$x;
3544 } else {
3545 /* build the external link*/
3546 $url = wfMsg( $urlmsg, $id);
3547 $sk =& $this->mOptions->getSkin();
3548 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3549 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3550 }
3551
3552 /* Check if the next RFC keyword is preceed by [[ */
3553 $internal = ( substr($x,-2) == '[[' );
3554 }
3555 return $text;
3556 }
3557
3558 /**
3559 * Transform wiki markup when saving a page by doing \r\n -> \n
3560 * conversion, substitting signatures, {{subst:}} templates, etc.
3561 *
3562 * @param string $text the text to transform
3563 * @param Title &$title the Title object for the current article
3564 * @param User &$user the User object describing the current user
3565 * @param ParserOptions $options parsing options
3566 * @param bool $clearState whether to clear the parser state first
3567 * @return string the altered wiki markup
3568 * @public
3569 */
3570 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3571 $this->mOptions = $options;
3572 $this->mTitle =& $title;
3573 $this->mOutputType = OT_WIKI;
3574
3575 if ( $clearState ) {
3576 $this->clearState();
3577 }
3578
3579 $stripState = false;
3580 $pairs = array(
3581 "\r\n" => "\n",
3582 );
3583 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3584 $text = $this->strip( $text, $stripState, true );
3585 $text = $this->pstPass2( $text, $stripState, $user );
3586 $text = $this->unstrip( $text, $stripState );
3587 $text = $this->unstripNoWiki( $text, $stripState );
3588 return $text;
3589 }
3590
3591 /**
3592 * Pre-save transform helper function
3593 * @private
3594 */
3595 function pstPass2( $text, &$stripState, &$user ) {
3596 global $wgContLang, $wgLocaltimezone;
3597
3598 /* Note: This is the timestamp saved as hardcoded wikitext to
3599 * the database, we use $wgContLang here in order to give
3600 * everyone the same signature and use the default one rather
3601 * than the one selected in each user's preferences.
3602 */
3603 if ( isset( $wgLocaltimezone ) ) {
3604 $oldtz = getenv( 'TZ' );
3605 putenv( 'TZ='.$wgLocaltimezone );
3606 }
3607 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3608 ' (' . date( 'T' ) . ')';
3609 if ( isset( $wgLocaltimezone ) ) {
3610 putenv( 'TZ='.$oldtz );
3611 }
3612
3613 # Variable replacement
3614 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3615 $text = $this->replaceVariables( $text );
3616
3617 # Strip out <nowiki> etc. added via replaceVariables
3618 $text = $this->strip( $text, $stripState );
3619
3620 # Signatures
3621 $sigText = $this->getUserSig( $user );
3622 $text = strtr( $text, array(
3623 '~~~~~' => $d,
3624 '~~~~' => "$sigText $d",
3625 '~~~' => $sigText
3626 ) );
3627
3628 # Context links: [[|name]] and [[name (context)|]]
3629 #
3630 global $wgLegalTitleChars;
3631 $tc = "[$wgLegalTitleChars]";
3632 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3633
3634 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3635 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3636
3637 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3638 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3639 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3640 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3641 $context = '';
3642 $t = $this->mTitle->getText();
3643 if ( preg_match( $conpat, $t, $m ) ) {
3644 $context = $m[2];
3645 }
3646 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3647 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3648 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3649
3650 if ( '' == $context ) {
3651 $text = preg_replace( $p2, '[[\\1]]', $text );
3652 } else {
3653 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3654 }
3655
3656 # Trim trailing whitespace
3657 # MAG_END (__END__) tag allows for trailing
3658 # whitespace to be deliberately included
3659 $text = rtrim( $text );
3660 $mw =& MagicWord::get( MAG_END );
3661 $mw->matchAndRemove( $text );
3662
3663 return $text;
3664 }
3665
3666 /**
3667 * Fetch the user's signature text, if any, and normalize to
3668 * validated, ready-to-insert wikitext.
3669 *
3670 * @param User $user
3671 * @return string
3672 * @private
3673 */
3674 function getUserSig( &$user ) {
3675 $username = $user->getName();
3676 $nickname = $user->getOption( 'nickname' );
3677 $nickname = $nickname === '' ? $username : $nickname;
3678
3679 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3680 # Sig. might contain markup; validate this
3681 if( $this->validateSig( $nickname ) !== false ) {
3682 # Validated; clean up (if needed) and return it
3683 return $this->cleanSig( $nickname, true );
3684 } else {
3685 # Failed to validate; fall back to the default
3686 $nickname = $username;
3687 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3688 }
3689 }
3690
3691 # If we're still here, make it a link to the user page
3692 $userpage = $user->getUserPage();
3693 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3694 }
3695
3696 /**
3697 * Check that the user's signature contains no bad XML
3698 *
3699 * @param string $text
3700 * @return mixed An expanded string, or false if invalid.
3701 */
3702 function validateSig( $text ) {
3703 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3704 }
3705
3706 /**
3707 * Clean up signature text
3708 *
3709 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3710 * 2) Substitute all transclusions
3711 *
3712 * @param string $text
3713 * @param $parsing Whether we're cleaning (preferences save) or parsing
3714 * @return string Signature text
3715 */
3716 function cleanSig( $text, $parsing = false ) {
3717 global $wgTitle;
3718 $this->startExternalParse( $wgTitle, new ParserOptions(), $parsing ? OT_WIKI : OT_MSG );
3719
3720 $substWord = MagicWord::get( MAG_SUBST );
3721 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3722 $substText = '{{' . $substWord->getSynonym( 0 );
3723
3724 $text = preg_replace( $substRegex, $substText, $text );
3725 $text = preg_replace( '/~{3,5}/', '', $text );
3726 $text = $this->replaceVariables( $text );
3727
3728 $this->clearState();
3729 return $text;
3730 }
3731
3732 /**
3733 * Set up some variables which are usually set up in parse()
3734 * so that an external function can call some class members with confidence
3735 * @public
3736 */
3737 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3738 $this->mTitle =& $title;
3739 $this->mOptions = $options;
3740 $this->mOutputType = $outputType;
3741 if ( $clearState ) {
3742 $this->clearState();
3743 }
3744 }
3745
3746 /**
3747 * Transform a MediaWiki message by replacing magic variables.
3748 *
3749 * @param string $text the text to transform
3750 * @param ParserOptions $options options
3751 * @return string the text with variables substituted
3752 * @public
3753 */
3754 function transformMsg( $text, $options ) {
3755 global $wgTitle;
3756 static $executing = false;
3757
3758 $fname = "Parser::transformMsg";
3759
3760 # Guard against infinite recursion
3761 if ( $executing ) {
3762 return $text;
3763 }
3764 $executing = true;
3765
3766 wfProfileIn($fname);
3767
3768 $this->mTitle = $wgTitle;
3769 $this->mOptions = $options;
3770 $this->mOutputType = OT_MSG;
3771 $this->clearState();
3772 $text = $this->replaceVariables( $text );
3773
3774 $executing = false;
3775 wfProfileOut($fname);
3776 return $text;
3777 }
3778
3779 /**
3780 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3781 * The callback should have the following form:
3782 * function myParserHook( $text, $params, &$parser ) { ... }
3783 *
3784 * Transform and return $text. Use $parser for any required context, e.g. use
3785 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3786 *
3787 * @public
3788 *
3789 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3790 * @param mixed $callback The callback function (and object) to use for the tag
3791 *
3792 * @return The old value of the mTagHooks array associated with the hook
3793 */
3794 function setHook( $tag, $callback ) {
3795 $tag = strtolower( $tag );
3796 $oldVal = @$this->mTagHooks[$tag];
3797 $this->mTagHooks[$tag] = $callback;
3798
3799 return $oldVal;
3800 }
3801
3802 /**
3803 * Create a function, e.g. {{sum:1|2|3}}
3804 * The callback function should have the form:
3805 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3806 *
3807 * The callback may either return the text result of the function, or an array with the text
3808 * in element 0, and a number of flags in the other elements. The names of the flags are
3809 * specified in the keys. Valid flags are:
3810 * found The text returned is valid, stop processing the template. This
3811 * is on by default.
3812 * nowiki Wiki markup in the return value should be escaped
3813 * noparse Unsafe HTML tags should not be stripped, etc.
3814 * noargs Don't replace triple-brace arguments in the return value
3815 * isHTML The returned text is HTML, armour it against wikitext transformation
3816 *
3817 * @public
3818 *
3819 * @param string $name The function name. Function names are case-insensitive.
3820 * @param mixed $callback The callback function (and object) to use
3821 *
3822 * @return The old callback function for this name, if any
3823 */
3824 function setFunctionHook( $name, $callback ) {
3825 $name = strtolower( $name );
3826 $oldVal = @$this->mFunctionHooks[$name];
3827 $this->mFunctionHooks[$name] = $callback;
3828 return $oldVal;
3829 }
3830
3831 /**
3832 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3833 * Placeholders created in Skin::makeLinkObj()
3834 * Returns an array of links found, indexed by PDBK:
3835 * 0 - broken
3836 * 1 - normal link
3837 * 2 - stub
3838 * $options is a bit field, RLH_FOR_UPDATE to select for update
3839 */
3840 function replaceLinkHolders( &$text, $options = 0 ) {
3841 global $wgUser;
3842 global $wgOutputReplace;
3843
3844 $fname = 'Parser::replaceLinkHolders';
3845 wfProfileIn( $fname );
3846
3847 $pdbks = array();
3848 $colours = array();
3849 $sk =& $this->mOptions->getSkin();
3850 $linkCache =& LinkCache::singleton();
3851
3852 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3853 wfProfileIn( $fname.'-check' );
3854 $dbr =& wfGetDB( DB_SLAVE );
3855 $page = $dbr->tableName( 'page' );
3856 $threshold = $wgUser->getOption('stubthreshold');
3857
3858 # Sort by namespace
3859 asort( $this->mLinkHolders['namespaces'] );
3860
3861 # Generate query
3862 $query = false;
3863 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3864 # Make title object
3865 $title = $this->mLinkHolders['titles'][$key];
3866
3867 # Skip invalid entries.
3868 # Result will be ugly, but prevents crash.
3869 if ( is_null( $title ) ) {
3870 continue;
3871 }
3872 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3873
3874 # Check if it's a static known link, e.g. interwiki
3875 if ( $title->isAlwaysKnown() ) {
3876 $colours[$pdbk] = 1;
3877 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3878 $colours[$pdbk] = 1;
3879 $this->mOutput->addLink( $title, $id );
3880 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3881 $colours[$pdbk] = 0;
3882 } else {
3883 # Not in the link cache, add it to the query
3884 if ( !isset( $current ) ) {
3885 $current = $ns;
3886 $query = "SELECT page_id, page_namespace, page_title";
3887 if ( $threshold > 0 ) {
3888 $query .= ', page_len, page_is_redirect';
3889 }
3890 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3891 } elseif ( $current != $ns ) {
3892 $current = $ns;
3893 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3894 } else {
3895 $query .= ', ';
3896 }
3897
3898 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3899 }
3900 }
3901 if ( $query ) {
3902 $query .= '))';
3903 if ( $options & RLH_FOR_UPDATE ) {
3904 $query .= ' FOR UPDATE';
3905 }
3906
3907 $res = $dbr->query( $query, $fname );
3908
3909 # Fetch data and form into an associative array
3910 # non-existent = broken
3911 # 1 = known
3912 # 2 = stub
3913 while ( $s = $dbr->fetchObject($res) ) {
3914 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3915 $pdbk = $title->getPrefixedDBkey();
3916 $linkCache->addGoodLinkObj( $s->page_id, $title );
3917 $this->mOutput->addLink( $title, $s->page_id );
3918
3919 if ( $threshold > 0 ) {
3920 $size = $s->page_len;
3921 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3922 $colours[$pdbk] = 1;
3923 } else {
3924 $colours[$pdbk] = 2;
3925 }
3926 } else {
3927 $colours[$pdbk] = 1;
3928 }
3929 }
3930 }
3931 wfProfileOut( $fname.'-check' );
3932
3933 # Construct search and replace arrays
3934 wfProfileIn( $fname.'-construct' );
3935 $wgOutputReplace = array();
3936 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3937 $pdbk = $pdbks[$key];
3938 $searchkey = "<!--LINK $key-->";
3939 $title = $this->mLinkHolders['titles'][$key];
3940 if ( empty( $colours[$pdbk] ) ) {
3941 $linkCache->addBadLinkObj( $title );
3942 $colours[$pdbk] = 0;
3943 $this->mOutput->addLink( $title, 0 );
3944 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3945 $this->mLinkHolders['texts'][$key],
3946 $this->mLinkHolders['queries'][$key] );
3947 } elseif ( $colours[$pdbk] == 1 ) {
3948 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3949 $this->mLinkHolders['texts'][$key],
3950 $this->mLinkHolders['queries'][$key] );
3951 } elseif ( $colours[$pdbk] == 2 ) {
3952 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3953 $this->mLinkHolders['texts'][$key],
3954 $this->mLinkHolders['queries'][$key] );
3955 }
3956 }
3957 wfProfileOut( $fname.'-construct' );
3958
3959 # Do the thing
3960 wfProfileIn( $fname.'-replace' );
3961
3962 $text = preg_replace_callback(
3963 '/(<!--LINK .*?-->)/',
3964 "wfOutputReplaceMatches",
3965 $text);
3966
3967 wfProfileOut( $fname.'-replace' );
3968 }
3969
3970 # Now process interwiki link holders
3971 # This is quite a bit simpler than internal links
3972 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3973 wfProfileIn( $fname.'-interwiki' );
3974 # Make interwiki link HTML
3975 $wgOutputReplace = array();
3976 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3977 $title = $this->mInterwikiLinkHolders['titles'][$key];
3978 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3979 }
3980
3981 $text = preg_replace_callback(
3982 '/<!--IWLINK (.*?)-->/',
3983 "wfOutputReplaceMatches",
3984 $text );
3985 wfProfileOut( $fname.'-interwiki' );
3986 }
3987
3988 wfProfileOut( $fname );
3989 return $colours;
3990 }
3991
3992 /**
3993 * Replace <!--LINK--> link placeholders with plain text of links
3994 * (not HTML-formatted).
3995 * @param string $text
3996 * @return string
3997 */
3998 function replaceLinkHoldersText( $text ) {
3999 $fname = 'Parser::replaceLinkHoldersText';
4000 wfProfileIn( $fname );
4001
4002 $text = preg_replace_callback(
4003 '/<!--(LINK|IWLINK) (.*?)-->/',
4004 array( &$this, 'replaceLinkHoldersTextCallback' ),
4005 $text );
4006
4007 wfProfileOut( $fname );
4008 return $text;
4009 }
4010
4011 /**
4012 * @param array $matches
4013 * @return string
4014 * @private
4015 */
4016 function replaceLinkHoldersTextCallback( $matches ) {
4017 $type = $matches[1];
4018 $key = $matches[2];
4019 if( $type == 'LINK' ) {
4020 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4021 return $this->mLinkHolders['texts'][$key];
4022 }
4023 } elseif( $type == 'IWLINK' ) {
4024 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4025 return $this->mInterwikiLinkHolders['texts'][$key];
4026 }
4027 }
4028 return $matches[0];
4029 }
4030
4031 /**
4032 * Renders an image gallery from a text with one line per image.
4033 * text labels may be given by using |-style alternative text. E.g.
4034 * Image:one.jpg|The number "1"
4035 * Image:tree.jpg|A tree
4036 * given as text will return the HTML of a gallery with two images,
4037 * labeled 'The number "1"' and
4038 * 'A tree'.
4039 */
4040 function renderImageGallery( $text ) {
4041 $ig = new ImageGallery();
4042 $ig->setShowBytes( false );
4043 $ig->setShowFilename( false );
4044 $ig->setParsing();
4045 $lines = explode( "\n", $text );
4046
4047 foreach ( $lines as $line ) {
4048 # match lines like these:
4049 # Image:someimage.jpg|This is some image
4050 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4051 # Skip empty lines
4052 if ( count( $matches ) == 0 ) {
4053 continue;
4054 }
4055 $nt =& Title::newFromText( $matches[1] );
4056 if( is_null( $nt ) ) {
4057 # Bogus title. Ignore these so we don't bomb out later.
4058 continue;
4059 }
4060 if ( isset( $matches[3] ) ) {
4061 $label = $matches[3];
4062 } else {
4063 $label = '';
4064 }
4065
4066 $pout = $this->parse( $label,
4067 $this->mTitle,
4068 $this->mOptions,
4069 false, // Strip whitespace...?
4070 false // Don't clear state!
4071 );
4072 $html = $pout->getText();
4073
4074 $ig->add( new Image( $nt ), $html );
4075
4076 # Only add real images (bug #5586)
4077 if ( $nt->getNamespace() == NS_IMAGE ) {
4078 $this->mOutput->addImage( $nt->getDBkey() );
4079 }
4080 }
4081 return $ig->toHTML();
4082 }
4083
4084 /**
4085 * Parse image options text and use it to make an image
4086 */
4087 function makeImage( &$nt, $options ) {
4088 global $wgUseImageResize;
4089
4090 $align = '';
4091
4092 # Check if the options text is of the form "options|alt text"
4093 # Options are:
4094 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4095 # * left no resizing, just left align. label is used for alt= only
4096 # * right same, but right aligned
4097 # * none same, but not aligned
4098 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4099 # * center center the image
4100 # * framed Keep original image size, no magnify-button.
4101
4102 $part = explode( '|', $options);
4103
4104 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
4105 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
4106 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
4107 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
4108 $mwNone =& MagicWord::get( MAG_IMG_NONE );
4109 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
4110 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
4111 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
4112 $caption = '';
4113
4114 $width = $height = $framed = $thumb = false;
4115 $manual_thumb = '' ;
4116
4117 foreach( $part as $key => $val ) {
4118 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4119 $thumb=true;
4120 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4121 # use manually specified thumbnail
4122 $thumb=true;
4123 $manual_thumb = $match;
4124 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4125 # remember to set an alignment, don't render immediately
4126 $align = 'right';
4127 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4128 # remember to set an alignment, don't render immediately
4129 $align = 'left';
4130 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4131 # remember to set an alignment, don't render immediately
4132 $align = 'center';
4133 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4134 # remember to set an alignment, don't render immediately
4135 $align = 'none';
4136 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4137 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4138 # $match is the image width in pixels
4139 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4140 $width = intval( $m[1] );
4141 $height = intval( $m[2] );
4142 } else {
4143 $width = intval($match);
4144 }
4145 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4146 $framed=true;
4147 } else {
4148 $caption = $val;
4149 }
4150 }
4151 # Strip bad stuff out of the alt text
4152 $alt = $this->replaceLinkHoldersText( $caption );
4153
4154 # make sure there are no placeholders in thumbnail attributes
4155 # that are later expanded to html- so expand them now and
4156 # remove the tags
4157 $alt = $this->unstrip($alt, $this->mStripState);
4158 $alt = Sanitizer::stripAllTags( $alt );
4159
4160 # Linker does the rest
4161 $sk =& $this->mOptions->getSkin();
4162 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4163 }
4164
4165 /**
4166 * Set a flag in the output object indicating that the content is dynamic and
4167 * shouldn't be cached.
4168 */
4169 function disableCache() {
4170 wfDebug( "Parser output marked as uncacheable.\n" );
4171 $this->mOutput->mCacheTime = -1;
4172 }
4173
4174 /**#@+
4175 * Callback from the Sanitizer for expanding items found in HTML attribute
4176 * values, so they can be safely tested and escaped.
4177 * @param string $text
4178 * @param array $args
4179 * @return string
4180 * @private
4181 */
4182 function attributeStripCallback( &$text, $args ) {
4183 $text = $this->replaceVariables( $text, $args );
4184 $text = $this->unstripForHTML( $text );
4185 return $text;
4186 }
4187
4188 function unstripForHTML( $text ) {
4189 $text = $this->unstrip( $text, $this->mStripState );
4190 $text = $this->unstripNoWiki( $text, $this->mStripState );
4191 return $text;
4192 }
4193 /**#@-*/
4194
4195 /**#@+
4196 * Accessor/mutator
4197 */
4198 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4199 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4200 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4201 /**#@-*/
4202
4203 /**#@+
4204 * Accessor
4205 */
4206 function getTags() { return array_keys( $this->mTagHooks ); }
4207 /**#@-*/
4208 }
4209
4210 /**
4211 * @todo document
4212 * @package MediaWiki
4213 */
4214 class ParserOutput
4215 {
4216 var $mText, # The output text
4217 $mLanguageLinks, # List of the full text of language links, in the order they appear
4218 $mCategories, # Map of category names to sort keys
4219 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4220 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4221 $mVersion, # Compatibility check
4222 $mTitleText, # title text of the chosen language variant
4223 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4224 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4225 $mImages, # DB keys of the images used, in the array key only
4226 $mExternalLinks, # External link URLs, in the key only
4227 $mHTMLtitle, # Display HTML title
4228 $mSubtitle, # Additional subtitle
4229 $mNewSection; # Show a new section link?
4230
4231 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4232 $containsOldMagic = false, $titletext = '' )
4233 {
4234 $this->mText = $text;
4235 $this->mLanguageLinks = $languageLinks;
4236 $this->mCategories = $categoryLinks;
4237 $this->mContainsOldMagic = $containsOldMagic;
4238 $this->mCacheTime = '';
4239 $this->mVersion = MW_PARSER_VERSION;
4240 $this->mTitleText = $titletext;
4241 $this->mLinks = array();
4242 $this->mTemplates = array();
4243 $this->mImages = array();
4244 $this->mExternalLinks = array();
4245 $this->mHTMLtitle = "" ;
4246 $this->mSubtitle = "" ;
4247 $this->mNewSection = false;
4248 }
4249
4250 function getText() { return $this->mText; }
4251 function &getLanguageLinks() { return $this->mLanguageLinks; }
4252 function getCategoryLinks() { return array_keys( $this->mCategories ); }
4253 function &getCategories() { return $this->mCategories; }
4254 function getCacheTime() { return $this->mCacheTime; }
4255 function getTitleText() { return $this->mTitleText; }
4256 function &getLinks() { return $this->mLinks; }
4257 function &getTemplates() { return $this->mTemplates; }
4258 function &getImages() { return $this->mImages; }
4259 function &getExternalLinks() { return $this->mExternalLinks; }
4260
4261 function containsOldMagic() { return $this->mContainsOldMagic; }
4262 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
4263 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
4264 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
4265 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
4266 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
4267 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
4268
4269 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
4270 function addImage( $name ) { $this->mImages[$name] = 1; }
4271 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
4272 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
4273
4274 function setNewSection( $value ) {
4275 $this->mNewSection = (bool)$value;
4276 }
4277 function getNewSection() {
4278 return (bool)$this->mNewSection;
4279 }
4280
4281 function addLink( $title, $id ) {
4282 $ns = $title->getNamespace();
4283 $dbk = $title->getDBkey();
4284 if ( !isset( $this->mLinks[$ns] ) ) {
4285 $this->mLinks[$ns] = array();
4286 }
4287 $this->mLinks[$ns][$dbk] = $id;
4288 }
4289
4290 function addTemplate( $title, $id ) {
4291 $ns = $title->getNamespace();
4292 $dbk = $title->getDBkey();
4293 if ( !isset( $this->mTemplates[$ns] ) ) {
4294 $this->mTemplates[$ns] = array();
4295 }
4296 $this->mTemplates[$ns][$dbk] = $id;
4297 }
4298
4299 /**
4300 * Return true if this cached output object predates the global or
4301 * per-article cache invalidation timestamps, or if it comes from
4302 * an incompatible older version.
4303 *
4304 * @param string $touched the affected article's last touched timestamp
4305 * @return bool
4306 * @public
4307 */
4308 function expired( $touched ) {
4309 global $wgCacheEpoch;
4310 return $this->getCacheTime() == -1 || // parser says it's uncacheable
4311 $this->getCacheTime() < $touched ||
4312 $this->getCacheTime() <= $wgCacheEpoch ||
4313 !isset( $this->mVersion ) ||
4314 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
4315 }
4316 }
4317
4318 /**
4319 * Set options of the Parser
4320 * @todo document
4321 * @package MediaWiki
4322 */
4323 class ParserOptions
4324 {
4325 # All variables are private
4326 var $mUseTeX; # Use texvc to expand <math> tags
4327 var $mUseDynamicDates; # Use DateFormatter to format dates
4328 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4329 var $mAllowExternalImages; # Allow external images inline
4330 var $mAllowExternalImagesFrom; # If not, any exception?
4331 var $mSkin; # Reference to the preferred skin
4332 var $mDateFormat; # Date format index
4333 var $mEditSection; # Create "edit section" links
4334 var $mNumberHeadings; # Automatically number headings
4335 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4336 var $mTidy; # Ask for tidy cleanup
4337 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4338
4339 function getUseTeX() { return $this->mUseTeX; }
4340 function getUseDynamicDates() { return $this->mUseDynamicDates; }
4341 function getInterwikiMagic() { return $this->mInterwikiMagic; }
4342 function getAllowExternalImages() { return $this->mAllowExternalImages; }
4343 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
4344 function &getSkin() { return $this->mSkin; }
4345 function getDateFormat() { return $this->mDateFormat; }
4346 function getEditSection() { return $this->mEditSection; }
4347 function getNumberHeadings() { return $this->mNumberHeadings; }
4348 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
4349 function getTidy() { return $this->mTidy; }
4350 function getInterfaceMessage() { return $this->mInterfaceMessage; }
4351
4352 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
4353 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
4354 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
4355 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
4356 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
4357 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
4358 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
4359 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
4360 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
4361 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
4362 function setSkin( &$x ) { $this->mSkin =& $x; }
4363 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage, $x); }
4364
4365 function ParserOptions() {
4366 global $wgUser;
4367 $this->initialiseFromUser( $wgUser );
4368 }
4369
4370 /**
4371 * Get parser options
4372 * @static
4373 */
4374 function newFromUser( &$user ) {
4375 $popts = new ParserOptions;
4376 $popts->initialiseFromUser( $user );
4377 return $popts;
4378 }
4379
4380 /** Get user options */
4381 function initialiseFromUser( &$userInput ) {
4382 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4383 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4384 $fname = 'ParserOptions::initialiseFromUser';
4385 wfProfileIn( $fname );
4386 if ( !$userInput ) {
4387 $user = new User;
4388 $user->setLoaded( true );
4389 } else {
4390 $user =& $userInput;
4391 }
4392
4393 $this->mUseTeX = $wgUseTeX;
4394 $this->mUseDynamicDates = $wgUseDynamicDates;
4395 $this->mInterwikiMagic = $wgInterwikiMagic;
4396 $this->mAllowExternalImages = $wgAllowExternalImages;
4397 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
4398 wfProfileIn( $fname.'-skin' );
4399 $this->mSkin =& $user->getSkin();
4400 wfProfileOut( $fname.'-skin' );
4401 $this->mDateFormat = $user->getOption( 'date' );
4402 $this->mEditSection = true;
4403 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4404 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4405 $this->mTidy = false;
4406 $this->mInterfaceMessage = false;
4407 wfProfileOut( $fname );
4408 }
4409 }
4410
4411 /**
4412 * Callback function used by Parser::replaceLinkHolders()
4413 * to substitute link placeholders.
4414 */
4415 function &wfOutputReplaceMatches( $matches ) {
4416 global $wgOutputReplace;
4417 return $wgOutputReplace[$matches[1]];
4418 }
4419
4420 /**
4421 * Return the total number of articles
4422 */
4423 function wfNumberOfArticles() {
4424 global $wgNumberOfArticles;
4425
4426 wfLoadSiteStats();
4427 return $wgNumberOfArticles;
4428 }
4429
4430 /**
4431 * Return the number of files
4432 */
4433 function wfNumberOfFiles() {
4434 $fname = 'wfNumberOfFiles';
4435
4436 wfProfileIn( $fname );
4437 $dbr =& wfGetDB( DB_SLAVE );
4438 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4439 wfProfileOut( $fname );
4440
4441 return $numImages;
4442 }
4443
4444 /**
4445 * Return the number of user accounts
4446 * @return integer
4447 */
4448 function wfNumberOfUsers() {
4449 wfProfileIn( 'wfNumberOfUsers' );
4450 $dbr =& wfGetDB( DB_SLAVE );
4451 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4452 wfProfileOut( 'wfNumberOfUsers' );
4453 return (int)$count;
4454 }
4455
4456 /**
4457 * Return the total number of pages
4458 * @return integer
4459 */
4460 function wfNumberOfPages() {
4461 wfProfileIn( 'wfNumberOfPages' );
4462 $dbr =& wfGetDB( DB_SLAVE );
4463 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4464 wfProfileOut( 'wfNumberOfPages' );
4465 return (int)$count;
4466 }
4467
4468 /**
4469 * Get various statistics from the database
4470 * @private
4471 */
4472 function wfLoadSiteStats() {
4473 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4474 $fname = 'wfLoadSiteStats';
4475
4476 if ( -1 != $wgNumberOfArticles ) return;
4477 $dbr =& wfGetDB( DB_SLAVE );
4478 $s = $dbr->selectRow( 'site_stats',
4479 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4480 array( 'ss_row_id' => 1 ), $fname
4481 );
4482
4483 if ( $s === false ) {
4484 return;
4485 } else {
4486 $wgTotalViews = $s->ss_total_views;
4487 $wgTotalEdits = $s->ss_total_edits;
4488 $wgNumberOfArticles = $s->ss_good_articles;
4489 }
4490 }
4491
4492 /**
4493 * Escape html tags
4494 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4495 *
4496 * @param $in String: text that might contain HTML tags.
4497 * @return string Escaped string
4498 */
4499 function wfEscapeHTMLTagsOnly( $in ) {
4500 return str_replace(
4501 array( '"', '>', '<' ),
4502 array( '&quot;', '&gt;', '&lt;' ),
4503 $in );
4504 }
4505
4506 ?>