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