HTML normalization: use double-quotes on RFC and PMID quotes for consistency with...
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2 /**
3 * File for Parser and related classes
4 *
5 * @package MediaWiki
6 * @subpackage Parser
7 */
8
9 /** */
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
12
13 /**
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
17 */
18 define( 'MW_PARSER_VERSION', '1.6.1' );
19
20 /**
21 * Variable substitution O(N^2) attack
22 *
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
28 */
29
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32
33 define( 'RLH_FOR_UPDATE', 1 );
34
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
39
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
50 # Including space, but excluding newlines
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x0a\\x0d]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.
55 EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
56 define( 'EXT_IMAGE_REGEX',
57 '/^('.HTTP_PROTOCOLS.')'. # Protocol
58 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
59 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
60 );
61
62 // State constants for the definition list colon extraction
63 define( 'MW_COLON_STATE_TEXT', 0 );
64 define( 'MW_COLON_STATE_TAG', 1 );
65 define( 'MW_COLON_STATE_TAGSTART', 2 );
66 define( 'MW_COLON_STATE_CLOSETAG', 3 );
67 define( 'MW_COLON_STATE_TAGSLASH', 4 );
68 define( 'MW_COLON_STATE_COMMENT', 5 );
69 define( 'MW_COLON_STATE_COMMENTDASH', 6 );
70 define( 'MW_COLON_STATE_COMMENTDASHDASH', 7 );
71
72 /**
73 * PHP Parser
74 *
75 * Processes wiki markup
76 *
77 * <pre>
78 * There are three main entry points into the Parser class:
79 * parse()
80 * produces HTML output
81 * preSaveTransform().
82 * produces altered wiki markup.
83 * transformMsg()
84 * performs brace substitution on MediaWiki messages
85 *
86 * Globals used:
87 * objects: $wgLang, $wgContLang
88 *
89 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
90 *
91 * settings:
92 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
93 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
94 * $wgLocaltimezone, $wgAllowSpecialInclusion*
95 *
96 * * only within ParserOptions
97 * </pre>
98 *
99 * @package MediaWiki
100 */
101 class Parser
102 {
103 /**#@+
104 * @private
105 */
106 # Persistent:
107 var $mTagHooks, $mFunctionHooks;
108
109 # Cleared with clearState():
110 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
111 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
112 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
113 var $mTemplates, // cache of already loaded templates, avoids
114 // multiple SQL queries for the same string
115 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
116 // in this path. Used for loop detection.
117
118 # Temporary
119 # These are variables reset at least once per parse regardless of $clearState
120 var $mOptions, // ParserOptions object
121 $mTitle, // Title context, used for self-link rendering and similar things
122 $mOutputType, // Output type, one of the OT_xxx constants
123 $mRevisionId; // ID to display in {{REVISIONID}} tags
124
125 /**#@-*/
126
127 /**
128 * Constructor
129 *
130 * @public
131 */
132 function Parser() {
133 $this->mTagHooks = array();
134 $this->mFunctionHooks = array();
135 $this->clearState();
136 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
137 }
138
139 /**
140 * Clear Parser state
141 *
142 * @private
143 */
144 function clearState() {
145 $this->mOutput = new ParserOutput;
146 $this->mAutonumber = 0;
147 $this->mLastSection = '';
148 $this->mDTopen = false;
149 $this->mVariables = false;
150 $this->mIncludeCount = array();
151 $this->mStripState = array();
152 $this->mArgStack = array();
153 $this->mInPre = false;
154 $this->mInterwikiLinkHolders = array(
155 'texts' => array(),
156 'titles' => array()
157 );
158 $this->mLinkHolders = array(
159 'namespaces' => array(),
160 'dbkeys' => array(),
161 'queries' => array(),
162 'texts' => array(),
163 'titles' => array()
164 );
165 $this->mRevisionId = null;
166
167 /**
168 * Prefix for temporary replacement strings for the multipass parser.
169 * \x07 should never appear in input as it's disallowed in XML.
170 * Using it at the front also gives us a little extra robustness
171 * since it shouldn't match when butted up against identifier-like
172 * string constructs.
173 */
174 $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
175
176 # Clear these on every parse, bug 4549
177 $this->mTemplates = array();
178 $this->mTemplatePath = array();
179
180 $this->mShowToc = true;
181 $this->mForceTocPosition = false;
182
183 wfRunHooks( 'ParserClearState', array( &$this ) );
184 }
185
186 /**
187 * Accessor for mUniqPrefix.
188 *
189 * @public
190 */
191 function UniqPrefix() {
192 return $this->mUniqPrefix;
193 }
194
195 /**
196 * Convert wikitext to HTML
197 * Do not call this function recursively.
198 *
199 * @private
200 * @param string $text Text we want to parse
201 * @param Title &$title A title object
202 * @param array $options
203 * @param boolean $linestart
204 * @param boolean $clearState
205 * @param int $revid number to pass in {{REVISIONID}}
206 * @return ParserOutput a ParserOutput
207 */
208 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
209 /**
210 * First pass--just handle <nowiki> sections, pass the rest off
211 * to internalParse() which does all the real work.
212 */
213
214 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
215 $fname = 'Parser::parse';
216 wfProfileIn( $fname );
217
218 if ( $clearState ) {
219 $this->clearState();
220 }
221
222 $this->mOptions = $options;
223 $this->mTitle =& $title;
224 $this->mRevisionId = $revid;
225 $this->mOutputType = OT_HTML;
226
227 //$text = $this->strip( $text, $this->mStripState );
228 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
229 $x =& $this->mStripState;
230
231 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
232 $text = $this->strip( $text, $x );
233 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
234
235 # Hook to suspend the parser in this state
236 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
237 wfProfileOut( $fname );
238 return $text ;
239 }
240
241 $text = $this->internalParse( $text );
242
243 $text = $this->unstrip( $text, $this->mStripState );
244
245 # Clean up special characters, only run once, next-to-last before doBlockLevels
246 $fixtags = array(
247 # french spaces, last one Guillemet-left
248 # only if there is something before the space
249 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
250 # french spaces, Guillemet-right
251 '/(\\302\\253) /' => '\\1&nbsp;',
252 );
253 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
254
255 # only once and last
256 $text = $this->doBlockLevels( $text, $linestart );
257
258 $this->replaceLinkHolders( $text );
259
260 # the position of the parserConvert() call should not be changed. it
261 # assumes that the links are all replaced and the only thing left
262 # is the <nowiki> mark.
263 # Side-effects: this calls $this->mOutput->setTitleText()
264 $text = $wgContLang->parserConvert( $text, $this );
265
266 $text = $this->unstripNoWiki( $text, $this->mStripState );
267
268 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
269
270 $text = Sanitizer::normalizeCharReferences( $text );
271
272 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
273 $text = Parser::tidy($text);
274 } else {
275 # attempt to sanitize at least some nesting problems
276 # (bug #2702 and quite a few others)
277 $tidyregs = array(
278 # ''Something [http://www.cool.com cool''] -->
279 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
280 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
281 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
282 # fix up an anchor inside another anchor, only
283 # at least for a single single nested link (bug 3695)
284 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
285 '\\1\\2</a>\\3</a>\\1\\4</a>',
286 # fix div inside inline elements- doBlockLevels won't wrap a line which
287 # contains a div, so fix it up here; replace
288 # div with escaped text
289 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
290 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
291 # remove empty italic or bold tag pairs, some
292 # introduced by rules above
293 '/<([bi])><\/\\1>/' => ''
294 );
295
296 $text = preg_replace(
297 array_keys( $tidyregs ),
298 array_values( $tidyregs ),
299 $text );
300 }
301
302 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
303
304 $this->mOutput->setText( $text );
305 wfProfileOut( $fname );
306
307 return $this->mOutput;
308 }
309
310 /**
311 * Get a random string
312 *
313 * @private
314 * @static
315 */
316 function getRandomString() {
317 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
318 }
319
320 function &getTitle() { return $this->mTitle; }
321 function getOptions() { return $this->mOptions; }
322
323 /**
324 * Replaces all occurrences of HTML-style comments and the given tags
325 * in the text with a random marker and returns teh next text. The output
326 * parameter $matches will be an associative array filled with data in
327 * the form:
328 * 'UNIQ-xxxxx' => array(
329 * 'element',
330 * 'tag content',
331 * array( 'param' => 'x' ),
332 * '<element param="x">tag content</element>' ) )
333 *
334 * @param $elements list of element names. Comments are always extracted.
335 * @param $text Source text string.
336 * @param $uniq_prefix
337 *
338 * @private
339 * @static
340 */
341 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
342 $rand = Parser::getRandomString();
343 $n = 1;
344 $stripped = '';
345 $matches = array();
346
347 $taglist = implode( '|', $elements );
348 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
349
350 while ( '' != $text ) {
351 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
352 $stripped .= $p[0];
353 if( count( $p ) < 5 ) {
354 break;
355 }
356 if( count( $p ) > 5 ) {
357 // comment
358 $element = $p[4];
359 $attributes = '';
360 $close = '';
361 $inside = $p[5];
362 } else {
363 // tag
364 $element = $p[1];
365 $attributes = $p[2];
366 $close = $p[3];
367 $inside = $p[4];
368 }
369
370 $marker = "$uniq_prefix-$element-$rand" . sprintf('%08X', $n++) . '-QINU';
371 $stripped .= $marker;
372
373 if ( $close === '/>' ) {
374 // Empty element tag, <tag />
375 $content = null;
376 $text = $inside;
377 $tail = null;
378 } else {
379 if( $element == '!--' ) {
380 $end = '/(-->)/';
381 } else {
382 $end = "/(<\\/$element\\s*>)/i";
383 }
384 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
385 $content = $q[0];
386 if( count( $q ) < 3 ) {
387 # No end tag -- let it run out to the end of the text.
388 $tail = '';
389 $text = '';
390 } else {
391 $tail = $q[1];
392 $text = $q[2];
393 }
394 }
395
396 $matches[$marker] = array( $element,
397 $content,
398 Sanitizer::decodeTagAttributes( $attributes ),
399 "<$element$attributes$close$content$tail" );
400 }
401 return $stripped;
402 }
403
404 /**
405 * Strips and renders nowiki, pre, math, hiero
406 * If $render is set, performs necessary rendering operations on plugins
407 * Returns the text, and fills an array with data needed in unstrip()
408 * If the $state is already a valid strip state, it adds to the state
409 *
410 * @param bool $stripcomments when set, HTML comments <!-- like this -->
411 * will be stripped in addition to other tags. This is important
412 * for section editing, where these comments cause confusion when
413 * counting the sections in the wikisource
414 *
415 * @private
416 */
417 function strip( $text, &$state, $stripcomments = false ) {
418 $render = ($this->mOutputType == OT_HTML);
419
420 # Replace any instances of the placeholders
421 $uniq_prefix = $this->mUniqPrefix;
422 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
423 $commentState = array();
424
425 $elements = array_merge(
426 array( 'nowiki', 'gallery' ),
427 array_keys( $this->mTagHooks ) );
428 global $wgRawHtml;
429 if( $wgRawHtml ) {
430 $elements[] = 'html';
431 }
432 if( $this->mOptions->getUseTeX() ) {
433 $elements[] = 'math';
434 }
435
436
437 $matches = array();
438 $text = Parser::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
439
440 foreach( $matches as $marker => $data ) {
441 list( $element, $content, $params, $tag ) = $data;
442 if( $render ) {
443 $tagName = strtolower( $element );
444 switch( $tagName ) {
445 case '!--':
446 // Comment
447 if( substr( $tag, -3 ) == '-->' ) {
448 $output = $tag;
449 } else {
450 // Unclosed comment in input.
451 // Close it so later stripping can remove it
452 $output = "$tag-->";
453 }
454 break;
455 case 'html':
456 if( $wgRawHtml ) {
457 $output = $content;
458 break;
459 }
460 // Shouldn't happen otherwise. :)
461 case 'nowiki':
462 $output = wfEscapeHTMLTagsOnly( $content );
463 break;
464 case 'math':
465 $output = MathRenderer::renderMath( $content );
466 break;
467 case 'gallery':
468 $output = $this->renderImageGallery( $content );
469 break;
470 default:
471 if( isset( $this->mTagHooks[$tagName] ) ) {
472 $output = call_user_func_array( $this->mTagHooks[$tagName],
473 array( $content, $params, $this ) );
474 } else {
475 throw new MWException( "Invalid call hook $element" );
476 }
477 }
478 } else {
479 // Just stripping tags; keep the source
480 $output = $tag;
481 }
482 if( !$stripcomments && $element == '!--' ) {
483 $commentState[$marker] = $output;
484 } else {
485 $state[$element][$marker] = $output;
486 }
487 }
488
489 # Unstrip comments unless explicitly told otherwise.
490 # (The comments are always stripped prior to this point, so as to
491 # not invoke any extension tags / parser hooks contained within
492 # a comment.)
493 if ( !$stripcomments ) {
494 // Put them all back and forget them
495 $text = strtr( $text, $commentState );
496 }
497
498 return $text;
499 }
500
501 /**
502 * Restores pre, math, and other extensions removed by strip()
503 *
504 * always call unstripNoWiki() after this one
505 * @private
506 */
507 function unstrip( $text, &$state ) {
508 if ( !is_array( $state ) ) {
509 return $text;
510 }
511
512 $replacements = array();
513 foreach( $state as $tag => $contentDict ) {
514 if( $tag != 'nowiki' && $tag != 'html' ) {
515 foreach( $contentDict as $uniq => $content ) {
516 $replacements[$uniq] = $content;
517 }
518 }
519 }
520 $text = strtr( $text, $replacements );
521
522 return $text;
523 }
524
525 /**
526 * Always call this after unstrip() to preserve the order
527 *
528 * @private
529 */
530 function unstripNoWiki( $text, &$state ) {
531 if ( !is_array( $state ) ) {
532 return $text;
533 }
534
535 $replacements = array();
536 foreach( $state as $tag => $contentDict ) {
537 if( $tag == 'nowiki' || $tag == 'html' ) {
538 foreach( $contentDict as $uniq => $content ) {
539 $replacements[$uniq] = $content;
540 }
541 }
542 }
543 $text = strtr( $text, $replacements );
544
545 return $text;
546 }
547
548 /**
549 * Add an item to the strip state
550 * Returns the unique tag which must be inserted into the stripped text
551 * The tag will be replaced with the original text in unstrip()
552 *
553 * @private
554 */
555 function insertStripItem( $text, &$state ) {
556 $rnd = $this->mUniqPrefix . '-item' . Parser::getRandomString();
557 if ( !$state ) {
558 $state = array();
559 }
560 $state['item'][$rnd] = $text;
561 return $rnd;
562 }
563
564 /**
565 * Interface with html tidy, used if $wgUseTidy = true.
566 * If tidy isn't able to correct the markup, the original will be
567 * returned in all its glory with a warning comment appended.
568 *
569 * Either the external tidy program or the in-process tidy extension
570 * will be used depending on availability. Override the default
571 * $wgTidyInternal setting to disable the internal if it's not working.
572 *
573 * @param string $text Hideous HTML input
574 * @return string Corrected HTML output
575 * @public
576 * @static
577 */
578 function tidy( $text ) {
579 global $wgTidyInternal;
580 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
581 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
582 '<head><title>test</title></head><body>'.$text.'</body></html>';
583 if( $wgTidyInternal ) {
584 $correctedtext = Parser::internalTidy( $wrappedtext );
585 } else {
586 $correctedtext = Parser::externalTidy( $wrappedtext );
587 }
588 if( is_null( $correctedtext ) ) {
589 wfDebug( "Tidy error detected!\n" );
590 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
591 }
592 return $correctedtext;
593 }
594
595 /**
596 * Spawn an external HTML tidy process and get corrected markup back from it.
597 *
598 * @private
599 * @static
600 */
601 function externalTidy( $text ) {
602 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
603 $fname = 'Parser::externalTidy';
604 wfProfileIn( $fname );
605
606 $cleansource = '';
607 $opts = ' -utf8';
608
609 $descriptorspec = array(
610 0 => array('pipe', 'r'),
611 1 => array('pipe', 'w'),
612 2 => array('file', '/dev/null', 'a')
613 );
614 $pipes = array();
615 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
616 if (is_resource($process)) {
617 // Theoretically, this style of communication could cause a deadlock
618 // here. If the stdout buffer fills up, then writes to stdin could
619 // block. This doesn't appear to happen with tidy, because tidy only
620 // writes to stdout after it's finished reading from stdin. Search
621 // for tidyParseStdin and tidySaveStdout in console/tidy.c
622 fwrite($pipes[0], $text);
623 fclose($pipes[0]);
624 while (!feof($pipes[1])) {
625 $cleansource .= fgets($pipes[1], 1024);
626 }
627 fclose($pipes[1]);
628 proc_close($process);
629 }
630
631 wfProfileOut( $fname );
632
633 if( $cleansource == '' && $text != '') {
634 // Some kind of error happened, so we couldn't get the corrected text.
635 // Just give up; we'll use the source text and append a warning.
636 return null;
637 } else {
638 return $cleansource;
639 }
640 }
641
642 /**
643 * Use the HTML tidy PECL extension to use the tidy library in-process,
644 * saving the overhead of spawning a new process. Currently written to
645 * the PHP 4.3.x version of the extension, may not work on PHP 5.
646 *
647 * 'pear install tidy' should be able to compile the extension module.
648 *
649 * @private
650 * @static
651 */
652 function internalTidy( $text ) {
653 global $wgTidyConf;
654 $fname = 'Parser::internalTidy';
655 wfProfileIn( $fname );
656
657 tidy_load_config( $wgTidyConf );
658 tidy_set_encoding( 'utf8' );
659 tidy_parse_string( $text );
660 tidy_clean_repair();
661 if( tidy_get_status() == 2 ) {
662 // 2 is magic number for fatal error
663 // http://www.php.net/manual/en/function.tidy-get-status.php
664 $cleansource = null;
665 } else {
666 $cleansource = tidy_get_output();
667 }
668 wfProfileOut( $fname );
669 return $cleansource;
670 }
671
672 /**
673 * parse the wiki syntax used to render tables
674 *
675 * @private
676 */
677 function doTableStuff ( $t ) {
678 $fname = 'Parser::doTableStuff';
679 wfProfileIn( $fname );
680
681 $t = explode ( "\n" , $t ) ;
682 $td = array () ; # Is currently a td tag open?
683 $ltd = array () ; # Was it TD or TH?
684 $tr = array () ; # Is currently a tr tag open?
685 $ltr = array () ; # tr attributes
686 $has_opened_tr = array(); # Did this table open a <tr> element?
687 $indent_level = 0; # indent level of the table
688 foreach ( $t AS $k => $x )
689 {
690 $x = trim ( $x ) ;
691 $fc = substr ( $x , 0 , 1 ) ;
692 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
693 $indent_level = strlen( $matches[1] );
694
695 $attributes = $this->unstripForHTML( $matches[2] );
696
697 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
698 '<table' . Sanitizer::fixTagAttributes ( $attributes, 'table' ) . '>' ;
699 array_push ( $td , false ) ;
700 array_push ( $ltd , '' ) ;
701 array_push ( $tr , false ) ;
702 array_push ( $ltr , '' ) ;
703 array_push ( $has_opened_tr, false );
704 }
705 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
706 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
707 $z = "</table>" . substr ( $x , 2);
708 $l = array_pop ( $ltd ) ;
709 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
710 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
711 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
712 array_pop ( $ltr ) ;
713 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
714 }
715 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
716 $x = substr ( $x , 1 ) ;
717 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
718 $z = '' ;
719 $l = array_pop ( $ltd ) ;
720 array_pop ( $has_opened_tr );
721 array_push ( $has_opened_tr , true ) ;
722 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
723 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
724 array_pop ( $ltr ) ;
725 $t[$k] = $z ;
726 array_push ( $tr , false ) ;
727 array_push ( $td , false ) ;
728 array_push ( $ltd , '' ) ;
729 $attributes = $this->unstripForHTML( $x );
730 array_push ( $ltr , Sanitizer::fixTagAttributes ( $attributes, 'tr' ) ) ;
731 }
732 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
733 # $x is a table row
734 if ( '|+' == substr ( $x , 0 , 2 ) ) {
735 $fc = '+' ;
736 $x = substr ( $x , 1 ) ;
737 }
738 $after = substr ( $x , 1 ) ;
739 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
740
741 // Split up multiple cells on the same line.
742 // FIXME: This can result in improper nesting of tags processed
743 // by earlier parser steps, but should avoid splitting up eg
744 // attribute values containing literal "||".
745 $after = wfExplodeMarkup( '||', $after );
746
747 $t[$k] = '' ;
748
749 # Loop through each table cell
750 foreach ( $after AS $theline )
751 {
752 $z = '' ;
753 if ( $fc != '+' )
754 {
755 $tra = array_pop ( $ltr ) ;
756 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
757 array_push ( $tr , true ) ;
758 array_push ( $ltr , '' ) ;
759 array_pop ( $has_opened_tr );
760 array_push ( $has_opened_tr , true ) ;
761 }
762
763 $l = array_pop ( $ltd ) ;
764 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
765 if ( $fc == '|' ) $l = 'td' ;
766 else if ( $fc == '!' ) $l = 'th' ;
767 else if ( $fc == '+' ) $l = 'caption' ;
768 else $l = '' ;
769 array_push ( $ltd , $l ) ;
770
771 # Cell parameters
772 $y = explode ( '|' , $theline , 2 ) ;
773 # Note that a '|' inside an invalid link should not
774 # be mistaken as delimiting cell parameters
775 if ( strpos( $y[0], '[[' ) !== false ) {
776 $y = array ($theline);
777 }
778 if ( count ( $y ) == 1 )
779 $y = "{$z}<{$l}>{$y[0]}" ;
780 else {
781 $attributes = $this->unstripForHTML( $y[0] );
782 $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($attributes, $l).">{$y[1]}" ;
783 }
784 $t[$k] .= $y ;
785 array_push ( $td , true ) ;
786 }
787 }
788 }
789
790 # Closing open td, tr && table
791 while ( count ( $td ) > 0 )
792 {
793 $l = array_pop ( $ltd ) ;
794 if ( array_pop ( $td ) ) $t[] = '</td>' ;
795 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
796 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
797 $t[] = '</table>' ;
798 }
799
800 $t = implode ( "\n" , $t ) ;
801 # special case: don't return empty table
802 if($t == "<table>\n<tr><td></td></tr>\n</table>")
803 $t = '';
804 wfProfileOut( $fname );
805 return $t ;
806 }
807
808 /**
809 * Helper function for parse() that transforms wiki markup into
810 * HTML. Only called for $mOutputType == OT_HTML.
811 *
812 * @private
813 */
814 function internalParse( $text ) {
815 $args = array();
816 $isMain = true;
817 $fname = 'Parser::internalParse';
818 wfProfileIn( $fname );
819
820 # Remove <noinclude> tags and <includeonly> sections
821 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
822 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
823 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
824
825 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
826
827 $text = $this->replaceVariables( $text, $args );
828
829 // Tables need to come after variable replacement for things to work
830 // properly; putting them before other transformations should keep
831 // exciting things like link expansions from showing up in surprising
832 // places.
833 $text = $this->doTableStuff( $text );
834
835 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
836
837 $text = $this->stripToc( $text );
838 $text = $this->doHeadings( $text );
839 if($this->mOptions->getUseDynamicDates()) {
840 $df =& DateFormatter::getInstance();
841 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
842 }
843 $text = $this->doAllQuotes( $text );
844 $text = $this->replaceInternalLinks( $text );
845 $text = $this->replaceExternalLinks( $text );
846
847 # replaceInternalLinks may sometimes leave behind
848 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
849 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
850
851 $text = $this->doMagicLinks( $text );
852 $text = $this->formatHeadings( $text, $isMain );
853
854 wfProfileOut( $fname );
855 return $text;
856 }
857
858 /**
859 * Replace special strings like "ISBN xxx" and "RFC xxx" with
860 * magic external links.
861 *
862 * @private
863 */
864 function &doMagicLinks( &$text ) {
865 $text = $this->magicISBN( $text );
866 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
867 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
868 return $text;
869 }
870
871 /**
872 * Parse headers and return html
873 *
874 * @private
875 */
876 function doHeadings( $text ) {
877 $fname = 'Parser::doHeadings';
878 wfProfileIn( $fname );
879 for ( $i = 6; $i >= 1; --$i ) {
880 $h = str_repeat( '=', $i );
881 $text = preg_replace( "/^{$h}(.+){$h}\\s*$/m",
882 "<h{$i}>\\1</h{$i}>\\2", $text );
883 }
884 wfProfileOut( $fname );
885 return $text;
886 }
887
888 /**
889 * Replace single quotes with HTML markup
890 * @private
891 * @return string the altered text
892 */
893 function doAllQuotes( $text ) {
894 $fname = 'Parser::doAllQuotes';
895 wfProfileIn( $fname );
896 $outtext = '';
897 $lines = explode( "\n", $text );
898 foreach ( $lines as $line ) {
899 $outtext .= $this->doQuotes ( $line ) . "\n";
900 }
901 $outtext = substr($outtext, 0,-1);
902 wfProfileOut( $fname );
903 return $outtext;
904 }
905
906 /**
907 * Helper function for doAllQuotes()
908 * @private
909 */
910 function doQuotes( $text ) {
911 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
912 if ( count( $arr ) == 1 )
913 return $text;
914 else
915 {
916 # First, do some preliminary work. This may shift some apostrophes from
917 # being mark-up to being text. It also counts the number of occurrences
918 # of bold and italics mark-ups.
919 $i = 0;
920 $numbold = 0;
921 $numitalics = 0;
922 foreach ( $arr as $r )
923 {
924 if ( ( $i % 2 ) == 1 )
925 {
926 # If there are ever four apostrophes, assume the first is supposed to
927 # be text, and the remaining three constitute mark-up for bold text.
928 if ( strlen( $arr[$i] ) == 4 )
929 {
930 $arr[$i-1] .= "'";
931 $arr[$i] = "'''";
932 }
933 # If there are more than 5 apostrophes in a row, assume they're all
934 # text except for the last 5.
935 else if ( strlen( $arr[$i] ) > 5 )
936 {
937 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
938 $arr[$i] = "'''''";
939 }
940 # Count the number of occurrences of bold and italics mark-ups.
941 # We are not counting sequences of five apostrophes.
942 if ( strlen( $arr[$i] ) == 2 ) $numitalics++; else
943 if ( strlen( $arr[$i] ) == 3 ) $numbold++; else
944 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
945 }
946 $i++;
947 }
948
949 # If there is an odd number of both bold and italics, it is likely
950 # that one of the bold ones was meant to be an apostrophe followed
951 # by italics. Which one we cannot know for certain, but it is more
952 # likely to be one that has a single-letter word before it.
953 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
954 {
955 $i = 0;
956 $firstsingleletterword = -1;
957 $firstmultiletterword = -1;
958 $firstspace = -1;
959 foreach ( $arr as $r )
960 {
961 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
962 {
963 $x1 = substr ($arr[$i-1], -1);
964 $x2 = substr ($arr[$i-1], -2, 1);
965 if ($x1 == ' ') {
966 if ($firstspace == -1) $firstspace = $i;
967 } else if ($x2 == ' ') {
968 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
969 } else {
970 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
971 }
972 }
973 $i++;
974 }
975
976 # If there is a single-letter word, use it!
977 if ($firstsingleletterword > -1)
978 {
979 $arr [ $firstsingleletterword ] = "''";
980 $arr [ $firstsingleletterword-1 ] .= "'";
981 }
982 # If not, but there's a multi-letter word, use that one.
983 else if ($firstmultiletterword > -1)
984 {
985 $arr [ $firstmultiletterword ] = "''";
986 $arr [ $firstmultiletterword-1 ] .= "'";
987 }
988 # ... otherwise use the first one that has neither.
989 # (notice that it is possible for all three to be -1 if, for example,
990 # there is only one pentuple-apostrophe in the line)
991 else if ($firstspace > -1)
992 {
993 $arr [ $firstspace ] = "''";
994 $arr [ $firstspace-1 ] .= "'";
995 }
996 }
997
998 # Now let's actually convert our apostrophic mush to HTML!
999 $output = '';
1000 $buffer = '';
1001 $state = '';
1002 $i = 0;
1003 foreach ($arr as $r)
1004 {
1005 if (($i % 2) == 0)
1006 {
1007 if ($state == 'both')
1008 $buffer .= $r;
1009 else
1010 $output .= $r;
1011 }
1012 else
1013 {
1014 if (strlen ($r) == 2)
1015 {
1016 if ($state == 'i')
1017 { $output .= '</i>'; $state = ''; }
1018 else if ($state == 'bi')
1019 { $output .= '</i>'; $state = 'b'; }
1020 else if ($state == 'ib')
1021 { $output .= '</b></i><b>'; $state = 'b'; }
1022 else if ($state == 'both')
1023 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1024 else # $state can be 'b' or ''
1025 { $output .= '<i>'; $state .= 'i'; }
1026 }
1027 else if (strlen ($r) == 3)
1028 {
1029 if ($state == 'b')
1030 { $output .= '</b>'; $state = ''; }
1031 else if ($state == 'bi')
1032 { $output .= '</i></b><i>'; $state = 'i'; }
1033 else if ($state == 'ib')
1034 { $output .= '</b>'; $state = 'i'; }
1035 else if ($state == 'both')
1036 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1037 else # $state can be 'i' or ''
1038 { $output .= '<b>'; $state .= 'b'; }
1039 }
1040 else if (strlen ($r) == 5)
1041 {
1042 if ($state == 'b')
1043 { $output .= '</b><i>'; $state = 'i'; }
1044 else if ($state == 'i')
1045 { $output .= '</i><b>'; $state = 'b'; }
1046 else if ($state == 'bi')
1047 { $output .= '</i></b>'; $state = ''; }
1048 else if ($state == 'ib')
1049 { $output .= '</b></i>'; $state = ''; }
1050 else if ($state == 'both')
1051 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1052 else # ($state == '')
1053 { $buffer = ''; $state = 'both'; }
1054 }
1055 }
1056 $i++;
1057 }
1058 # Now close all remaining tags. Notice that the order is important.
1059 if ($state == 'b' || $state == 'ib')
1060 $output .= '</b>';
1061 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1062 $output .= '</i>';
1063 if ($state == 'bi')
1064 $output .= '</b>';
1065 if ($state == 'both')
1066 $output .= '<b><i>'.$buffer.'</i></b>';
1067 return $output;
1068 }
1069 }
1070
1071 /**
1072 * Replace external links
1073 *
1074 * Note: this is all very hackish and the order of execution matters a lot.
1075 * Make sure to run maintenance/parserTests.php if you change this code.
1076 *
1077 * @private
1078 */
1079 function replaceExternalLinks( $text ) {
1080 global $wgContLang;
1081 $fname = 'Parser::replaceExternalLinks';
1082 wfProfileIn( $fname );
1083
1084 $sk =& $this->mOptions->getSkin();
1085
1086 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1087
1088 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1089
1090 $i = 0;
1091 while ( $i<count( $bits ) ) {
1092 $url = $bits[$i++];
1093 $protocol = $bits[$i++];
1094 $text = $bits[$i++];
1095 $trail = $bits[$i++];
1096
1097 # The characters '<' and '>' (which were escaped by
1098 # removeHTMLtags()) should not be included in
1099 # URLs, per RFC 2396.
1100 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1101 $text = substr($url, $m2[0][1]) . ' ' . $text;
1102 $url = substr($url, 0, $m2[0][1]);
1103 }
1104
1105 # If the link text is an image URL, replace it with an <img> tag
1106 # This happened by accident in the original parser, but some people used it extensively
1107 $img = $this->maybeMakeExternalImage( $text );
1108 if ( $img !== false ) {
1109 $text = $img;
1110 }
1111
1112 $dtrail = '';
1113
1114 # Set linktype for CSS - if URL==text, link is essentially free
1115 $linktype = ($text == $url) ? 'free' : 'text';
1116
1117 # No link text, e.g. [http://domain.tld/some.link]
1118 if ( $text == '' ) {
1119 # Autonumber if allowed. See bug #5918
1120 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1121 $text = '[' . ++$this->mAutonumber . ']';
1122 $linktype = 'autonumber';
1123 } else {
1124 # Otherwise just use the URL
1125 $text = htmlspecialchars( $url );
1126 $linktype = 'free';
1127 }
1128 } else {
1129 # Have link text, e.g. [http://domain.tld/some.link text]s
1130 # Check for trail
1131 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1132 }
1133
1134 $text = $wgContLang->markNoConversion($text);
1135
1136 # Normalize any HTML entities in input. They will be
1137 # re-escaped by makeExternalLink().
1138 $url = Sanitizer::decodeCharReferences( $url );
1139
1140 # Process the trail (i.e. everything after this link up until start of the next link),
1141 # replacing any non-bracketed links
1142 $trail = $this->replaceFreeExternalLinks( $trail );
1143
1144 # Use the encoded URL
1145 # This means that users can paste URLs directly into the text
1146 # Funny characters like &ouml; aren't valid in URLs anyway
1147 # This was changed in August 2004
1148 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle->getNamespace() ) . $dtrail . $trail;
1149
1150 # Register link in the output object.
1151 # Replace unnecessary URL escape codes with the referenced character
1152 # This prevents spammers from hiding links from the filters
1153 $pasteurized = Parser::replaceUnusualEscapes( $url );
1154 $this->mOutput->addExternalLink( $pasteurized );
1155 }
1156
1157 wfProfileOut( $fname );
1158 return $s;
1159 }
1160
1161 /**
1162 * Replace anything that looks like a URL with a link
1163 * @private
1164 */
1165 function replaceFreeExternalLinks( $text ) {
1166 global $wgContLang;
1167 $fname = 'Parser::replaceFreeExternalLinks';
1168 wfProfileIn( $fname );
1169
1170 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1171 $s = array_shift( $bits );
1172 $i = 0;
1173
1174 $sk =& $this->mOptions->getSkin();
1175
1176 while ( $i < count( $bits ) ){
1177 $protocol = $bits[$i++];
1178 $remainder = $bits[$i++];
1179
1180 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1181 # Found some characters after the protocol that look promising
1182 $url = $protocol . $m[1];
1183 $trail = $m[2];
1184
1185 # special case: handle urls as url args:
1186 # http://www.example.com/foo?=http://www.example.com/bar
1187 if(strlen($trail) == 0 &&
1188 isset($bits[$i]) &&
1189 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1190 preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $bits[$i + 1], $m ))
1191 {
1192 # add protocol, arg
1193 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1194 $i += 2;
1195 $trail = $m[2];
1196 }
1197
1198 # The characters '<' and '>' (which were escaped by
1199 # removeHTMLtags()) should not be included in
1200 # URLs, per RFC 2396.
1201 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1202 $trail = substr($url, $m2[0][1]) . $trail;
1203 $url = substr($url, 0, $m2[0][1]);
1204 }
1205
1206 # Move trailing punctuation to $trail
1207 $sep = ',;\.:!?';
1208 # If there is no left bracket, then consider right brackets fair game too
1209 if ( strpos( $url, '(' ) === false ) {
1210 $sep .= ')';
1211 }
1212
1213 $numSepChars = strspn( strrev( $url ), $sep );
1214 if ( $numSepChars ) {
1215 $trail = substr( $url, -$numSepChars ) . $trail;
1216 $url = substr( $url, 0, -$numSepChars );
1217 }
1218
1219 # Normalize any HTML entities in input. They will be
1220 # re-escaped by makeExternalLink() or maybeMakeExternalImage()
1221 $url = Sanitizer::decodeCharReferences( $url );
1222
1223 # Is this an external image?
1224 $text = $this->maybeMakeExternalImage( $url );
1225 if ( $text === false ) {
1226 # Not an image, make a link
1227 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle->getNamespace() );
1228 # Register it in the output object...
1229 # Replace unnecessary URL escape codes with their equivalent characters
1230 $pasteurized = Parser::replaceUnusualEscapes( $url );
1231 $this->mOutput->addExternalLink( $pasteurized );
1232 }
1233 $s .= $text . $trail;
1234 } else {
1235 $s .= $protocol . $remainder;
1236 }
1237 }
1238 wfProfileOut( $fname );
1239 return $s;
1240 }
1241
1242 /**
1243 * Replace unusual URL escape codes with their equivalent characters
1244 * @param string
1245 * @return string
1246 * @static
1247 * @fixme This can merge genuinely required bits in the path or query string,
1248 * breaking legit URLs. A proper fix would treat the various parts of
1249 * the URL differently; as a workaround, just use the output for
1250 * statistical records, not for actual linking/output.
1251 */
1252 function replaceUnusualEscapes( $url ) {
1253 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1254 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1255 }
1256
1257 /**
1258 * Callback function used in replaceUnusualEscapes().
1259 * Replaces unusual URL escape codes with their equivalent character
1260 * @static
1261 * @private
1262 */
1263 function replaceUnusualEscapesCallback( $matches ) {
1264 $char = urldecode( $matches[0] );
1265 $ord = ord( $char );
1266 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1267 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1268 // No, shouldn't be escaped
1269 return $char;
1270 } else {
1271 // Yes, leave it escaped
1272 return $matches[0];
1273 }
1274 }
1275
1276 /**
1277 * make an image if it's allowed, either through the global
1278 * option or through the exception
1279 * @private
1280 */
1281 function maybeMakeExternalImage( $url ) {
1282 $sk =& $this->mOptions->getSkin();
1283 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1284 $imagesexception = !empty($imagesfrom);
1285 $text = false;
1286 if ( $this->mOptions->getAllowExternalImages()
1287 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1288 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1289 # Image found
1290 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1291 }
1292 }
1293 return $text;
1294 }
1295
1296 /**
1297 * Process [[ ]] wikilinks
1298 *
1299 * @private
1300 */
1301 function replaceInternalLinks( $s ) {
1302 global $wgContLang;
1303 static $fname = 'Parser::replaceInternalLinks' ;
1304
1305 wfProfileIn( $fname );
1306
1307 wfProfileIn( $fname.'-setup' );
1308 static $tc = FALSE;
1309 # the % is needed to support urlencoded titles as well
1310 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1311
1312 $sk =& $this->mOptions->getSkin();
1313
1314 #split the entire text string on occurences of [[
1315 $a = explode( '[[', ' ' . $s );
1316 #get the first element (all text up to first [[), and remove the space we added
1317 $s = array_shift( $a );
1318 $s = substr( $s, 1 );
1319
1320 # Match a link having the form [[namespace:link|alternate]]trail
1321 static $e1 = FALSE;
1322 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1323 # Match cases where there is no "]]", which might still be images
1324 static $e1_img = FALSE;
1325 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1326 # Match the end of a line for a word that's not followed by whitespace,
1327 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1328 $e2 = wfMsgForContent( 'linkprefix' );
1329
1330 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1331
1332 if( is_null( $this->mTitle ) ) {
1333 throw new MWException( 'nooo' );
1334 }
1335 $nottalk = !$this->mTitle->isTalkPage();
1336
1337 if ( $useLinkPrefixExtension ) {
1338 if ( preg_match( $e2, $s, $m ) ) {
1339 $first_prefix = $m[2];
1340 } else {
1341 $first_prefix = false;
1342 }
1343 } else {
1344 $prefix = '';
1345 }
1346
1347 $selflink = $this->mTitle->getPrefixedText();
1348 wfProfileOut( $fname.'-setup' );
1349
1350 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1351 $useSubpages = $this->areSubpagesAllowed();
1352
1353 # Loop for each link
1354 for ($k = 0; isset( $a[$k] ); $k++) {
1355 $line = $a[$k];
1356 if ( $useLinkPrefixExtension ) {
1357 wfProfileIn( $fname.'-prefixhandling' );
1358 if ( preg_match( $e2, $s, $m ) ) {
1359 $prefix = $m[2];
1360 $s = $m[1];
1361 } else {
1362 $prefix='';
1363 }
1364 # first link
1365 if($first_prefix) {
1366 $prefix = $first_prefix;
1367 $first_prefix = false;
1368 }
1369 wfProfileOut( $fname.'-prefixhandling' );
1370 }
1371
1372 $might_be_img = false;
1373
1374 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1375 $text = $m[2];
1376 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1377 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1378 # the real problem is with the $e1 regex
1379 # See bug 1300.
1380 #
1381 # Still some problems for cases where the ] is meant to be outside punctuation,
1382 # and no image is in sight. See bug 2095.
1383 #
1384 if( $text !== '' &&
1385 preg_match( "/^\](.*)/s", $m[3], $n ) &&
1386 strpos($text, '[') !== false
1387 )
1388 {
1389 $text .= ']'; # so that replaceExternalLinks($text) works later
1390 $m[3] = $n[1];
1391 }
1392 # fix up urlencoded title texts
1393 if(preg_match('/%/', $m[1] ))
1394 # Should anchors '#' also be rejected?
1395 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1396 $trail = $m[3];
1397 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1398 $might_be_img = true;
1399 $text = $m[2];
1400 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1401 $trail = "";
1402 } else { # Invalid form; output directly
1403 $s .= $prefix . '[[' . $line ;
1404 continue;
1405 }
1406
1407 # Don't allow internal links to pages containing
1408 # PROTO: where PROTO is a valid URL protocol; these
1409 # should be external links.
1410 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1411 $s .= $prefix . '[[' . $line ;
1412 continue;
1413 }
1414
1415 # Make subpage if necessary
1416 if( $useSubpages ) {
1417 $link = $this->maybeDoSubpageLink( $m[1], $text );
1418 } else {
1419 $link = $m[1];
1420 }
1421
1422 $noforce = (substr($m[1], 0, 1) != ':');
1423 if (!$noforce) {
1424 # Strip off leading ':'
1425 $link = substr($link, 1);
1426 }
1427
1428 $nt = Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1429 if( !$nt ) {
1430 $s .= $prefix . '[[' . $line;
1431 continue;
1432 }
1433
1434 #check other language variants of the link
1435 #if the article does not exist
1436 if( $checkVariantLink
1437 && $nt->getArticleID() == 0 ) {
1438 $wgContLang->findVariantLink($link, $nt);
1439 }
1440
1441 $ns = $nt->getNamespace();
1442 $iw = $nt->getInterWiki();
1443
1444 if ($might_be_img) { # if this is actually an invalid link
1445 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1446 $found = false;
1447 while (isset ($a[$k+1]) ) {
1448 #look at the next 'line' to see if we can close it there
1449 $spliced = array_splice( $a, $k + 1, 1 );
1450 $next_line = array_shift( $spliced );
1451 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1452 # the first ]] closes the inner link, the second the image
1453 $found = true;
1454 $text .= '[[' . $m[1];
1455 $trail = $m[2];
1456 break;
1457 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1458 #if there's exactly one ]] that's fine, we'll keep looking
1459 $text .= '[[' . $m[0];
1460 } else {
1461 #if $next_line is invalid too, we need look no further
1462 $text .= '[[' . $next_line;
1463 break;
1464 }
1465 }
1466 if ( !$found ) {
1467 # we couldn't find the end of this imageLink, so output it raw
1468 #but don't ignore what might be perfectly normal links in the text we've examined
1469 $text = $this->replaceInternalLinks($text);
1470 $s .= $prefix . '[[' . $link . '|' . $text;
1471 # note: no $trail, because without an end, there *is* no trail
1472 continue;
1473 }
1474 } else { #it's not an image, so output it raw
1475 $s .= $prefix . '[[' . $link . '|' . $text;
1476 # note: no $trail, because without an end, there *is* no trail
1477 continue;
1478 }
1479 }
1480
1481 $wasblank = ( '' == $text );
1482 if( $wasblank ) $text = $link;
1483
1484
1485 # Link not escaped by : , create the various objects
1486 if( $noforce ) {
1487
1488 # Interwikis
1489 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1490 $this->mOutput->addLanguageLink( $nt->getFullText() );
1491 $s = rtrim($s . "\n");
1492 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1493 continue;
1494 }
1495
1496 if ( $ns == NS_IMAGE ) {
1497 wfProfileIn( "$fname-image" );
1498 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1499 # recursively parse links inside the image caption
1500 # actually, this will parse them in any other parameters, too,
1501 # but it might be hard to fix that, and it doesn't matter ATM
1502 $text = $this->replaceExternalLinks($text);
1503 $text = $this->replaceInternalLinks($text);
1504
1505 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1506 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1507 $this->mOutput->addImage( $nt->getDBkey() );
1508
1509 wfProfileOut( "$fname-image" );
1510 continue;
1511 }
1512 wfProfileOut( "$fname-image" );
1513
1514 }
1515
1516 if ( $ns == NS_CATEGORY ) {
1517 wfProfileIn( "$fname-category" );
1518 $s = rtrim($s . "\n"); # bug 87
1519
1520 if ( $wasblank ) {
1521 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1522 $sortkey = $this->mTitle->getText();
1523 } else {
1524 $sortkey = $this->mTitle->getPrefixedText();
1525 }
1526 } else {
1527 $sortkey = $text;
1528 }
1529 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1530 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1531 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1532
1533 /**
1534 * Strip the whitespace Category links produce, see bug 87
1535 * @todo We might want to use trim($tmp, "\n") here.
1536 */
1537 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1538
1539 wfProfileOut( "$fname-category" );
1540 continue;
1541 }
1542 }
1543
1544 if( ( $nt->getPrefixedText() === $selflink ) &&
1545 ( $nt->getFragment() === '' ) ) {
1546 # Self-links are handled specially; generally de-link and change to bold.
1547 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1548 continue;
1549 }
1550
1551 # Special and Media are pseudo-namespaces; no pages actually exist in them
1552 if( $ns == NS_MEDIA ) {
1553 $link = $sk->makeMediaLinkObj( $nt, $text );
1554 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1555 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1556 $this->mOutput->addImage( $nt->getDBkey() );
1557 continue;
1558 } elseif( $ns == NS_SPECIAL ) {
1559 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1560 continue;
1561 } elseif( $ns == NS_IMAGE ) {
1562 $img = Image::newFromTitle( $nt );
1563 if( $img->exists() ) {
1564 // Force a blue link if the file exists; may be a remote
1565 // upload on the shared repository, and we want to see its
1566 // auto-generated page.
1567 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1568 continue;
1569 }
1570 }
1571 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1572 }
1573 wfProfileOut( $fname );
1574 return $s;
1575 }
1576
1577 /**
1578 * Make a link placeholder. The text returned can be later resolved to a real link with
1579 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1580 * parsing of interwiki links, and secondly to allow all extistence checks and
1581 * article length checks (for stub links) to be bundled into a single query.
1582 *
1583 */
1584 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1585 if ( ! is_object($nt) ) {
1586 # Fail gracefully
1587 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1588 } else {
1589 # Separate the link trail from the rest of the link
1590 list( $inside, $trail ) = Linker::splitTrail( $trail );
1591
1592 if ( $nt->isExternal() ) {
1593 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1594 $this->mInterwikiLinkHolders['titles'][] = $nt;
1595 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1596 } else {
1597 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1598 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1599 $this->mLinkHolders['queries'][] = $query;
1600 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1601 $this->mLinkHolders['titles'][] = $nt;
1602
1603 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1604 }
1605 }
1606 return $retVal;
1607 }
1608
1609 /**
1610 * Render a forced-blue link inline; protect against double expansion of
1611 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1612 * Since this little disaster has to split off the trail text to avoid
1613 * breaking URLs in the following text without breaking trails on the
1614 * wiki links, it's been made into a horrible function.
1615 *
1616 * @param Title $nt
1617 * @param string $text
1618 * @param string $query
1619 * @param string $trail
1620 * @param string $prefix
1621 * @return string HTML-wikitext mix oh yuck
1622 */
1623 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1624 list( $inside, $trail ) = Linker::splitTrail( $trail );
1625 $sk =& $this->mOptions->getSkin();
1626 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1627 return $this->armorLinks( $link ) . $trail;
1628 }
1629
1630 /**
1631 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1632 * going to go through further parsing steps before inline URL expansion.
1633 *
1634 * In particular this is important when using action=render, which causes
1635 * full URLs to be included.
1636 *
1637 * Oh man I hate our multi-layer parser!
1638 *
1639 * @param string more-or-less HTML
1640 * @return string less-or-more HTML with NOPARSE bits
1641 */
1642 function armorLinks( $text ) {
1643 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1644 "{$this->mUniqPrefix}NOPARSE$1", $text );
1645 }
1646
1647 /**
1648 * Return true if subpage links should be expanded on this page.
1649 * @return bool
1650 */
1651 function areSubpagesAllowed() {
1652 # Some namespaces don't allow subpages
1653 global $wgNamespacesWithSubpages;
1654 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1655 }
1656
1657 /**
1658 * Handle link to subpage if necessary
1659 * @param string $target the source of the link
1660 * @param string &$text the link text, modified as necessary
1661 * @return string the full name of the link
1662 * @private
1663 */
1664 function maybeDoSubpageLink($target, &$text) {
1665 # Valid link forms:
1666 # Foobar -- normal
1667 # :Foobar -- override special treatment of prefix (images, language links)
1668 # /Foobar -- convert to CurrentPage/Foobar
1669 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1670 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1671 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1672
1673 $fname = 'Parser::maybeDoSubpageLink';
1674 wfProfileIn( $fname );
1675 $ret = $target; # default return value is no change
1676
1677 # Some namespaces don't allow subpages,
1678 # so only perform processing if subpages are allowed
1679 if( $this->areSubpagesAllowed() ) {
1680 # Look at the first character
1681 if( $target != '' && $target{0} == '/' ) {
1682 # / at end means we don't want the slash to be shown
1683 if( substr( $target, -1, 1 ) == '/' ) {
1684 $target = substr( $target, 1, -1 );
1685 $noslash = $target;
1686 } else {
1687 $noslash = substr( $target, 1 );
1688 }
1689
1690 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1691 if( '' === $text ) {
1692 $text = $target;
1693 } # this might be changed for ugliness reasons
1694 } else {
1695 # check for .. subpage backlinks
1696 $dotdotcount = 0;
1697 $nodotdot = $target;
1698 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1699 ++$dotdotcount;
1700 $nodotdot = substr( $nodotdot, 3 );
1701 }
1702 if($dotdotcount > 0) {
1703 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1704 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1705 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1706 # / at the end means don't show full path
1707 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1708 $nodotdot = substr( $nodotdot, 0, -1 );
1709 if( '' === $text ) {
1710 $text = $nodotdot;
1711 }
1712 }
1713 $nodotdot = trim( $nodotdot );
1714 if( $nodotdot != '' ) {
1715 $ret .= '/' . $nodotdot;
1716 }
1717 }
1718 }
1719 }
1720 }
1721
1722 wfProfileOut( $fname );
1723 return $ret;
1724 }
1725
1726 /**#@+
1727 * Used by doBlockLevels()
1728 * @private
1729 */
1730 /* private */ function closeParagraph() {
1731 $result = '';
1732 if ( '' != $this->mLastSection ) {
1733 $result = '</' . $this->mLastSection . ">\n";
1734 }
1735 $this->mInPre = false;
1736 $this->mLastSection = '';
1737 return $result;
1738 }
1739 # getCommon() returns the length of the longest common substring
1740 # of both arguments, starting at the beginning of both.
1741 #
1742 /* private */ function getCommon( $st1, $st2 ) {
1743 $fl = strlen( $st1 );
1744 $shorter = strlen( $st2 );
1745 if ( $fl < $shorter ) { $shorter = $fl; }
1746
1747 for ( $i = 0; $i < $shorter; ++$i ) {
1748 if ( $st1{$i} != $st2{$i} ) { break; }
1749 }
1750 return $i;
1751 }
1752 # These next three functions open, continue, and close the list
1753 # element appropriate to the prefix character passed into them.
1754 #
1755 /* private */ function openList( $char ) {
1756 $result = $this->closeParagraph();
1757
1758 if ( '*' == $char ) { $result .= '<ul><li>'; }
1759 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1760 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1761 else if ( ';' == $char ) {
1762 $result .= '<dl><dt>';
1763 $this->mDTopen = true;
1764 }
1765 else { $result = '<!-- ERR 1 -->'; }
1766
1767 return $result;
1768 }
1769
1770 /* private */ function nextItem( $char ) {
1771 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1772 else if ( ':' == $char || ';' == $char ) {
1773 $close = '</dd>';
1774 if ( $this->mDTopen ) { $close = '</dt>'; }
1775 if ( ';' == $char ) {
1776 $this->mDTopen = true;
1777 return $close . '<dt>';
1778 } else {
1779 $this->mDTopen = false;
1780 return $close . '<dd>';
1781 }
1782 }
1783 return '<!-- ERR 2 -->';
1784 }
1785
1786 /* private */ function closeList( $char ) {
1787 if ( '*' == $char ) { $text = '</li></ul>'; }
1788 else if ( '#' == $char ) { $text = '</li></ol>'; }
1789 else if ( ':' == $char ) {
1790 if ( $this->mDTopen ) {
1791 $this->mDTopen = false;
1792 $text = '</dt></dl>';
1793 } else {
1794 $text = '</dd></dl>';
1795 }
1796 }
1797 else { return '<!-- ERR 3 -->'; }
1798 return $text."\n";
1799 }
1800 /**#@-*/
1801
1802 /**
1803 * Make lists from lines starting with ':', '*', '#', etc.
1804 *
1805 * @private
1806 * @return string the lists rendered as HTML
1807 */
1808 function doBlockLevels( $text, $linestart ) {
1809 $fname = 'Parser::doBlockLevels';
1810 wfProfileIn( $fname );
1811
1812 # Parsing through the text line by line. The main thing
1813 # happening here is handling of block-level elements p, pre,
1814 # and making lists from lines starting with * # : etc.
1815 #
1816 $textLines = explode( "\n", $text );
1817
1818 $lastPrefix = $output = '';
1819 $this->mDTopen = $inBlockElem = false;
1820 $prefixLength = 0;
1821 $paragraphStack = false;
1822
1823 if ( !$linestart ) {
1824 $output .= array_shift( $textLines );
1825 }
1826 foreach ( $textLines as $oLine ) {
1827 $lastPrefixLength = strlen( $lastPrefix );
1828 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1829 $preOpenMatch = preg_match('/<pre/i', $oLine );
1830 if ( !$this->mInPre ) {
1831 # Multiple prefixes may abut each other for nested lists.
1832 $prefixLength = strspn( $oLine, '*#:;' );
1833 $pref = substr( $oLine, 0, $prefixLength );
1834
1835 # eh?
1836 $pref2 = str_replace( ';', ':', $pref );
1837 $t = substr( $oLine, $prefixLength );
1838 $this->mInPre = !empty($preOpenMatch);
1839 } else {
1840 # Don't interpret any other prefixes in preformatted text
1841 $prefixLength = 0;
1842 $pref = $pref2 = '';
1843 $t = $oLine;
1844 }
1845
1846 # List generation
1847 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1848 # Same as the last item, so no need to deal with nesting or opening stuff
1849 $output .= $this->nextItem( substr( $pref, -1 ) );
1850 $paragraphStack = false;
1851
1852 if ( substr( $pref, -1 ) == ';') {
1853 # The one nasty exception: definition lists work like this:
1854 # ; title : definition text
1855 # So we check for : in the remainder text to split up the
1856 # title and definition, without b0rking links.
1857 $term = $t2 = '';
1858 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1859 $t = $t2;
1860 $output .= $term . $this->nextItem( ':' );
1861 }
1862 }
1863 } elseif( $prefixLength || $lastPrefixLength ) {
1864 # Either open or close a level...
1865 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1866 $paragraphStack = false;
1867
1868 while( $commonPrefixLength < $lastPrefixLength ) {
1869 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1870 --$lastPrefixLength;
1871 }
1872 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1873 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1874 }
1875 while ( $prefixLength > $commonPrefixLength ) {
1876 $char = substr( $pref, $commonPrefixLength, 1 );
1877 $output .= $this->openList( $char );
1878
1879 if ( ';' == $char ) {
1880 # FIXME: This is dupe of code above
1881 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1882 $t = $t2;
1883 $output .= $term . $this->nextItem( ':' );
1884 }
1885 }
1886 ++$commonPrefixLength;
1887 }
1888 $lastPrefix = $pref2;
1889 }
1890 if( 0 == $prefixLength ) {
1891 wfProfileIn( "$fname-paragraph" );
1892 # No prefix (not in list)--go to paragraph mode
1893 // XXX: use a stack for nestable elements like span, table and div
1894 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/center|<\\/tr|<\\/td|<\\/th)/iS', $t );
1895 $closematch = preg_match(
1896 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1897 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<center)/iS', $t );
1898 if ( $openmatch or $closematch ) {
1899 $paragraphStack = false;
1900 # TODO bug 5718: paragraph closed
1901 $output .= $this->closeParagraph();
1902 if ( $preOpenMatch and !$preCloseMatch ) {
1903 $this->mInPre = true;
1904 }
1905 if ( $closematch ) {
1906 $inBlockElem = false;
1907 } else {
1908 $inBlockElem = true;
1909 }
1910 } else if ( !$inBlockElem && !$this->mInPre ) {
1911 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1912 // pre
1913 if ($this->mLastSection != 'pre') {
1914 $paragraphStack = false;
1915 $output .= $this->closeParagraph().'<pre>';
1916 $this->mLastSection = 'pre';
1917 }
1918 $t = substr( $t, 1 );
1919 } else {
1920 // paragraph
1921 if ( '' == trim($t) ) {
1922 if ( $paragraphStack ) {
1923 $output .= $paragraphStack.'<br />';
1924 $paragraphStack = false;
1925 $this->mLastSection = 'p';
1926 } else {
1927 if ($this->mLastSection != 'p' ) {
1928 $output .= $this->closeParagraph();
1929 $this->mLastSection = '';
1930 $paragraphStack = '<p>';
1931 } else {
1932 $paragraphStack = '</p><p>';
1933 }
1934 }
1935 } else {
1936 if ( $paragraphStack ) {
1937 $output .= $paragraphStack;
1938 $paragraphStack = false;
1939 $this->mLastSection = 'p';
1940 } else if ($this->mLastSection != 'p') {
1941 $output .= $this->closeParagraph().'<p>';
1942 $this->mLastSection = 'p';
1943 }
1944 }
1945 }
1946 }
1947 wfProfileOut( "$fname-paragraph" );
1948 }
1949 // somewhere above we forget to get out of pre block (bug 785)
1950 if($preCloseMatch && $this->mInPre) {
1951 $this->mInPre = false;
1952 }
1953 if ($paragraphStack === false) {
1954 $output .= $t."\n";
1955 }
1956 }
1957 while ( $prefixLength ) {
1958 $output .= $this->closeList( $pref2{$prefixLength-1} );
1959 --$prefixLength;
1960 }
1961 if ( '' != $this->mLastSection ) {
1962 $output .= '</' . $this->mLastSection . '>';
1963 $this->mLastSection = '';
1964 }
1965
1966 wfProfileOut( $fname );
1967 return $output;
1968 }
1969
1970 /**
1971 * Split up a string on ':', ignoring any occurences inside tags
1972 * to prevent illegal overlapping.
1973 * @param string $str the string to split
1974 * @param string &$before set to everything before the ':'
1975 * @param string &$after set to everything after the ':'
1976 * return string the position of the ':', or false if none found
1977 */
1978 function findColonNoLinks($str, &$before, &$after) {
1979 $fname = 'Parser::findColonNoLinks';
1980 wfProfileIn( $fname );
1981
1982 $pos = strpos( $str, ':' );
1983 if( $pos === false ) {
1984 // Nothing to find!
1985 wfProfileOut( $fname );
1986 return false;
1987 }
1988
1989 $lt = strpos( $str, '<' );
1990 if( $lt === false || $lt > $pos ) {
1991 // Easy; no tag nesting to worry about
1992 $before = substr( $str, 0, $pos );
1993 $after = substr( $str, $pos+1 );
1994 wfProfileOut( $fname );
1995 return $pos;
1996 }
1997
1998 // Ugly state machine to walk through avoiding tags.
1999 $state = MW_COLON_STATE_TEXT;
2000 $stack = 0;
2001 $len = strlen( $str );
2002 for( $i = 0; $i < $len; $i++ ) {
2003 $c = $str{$i};
2004
2005 switch( $state ) {
2006 // (Using the number is a performance hack for common cases)
2007 case 0: // MW_COLON_STATE_TEXT:
2008 switch( $c ) {
2009 case "<":
2010 // Could be either a <start> tag or an </end> tag
2011 $state = MW_COLON_STATE_TAGSTART;
2012 break;
2013 case ":":
2014 if( $stack == 0 ) {
2015 // We found it!
2016 $before = substr( $str, 0, $i );
2017 $after = substr( $str, $i + 1 );
2018 wfProfileOut( $fname );
2019 return $i;
2020 }
2021 // Embedded in a tag; don't break it.
2022 break;
2023 default:
2024 // Skip ahead looking for something interesting
2025 $colon = strpos( $str, ':', $i );
2026 if( $colon === false ) {
2027 // Nothing else interesting
2028 wfProfileOut( $fname );
2029 return false;
2030 }
2031 $lt = strpos( $str, '<', $i );
2032 if( $stack === 0 ) {
2033 if( $lt === false || $colon < $lt ) {
2034 // We found it!
2035 $before = substr( $str, 0, $colon );
2036 $after = substr( $str, $colon + 1 );
2037 wfProfileOut( $fname );
2038 return $i;
2039 }
2040 }
2041 if( $lt === false ) {
2042 // Nothing else interesting to find; abort!
2043 // We're nested, but there's no close tags left. Abort!
2044 break 2;
2045 }
2046 // Skip ahead to next tag start
2047 $i = $lt;
2048 $state = MW_COLON_STATE_TAGSTART;
2049 }
2050 break;
2051 case 1: // MW_COLON_STATE_TAG:
2052 // In a <tag>
2053 switch( $c ) {
2054 case ">":
2055 $stack++;
2056 $state = MW_COLON_STATE_TEXT;
2057 break;
2058 case "/":
2059 // Slash may be followed by >?
2060 $state = MW_COLON_STATE_TAGSLASH;
2061 break;
2062 default:
2063 // ignore
2064 }
2065 break;
2066 case 2: // MW_COLON_STATE_TAGSTART:
2067 switch( $c ) {
2068 case "/":
2069 $state = MW_COLON_STATE_CLOSETAG;
2070 break;
2071 case "!":
2072 $state = MW_COLON_STATE_COMMENT;
2073 break;
2074 case ">":
2075 // Illegal early close? This shouldn't happen D:
2076 $state = MW_COLON_STATE_TEXT;
2077 break;
2078 default:
2079 $state = MW_COLON_STATE_TAG;
2080 }
2081 break;
2082 case 3: // MW_COLON_STATE_CLOSETAG:
2083 // In a </tag>
2084 if( $c == ">" ) {
2085 $stack--;
2086 if( $stack < 0 ) {
2087 wfDebug( "Invalid input in $fname; too many close tags\n" );
2088 wfProfileOut( $fname );
2089 return false;
2090 }
2091 $state = MW_COLON_STATE_TEXT;
2092 }
2093 break;
2094 case MW_COLON_STATE_TAGSLASH:
2095 if( $c == ">" ) {
2096 // Yes, a self-closed tag <blah/>
2097 $state = MW_COLON_STATE_TEXT;
2098 } else {
2099 // Probably we're jumping the gun, and this is an attribute
2100 $state = MW_COLON_STATE_TAG;
2101 }
2102 break;
2103 case 5: // MW_COLON_STATE_COMMENT:
2104 if( $c == "-" ) {
2105 $state = MW_COLON_STATE_COMMENTDASH;
2106 }
2107 break;
2108 case MW_COLON_STATE_COMMENTDASH:
2109 if( $c == "-" ) {
2110 $state = MW_COLON_STATE_COMMENTDASHDASH;
2111 } else {
2112 $state = MW_COLON_STATE_COMMENT;
2113 }
2114 break;
2115 case MW_COLON_STATE_COMMENTDASHDASH:
2116 if( $c == ">" ) {
2117 $state = MW_COLON_STATE_TEXT;
2118 } else {
2119 $state = MW_COLON_STATE_COMMENT;
2120 }
2121 break;
2122 default:
2123 throw new MWException( "State machine error in $fname" );
2124 }
2125 }
2126 if( $stack > 0 ) {
2127 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2128 return false;
2129 }
2130 wfProfileOut( $fname );
2131 return false;
2132 }
2133
2134 /**
2135 * Return value of a magic variable (like PAGENAME)
2136 *
2137 * @private
2138 */
2139 function getVariableValue( $index ) {
2140 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2141
2142 /**
2143 * Some of these require message or data lookups and can be
2144 * expensive to check many times.
2145 */
2146 static $varCache = array();
2147 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2148 if ( isset( $varCache[$index] ) )
2149 return $varCache[$index];
2150
2151 $ts = time();
2152 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2153
2154 switch ( $index ) {
2155 case MAG_CURRENTMONTH:
2156 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2157 case MAG_CURRENTMONTHNAME:
2158 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2159 case MAG_CURRENTMONTHNAMEGEN:
2160 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2161 case MAG_CURRENTMONTHABBREV:
2162 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2163 case MAG_CURRENTDAY:
2164 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2165 case MAG_CURRENTDAY2:
2166 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2167 case MAG_PAGENAME:
2168 return $this->mTitle->getText();
2169 case MAG_PAGENAMEE:
2170 return $this->mTitle->getPartialURL();
2171 case MAG_FULLPAGENAME:
2172 return $this->mTitle->getPrefixedText();
2173 case MAG_FULLPAGENAMEE:
2174 return $this->mTitle->getPrefixedURL();
2175 case MAG_SUBPAGENAME:
2176 return $this->mTitle->getSubpageText();
2177 case MAG_SUBPAGENAMEE:
2178 return $this->mTitle->getSubpageUrlForm();
2179 case MAG_BASEPAGENAME:
2180 return $this->mTitle->getBaseText();
2181 case MAG_BASEPAGENAMEE:
2182 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2183 case MAG_TALKPAGENAME:
2184 if( $this->mTitle->canTalk() ) {
2185 $talkPage = $this->mTitle->getTalkPage();
2186 return $talkPage->getPrefixedText();
2187 } else {
2188 return '';
2189 }
2190 case MAG_TALKPAGENAMEE:
2191 if( $this->mTitle->canTalk() ) {
2192 $talkPage = $this->mTitle->getTalkPage();
2193 return $talkPage->getPrefixedUrl();
2194 } else {
2195 return '';
2196 }
2197 case MAG_SUBJECTPAGENAME:
2198 $subjPage = $this->mTitle->getSubjectPage();
2199 return $subjPage->getPrefixedText();
2200 case MAG_SUBJECTPAGENAMEE:
2201 $subjPage = $this->mTitle->getSubjectPage();
2202 return $subjPage->getPrefixedUrl();
2203 case MAG_REVISIONID:
2204 return $this->mRevisionId;
2205 case MAG_NAMESPACE:
2206 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2207 case MAG_NAMESPACEE:
2208 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2209 case MAG_TALKSPACE:
2210 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2211 case MAG_TALKSPACEE:
2212 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2213 case MAG_SUBJECTSPACE:
2214 return $this->mTitle->getSubjectNsText();
2215 case MAG_SUBJECTSPACEE:
2216 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2217 case MAG_CURRENTDAYNAME:
2218 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
2219 case MAG_CURRENTYEAR:
2220 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2221 case MAG_CURRENTTIME:
2222 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2223 case MAG_CURRENTWEEK:
2224 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2225 // int to remove the padding
2226 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2227 case MAG_CURRENTDOW:
2228 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2229 case MAG_NUMBEROFARTICLES:
2230 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2231 case MAG_NUMBEROFFILES:
2232 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2233 case MAG_NUMBEROFUSERS:
2234 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfUsers() );
2235 case MAG_NUMBEROFPAGES:
2236 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfPages() );
2237 case MAG_CURRENTTIMESTAMP:
2238 return $varCache[$index] = wfTimestampNow();
2239 case MAG_CURRENTVERSION:
2240 global $wgVersion;
2241 return $wgVersion;
2242 case MAG_SITENAME:
2243 return $wgSitename;
2244 case MAG_SERVER:
2245 return $wgServer;
2246 case MAG_SERVERNAME:
2247 return $wgServerName;
2248 case MAG_SCRIPTPATH:
2249 return $wgScriptPath;
2250 case MAG_DIRECTIONMARK:
2251 return $wgContLang->getDirMark();
2252 case MAG_CONTENTLANGUAGE:
2253 global $wgContLanguageCode;
2254 return $wgContLanguageCode;
2255 default:
2256 $ret = null;
2257 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2258 return $ret;
2259 else
2260 return null;
2261 }
2262 }
2263
2264 /**
2265 * initialise the magic variables (like CURRENTMONTHNAME)
2266 *
2267 * @private
2268 */
2269 function initialiseVariables() {
2270 $fname = 'Parser::initialiseVariables';
2271 wfProfileIn( $fname );
2272 global $wgVariableIDs;
2273 $this->mVariables = array();
2274 foreach ( $wgVariableIDs as $id ) {
2275 $mw =& MagicWord::get( $id );
2276 $mw->addToArray( $this->mVariables, $id );
2277 }
2278 wfProfileOut( $fname );
2279 }
2280
2281 /**
2282 * parse any parentheses in format ((title|part|part))
2283 * and call callbacks to get a replacement text for any found piece
2284 *
2285 * @param string $text The text to parse
2286 * @param array $callbacks rules in form:
2287 * '{' => array( # opening parentheses
2288 * 'end' => '}', # closing parentheses
2289 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2290 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2291 * )
2292 * )
2293 * @private
2294 */
2295 function replace_callback ($text, $callbacks) {
2296 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2297 $lastOpeningBrace = -1; # last not closed parentheses
2298
2299 for ($i = 0; $i < strlen($text); $i++) {
2300 # check for any opening brace
2301 $rule = null;
2302 $nextPos = -1;
2303 foreach ($callbacks as $key => $value) {
2304 $pos = strpos ($text, $key, $i);
2305 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
2306 $rule = $value;
2307 $nextPos = $pos;
2308 }
2309 }
2310
2311 if ($lastOpeningBrace >= 0) {
2312 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2313
2314 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2315 $rule = null;
2316 $nextPos = $pos;
2317 }
2318
2319 $pos = strpos ($text, '|', $i);
2320
2321 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2322 $rule = null;
2323 $nextPos = $pos;
2324 }
2325 }
2326
2327 if ($nextPos == -1)
2328 break;
2329
2330 $i = $nextPos;
2331
2332 # found openning brace, lets add it to parentheses stack
2333 if (null != $rule) {
2334 $piece = array('brace' => $text[$i],
2335 'braceEnd' => $rule['end'],
2336 'count' => 1,
2337 'title' => '',
2338 'parts' => null);
2339
2340 # count openning brace characters
2341 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2342 $piece['count']++;
2343 $i++;
2344 }
2345
2346 $piece['startAt'] = $i+1;
2347 $piece['partStart'] = $i+1;
2348
2349 # we need to add to stack only if openning brace count is enough for any given rule
2350 foreach ($rule['cb'] as $cnt => $fn) {
2351 if ($piece['count'] >= $cnt) {
2352 $lastOpeningBrace ++;
2353 $openingBraceStack[$lastOpeningBrace] = $piece;
2354 break;
2355 }
2356 }
2357
2358 continue;
2359 }
2360 else if ($lastOpeningBrace >= 0) {
2361 # first check if it is a closing brace
2362 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2363 # lets check if it is enough characters for closing brace
2364 $count = 1;
2365 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2366 $count++;
2367
2368 # if there are more closing parentheses than opening ones, we parse less
2369 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2370 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2371
2372 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2373 $matchingCount = 0;
2374 $matchingCallback = null;
2375 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2376 if ($count >= $cnt && $matchingCount < $cnt) {
2377 $matchingCount = $cnt;
2378 $matchingCallback = $fn;
2379 }
2380 }
2381
2382 if ($matchingCount == 0) {
2383 $i += $count - 1;
2384 continue;
2385 }
2386
2387 # lets set a title or last part (if '|' was found)
2388 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2389 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2390 else
2391 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2392
2393 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2394 $pieceEnd = $i + $matchingCount;
2395
2396 if( is_callable( $matchingCallback ) ) {
2397 $cbArgs = array (
2398 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2399 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2400 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2401 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2402 );
2403 # finally we can call a user callback and replace piece of text
2404 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2405 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2406 $i = $pieceStart + strlen($replaceWith) - 1;
2407 }
2408 else {
2409 # null value for callback means that parentheses should be parsed, but not replaced
2410 $i += $matchingCount - 1;
2411 }
2412
2413 # reset last openning parentheses, but keep it in case there are unused characters
2414 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2415 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2416 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2417 'title' => '',
2418 'parts' => null,
2419 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2420 $openingBraceStack[$lastOpeningBrace--] = null;
2421
2422 if ($matchingCount < $piece['count']) {
2423 $piece['count'] -= $matchingCount;
2424 $piece['startAt'] -= $matchingCount;
2425 $piece['partStart'] = $piece['startAt'];
2426 # do we still qualify for any callback with remaining count?
2427 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2428 if ($piece['count'] >= $cnt) {
2429 $lastOpeningBrace ++;
2430 $openingBraceStack[$lastOpeningBrace] = $piece;
2431 break;
2432 }
2433 }
2434 }
2435 continue;
2436 }
2437
2438 # lets set a title if it is a first separator, or next part otherwise
2439 if ($text[$i] == '|') {
2440 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2441 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2442 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2443 }
2444 else
2445 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2446
2447 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2448 }
2449 }
2450 }
2451
2452 return $text;
2453 }
2454
2455 /**
2456 * Replace magic variables, templates, and template arguments
2457 * with the appropriate text. Templates are substituted recursively,
2458 * taking care to avoid infinite loops.
2459 *
2460 * Note that the substitution depends on value of $mOutputType:
2461 * OT_WIKI: only {{subst:}} templates
2462 * OT_MSG: only magic variables
2463 * OT_HTML: all templates and magic variables
2464 *
2465 * @param string $tex The text to transform
2466 * @param array $args Key-value pairs representing template parameters to substitute
2467 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2468 * @private
2469 */
2470 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2471 # Prevent too big inclusions
2472 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2473 return $text;
2474 }
2475
2476 $fname = 'Parser::replaceVariables';
2477 wfProfileIn( $fname );
2478
2479 # This function is called recursively. To keep track of arguments we need a stack:
2480 array_push( $this->mArgStack, $args );
2481
2482 $braceCallbacks = array();
2483 if ( !$argsOnly ) {
2484 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2485 }
2486 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2487 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2488 }
2489 $callbacks = array();
2490 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2491 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2492 $text = $this->replace_callback ($text, $callbacks);
2493
2494 array_pop( $this->mArgStack );
2495
2496 wfProfileOut( $fname );
2497 return $text;
2498 }
2499
2500 /**
2501 * Replace magic variables
2502 * @private
2503 */
2504 function variableSubstitution( $matches ) {
2505 $fname = 'Parser::variableSubstitution';
2506 $varname = $matches[1];
2507 wfProfileIn( $fname );
2508 if ( !$this->mVariables ) {
2509 $this->initialiseVariables();
2510 }
2511 $skip = false;
2512 if ( $this->mOutputType == OT_WIKI ) {
2513 # Do only magic variables prefixed by SUBST
2514 $mwSubst =& MagicWord::get( MAG_SUBST );
2515 if (!$mwSubst->matchStartAndRemove( $varname ))
2516 $skip = true;
2517 # Note that if we don't substitute the variable below,
2518 # we don't remove the {{subst:}} magic word, in case
2519 # it is a template rather than a magic variable.
2520 }
2521 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2522 $id = $this->mVariables[$varname];
2523 $text = $this->getVariableValue( $id );
2524 $this->mOutput->mContainsOldMagic = true;
2525 } else {
2526 $text = $matches[0];
2527 }
2528 wfProfileOut( $fname );
2529 return $text;
2530 }
2531
2532 # Split template arguments
2533 function getTemplateArgs( $argsString ) {
2534 if ( $argsString === '' ) {
2535 return array();
2536 }
2537
2538 $args = explode( '|', substr( $argsString, 1 ) );
2539
2540 # If any of the arguments contains a '[[' but no ']]', it needs to be
2541 # merged with the next arg because the '|' character between belongs
2542 # to the link syntax and not the template parameter syntax.
2543 $argc = count($args);
2544
2545 for ( $i = 0; $i < $argc-1; $i++ ) {
2546 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2547 $args[$i] .= '|'.$args[$i+1];
2548 array_splice($args, $i+1, 1);
2549 $i--;
2550 $argc--;
2551 }
2552 }
2553
2554 return $args;
2555 }
2556
2557 /**
2558 * Return the text of a template, after recursively
2559 * replacing any variables or templates within the template.
2560 *
2561 * @param array $piece The parts of the template
2562 * $piece['text']: matched text
2563 * $piece['title']: the title, i.e. the part before the |
2564 * $piece['parts']: the parameter array
2565 * @return string the text of the template
2566 * @private
2567 */
2568 function braceSubstitution( $piece ) {
2569 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $action;
2570 $fname = 'Parser::braceSubstitution';
2571 wfProfileIn( $fname );
2572
2573 # Flags
2574 $found = false; # $text has been filled
2575 $nowiki = false; # wiki markup in $text should be escaped
2576 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2577 $noargs = false; # Don't replace triple-brace arguments in $text
2578 $replaceHeadings = false; # Make the edit section links go to the template not the article
2579 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2580 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2581
2582 # Title object, where $text came from
2583 $title = NULL;
2584
2585 $linestart = '';
2586
2587 # $part1 is the bit before the first |, and must contain only title characters
2588 # $args is a list of arguments, starting from index 0, not including $part1
2589
2590 $part1 = $piece['title'];
2591 # If the third subpattern matched anything, it will start with |
2592
2593 if (null == $piece['parts']) {
2594 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2595 if ($replaceWith != $piece['text']) {
2596 $text = $replaceWith;
2597 $found = true;
2598 $noparse = true;
2599 $noargs = true;
2600 }
2601 }
2602
2603 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2604 $argc = count( $args );
2605
2606 # SUBST
2607 if ( !$found ) {
2608 $mwSubst =& MagicWord::get( MAG_SUBST );
2609 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2610 # One of two possibilities is true:
2611 # 1) Found SUBST but not in the PST phase
2612 # 2) Didn't find SUBST and in the PST phase
2613 # In either case, return without further processing
2614 $text = $piece['text'];
2615 $found = true;
2616 $noparse = true;
2617 $noargs = true;
2618 }
2619 }
2620
2621 # MSG, MSGNW, INT and RAW
2622 if ( !$found ) {
2623 # Check for MSGNW:
2624 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2625 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2626 $nowiki = true;
2627 } else {
2628 # Remove obsolete MSG:
2629 $mwMsg =& MagicWord::get( MAG_MSG );
2630 $mwMsg->matchStartAndRemove( $part1 );
2631 }
2632
2633 # Check for RAW:
2634 $mwRaw =& MagicWord::get( MAG_RAW );
2635 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2636 $forceRawInterwiki = true;
2637 }
2638
2639 # Check if it is an internal message
2640 $mwInt =& MagicWord::get( MAG_INT );
2641 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2642 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2643 $text = $linestart . wfMsgReal( $part1, $args, true );
2644 $found = true;
2645 }
2646 }
2647 }
2648
2649 # NS
2650 if ( !$found ) {
2651 # Check for NS: (namespace expansion)
2652 $mwNs = MagicWord::get( MAG_NS );
2653 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2654 if ( intval( $part1 ) || $part1 == "0" ) {
2655 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2656 $found = true;
2657 } else {
2658 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2659 if ( !is_null( $index ) ) {
2660 $text = $linestart . $wgContLang->getNsText( $index );
2661 $found = true;
2662 }
2663 }
2664 }
2665 }
2666
2667 # URLENCODE
2668 if( !$found ) {
2669 $urlencode =& MagicWord::get( MAG_URLENCODE );
2670 if( $urlencode->matchStartAndRemove( $part1 ) ) {
2671 $text = $linestart . urlencode( $part1 );
2672 $found = true;
2673 }
2674 }
2675
2676 # LCFIRST, UCFIRST, LC and UC
2677 if ( !$found ) {
2678 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2679 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2680 $lc =& MagicWord::get( MAG_LC );
2681 $uc =& MagicWord::get( MAG_UC );
2682 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2683 $text = $linestart . $wgContLang->lcfirst( $part1 );
2684 $found = true;
2685 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2686 $text = $linestart . $wgContLang->ucfirst( $part1 );
2687 $found = true;
2688 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2689 $text = $linestart . $wgContLang->lc( $part1 );
2690 $found = true;
2691 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2692 $text = $linestart . $wgContLang->uc( $part1 );
2693 $found = true;
2694 }
2695 }
2696
2697 # LOCALURL and FULLURL
2698 if ( !$found ) {
2699 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2700 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2701 $mwFull =& MagicWord::get( MAG_FULLURL );
2702 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2703
2704
2705 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2706 $func = 'getLocalURL';
2707 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2708 $func = 'escapeLocalURL';
2709 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2710 $func = 'getFullURL';
2711 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2712 $func = 'escapeFullURL';
2713 } else {
2714 $func = false;
2715 }
2716
2717 if ( $func !== false ) {
2718 $title = Title::newFromText( $part1 );
2719 # Due to order of execution of a lot of bits, the values might be encoded
2720 # before arriving here; if that's true, then the title can't be created
2721 # and the variable will fail. If we can't get a decent title from the first
2722 # attempt, url-decode and try for a second.
2723 if( is_null( $title ) )
2724 $title = Title::newFromUrl( urldecode( $part1 ) );
2725 if ( !is_null( $title ) ) {
2726 if ( $argc > 0 ) {
2727 $text = $linestart . $title->$func( $args[0] );
2728 } else {
2729 $text = $linestart . $title->$func();
2730 }
2731 $found = true;
2732 }
2733 }
2734 }
2735
2736 $lang = $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
2737 # GRAMMAR
2738 if ( !$found && $argc == 1 ) {
2739 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2740 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2741 $text = $linestart . $lang->convertGrammar( $args[0], $part1 );
2742 $found = true;
2743 }
2744 }
2745
2746 # PLURAL
2747 if ( !$found && $argc >= 2 ) {
2748 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2749 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2750 while ( count($args) < 5 ) { $args[] = $args[count($args)-1]; }
2751 $text = $linestart . $lang->convertPlural( $part1, $args[0], $args[1],
2752 $args[2], $args[3], $args[4]);
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 * Tag hook handler for 'pre'.
4036 */
4037 function renderPreTag( $text, $attribs, $parser ) {
4038 // Backwards-compatibility hack
4039 $content = preg_replace( '!<nowiki>(.*?)</nowiki>!is', '\\1', $text );
4040
4041 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4042 return wfOpenElement( 'pre', $attribs ) .
4043 wfEscapeHTMLTagsOnly( $content ) .
4044 '</pre>';
4045 }
4046
4047 /**
4048 * Renders an image gallery from a text with one line per image.
4049 * text labels may be given by using |-style alternative text. E.g.
4050 * Image:one.jpg|The number "1"
4051 * Image:tree.jpg|A tree
4052 * given as text will return the HTML of a gallery with two images,
4053 * labeled 'The number "1"' and
4054 * 'A tree'.
4055 */
4056 function renderImageGallery( $text ) {
4057 $ig = new ImageGallery();
4058 $ig->setShowBytes( false );
4059 $ig->setShowFilename( false );
4060 $ig->setParsing();
4061 $lines = explode( "\n", $text );
4062
4063 foreach ( $lines as $line ) {
4064 # match lines like these:
4065 # Image:someimage.jpg|This is some image
4066 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4067 # Skip empty lines
4068 if ( count( $matches ) == 0 ) {
4069 continue;
4070 }
4071 $nt =& Title::newFromText( $matches[1] );
4072 if( is_null( $nt ) ) {
4073 # Bogus title. Ignore these so we don't bomb out later.
4074 continue;
4075 }
4076 if ( isset( $matches[3] ) ) {
4077 $label = $matches[3];
4078 } else {
4079 $label = '';
4080 }
4081
4082 $pout = $this->parse( $label,
4083 $this->mTitle,
4084 $this->mOptions,
4085 false, // Strip whitespace...?
4086 false // Don't clear state!
4087 );
4088 $html = $pout->getText();
4089
4090 $ig->add( new Image( $nt ), $html );
4091
4092 # Only add real images (bug #5586)
4093 if ( $nt->getNamespace() == NS_IMAGE ) {
4094 $this->mOutput->addImage( $nt->getDBkey() );
4095 }
4096 }
4097 return $ig->toHTML();
4098 }
4099
4100 /**
4101 * Parse image options text and use it to make an image
4102 */
4103 function makeImage( &$nt, $options ) {
4104 global $wgUseImageResize;
4105
4106 $align = '';
4107
4108 # Check if the options text is of the form "options|alt text"
4109 # Options are:
4110 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4111 # * left no resizing, just left align. label is used for alt= only
4112 # * right same, but right aligned
4113 # * none same, but not aligned
4114 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4115 # * center center the image
4116 # * framed Keep original image size, no magnify-button.
4117
4118 $part = explode( '|', $options);
4119
4120 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
4121 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
4122 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
4123 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
4124 $mwNone =& MagicWord::get( MAG_IMG_NONE );
4125 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
4126 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
4127 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
4128 $caption = '';
4129
4130 $width = $height = $framed = $thumb = false;
4131 $manual_thumb = '' ;
4132
4133 foreach( $part as $key => $val ) {
4134 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
4135 $thumb=true;
4136 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
4137 # use manually specified thumbnail
4138 $thumb=true;
4139 $manual_thumb = $match;
4140 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
4141 # remember to set an alignment, don't render immediately
4142 $align = 'right';
4143 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
4144 # remember to set an alignment, don't render immediately
4145 $align = 'left';
4146 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
4147 # remember to set an alignment, don't render immediately
4148 $align = 'center';
4149 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
4150 # remember to set an alignment, don't render immediately
4151 $align = 'none';
4152 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
4153 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
4154 # $match is the image width in pixels
4155 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
4156 $width = intval( $m[1] );
4157 $height = intval( $m[2] );
4158 } else {
4159 $width = intval($match);
4160 }
4161 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
4162 $framed=true;
4163 } else {
4164 $caption = $val;
4165 }
4166 }
4167 # Strip bad stuff out of the alt text
4168 $alt = $this->replaceLinkHoldersText( $caption );
4169
4170 # make sure there are no placeholders in thumbnail attributes
4171 # that are later expanded to html- so expand them now and
4172 # remove the tags
4173 $alt = $this->unstrip($alt, $this->mStripState);
4174 $alt = Sanitizer::stripAllTags( $alt );
4175
4176 # Linker does the rest
4177 $sk =& $this->mOptions->getSkin();
4178 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
4179 }
4180
4181 /**
4182 * Set a flag in the output object indicating that the content is dynamic and
4183 * shouldn't be cached.
4184 */
4185 function disableCache() {
4186 wfDebug( "Parser output marked as uncacheable.\n" );
4187 $this->mOutput->mCacheTime = -1;
4188 }
4189
4190 /**#@+
4191 * Callback from the Sanitizer for expanding items found in HTML attribute
4192 * values, so they can be safely tested and escaped.
4193 * @param string $text
4194 * @param array $args
4195 * @return string
4196 * @private
4197 */
4198 function attributeStripCallback( &$text, $args ) {
4199 $text = $this->replaceVariables( $text, $args );
4200 $text = $this->unstripForHTML( $text );
4201 return $text;
4202 }
4203
4204 function unstripForHTML( $text ) {
4205 $text = $this->unstrip( $text, $this->mStripState );
4206 $text = $this->unstripNoWiki( $text, $this->mStripState );
4207 return $text;
4208 }
4209 /**#@-*/
4210
4211 /**#@+
4212 * Accessor/mutator
4213 */
4214 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4215 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4216 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4217 /**#@-*/
4218
4219 /**#@+
4220 * Accessor
4221 */
4222 function getTags() { return array_keys( $this->mTagHooks ); }
4223 /**#@-*/
4224
4225
4226 /**
4227 * Break wikitext input into sections, and either pull or replace
4228 * some particular section's text.
4229 *
4230 * External callers should use the getSection and replaceSection methods.
4231 *
4232 * @param $text Page wikitext
4233 * @param $section Numbered section. 0 pulls the text before the first
4234 * heading; other numbers will pull the given section
4235 * along with its lower-level subsections.
4236 * @param $mode One of "get" or "replace"
4237 * @param $newtext Replacement text for section data.
4238 * @return string for "get", the extracted section text.
4239 * for "replace", the whole page with the section replaced.
4240 */
4241 private function extractSections( $text, $section, $mode, $newtext='' ) {
4242 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
4243 # comments to be stripped as well)
4244 $striparray = array();
4245
4246 $oldOutputType = $this->mOutputType;
4247 $oldOptions = $this->mOptions;
4248 $this->mOptions = new ParserOptions();
4249 $this->mOutputType = OT_WIKI;
4250
4251 $striptext = $this->strip( $text, $striparray, true );
4252
4253 $this->mOutputType = $oldOutputType;
4254 $this->mOptions = $oldOptions;
4255
4256 # now that we can be sure that no pseudo-sections are in the source,
4257 # split it up by section
4258 $uniq = preg_quote( $this->uniqPrefix(), '/' );
4259 $comment = "(?:$uniq-!--.*?QINU)";
4260 $secs = preg_split(
4261 /*
4262 "/
4263 ^(
4264 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4265 (?:
4266 (=+) # Should this be limited to 6?
4267 .+? # Section title...
4268 \\2 # Ending = count must match start
4269 |
4270 ^
4271 <h([1-6])\b.*?>
4272 .*?
4273 <\/h\\3\s*>
4274 )
4275 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4276 )$
4277 /mix",
4278 */
4279 "/
4280 (
4281 ^
4282 (?:$comment|<\/?noinclude>)* # Initial comments will be stripped
4283 (=+) # Should this be limited to 6?
4284 .+? # Section title...
4285 \\2 # Ending = count must match start
4286 (?:$comment|<\/?noinclude>|\s+)* # Trailing whitespace ok
4287 $
4288 |
4289 <h([1-6])\b.*?>
4290 .*?
4291 <\/h\\3\s*>
4292 )
4293 /mix",
4294 $striptext, -1,
4295 PREG_SPLIT_DELIM_CAPTURE);
4296
4297 if( $mode == "get" ) {
4298 if( $section == 0 ) {
4299 // "Section 0" returns the content before any other section.
4300 $rv = $secs[0];
4301 } else {
4302 $rv = "";
4303 }
4304 } elseif( $mode == "replace" ) {
4305 if( $section == 0 ) {
4306 $rv = $newtext . "\n\n";
4307 $remainder = true;
4308 } else {
4309 $rv = $secs[0];
4310 $remainder = false;
4311 }
4312 }
4313 $count = 0;
4314 $sectionLevel = 0;
4315 for( $index = 1; $index < count( $secs ); ) {
4316 $headerLine = $secs[$index++];
4317 if( $secs[$index] ) {
4318 // A wiki header
4319 $headerLevel = strlen( $secs[$index++] );
4320 } else {
4321 // An HTML header
4322 $index++;
4323 $headerLevel = intval( $secs[$index++] );
4324 }
4325 $content = $secs[$index++];
4326
4327 $count++;
4328 if( $mode == "get" ) {
4329 if( $count == $section ) {
4330 $rv = $headerLine . $content;
4331 $sectionLevel = $headerLevel;
4332 } elseif( $count > $section ) {
4333 if( $sectionLevel && $headerLevel > $sectionLevel ) {
4334 $rv .= $headerLine . $content;
4335 } else {
4336 // Broke out to a higher-level section
4337 break;
4338 }
4339 }
4340 } elseif( $mode == "replace" ) {
4341 if( $count < $section ) {
4342 $rv .= $headerLine . $content;
4343 } elseif( $count == $section ) {
4344 $rv .= $newtext . "\n\n";
4345 $sectionLevel = $headerLevel;
4346 } elseif( $count > $section ) {
4347 if( $headerLevel <= $sectionLevel ) {
4348 // Passed the section's sub-parts.
4349 $remainder = true;
4350 }
4351 if( $remainder ) {
4352 $rv .= $headerLine . $content;
4353 }
4354 }
4355 }
4356 }
4357 # reinsert stripped tags
4358 $rv = $this->unstrip( $rv, $striparray );
4359 $rv = $this->unstripNoWiki( $rv, $striparray );
4360 $rv = trim( $rv );
4361 return $rv;
4362 }
4363
4364 /**
4365 * This function returns the text of a section, specified by a number ($section).
4366 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4367 * the first section before any such heading (section 0).
4368 *
4369 * If a section contains subsections, these are also returned.
4370 *
4371 * @param $text String: text to look in
4372 * @param $section Integer: section number
4373 * @return string text of the requested section
4374 */
4375 function getSection( $text, $section ) {
4376 return $this->extractSections( $text, $section, "get" );
4377 }
4378
4379 function replaceSection( $oldtext, $section, $text ) {
4380 return $this->extractSections( $oldtext, $section, "replace", $text );
4381 }
4382
4383 }
4384
4385 /**
4386 * @todo document
4387 * @package MediaWiki
4388 */
4389 class ParserOutput
4390 {
4391 var $mText, # The output text
4392 $mLanguageLinks, # List of the full text of language links, in the order they appear
4393 $mCategories, # Map of category names to sort keys
4394 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
4395 $mCacheTime, # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
4396 $mVersion, # Compatibility check
4397 $mTitleText, # title text of the chosen language variant
4398 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
4399 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
4400 $mImages, # DB keys of the images used, in the array key only
4401 $mExternalLinks, # External link URLs, in the key only
4402 $mHTMLtitle, # Display HTML title
4403 $mSubtitle, # Additional subtitle
4404 $mNewSection; # Show a new section link?
4405
4406 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
4407 $containsOldMagic = false, $titletext = '' )
4408 {
4409 $this->mText = $text;
4410 $this->mLanguageLinks = $languageLinks;
4411 $this->mCategories = $categoryLinks;
4412 $this->mContainsOldMagic = $containsOldMagic;
4413 $this->mCacheTime = '';
4414 $this->mVersion = MW_PARSER_VERSION;
4415 $this->mTitleText = $titletext;
4416 $this->mLinks = array();
4417 $this->mTemplates = array();
4418 $this->mImages = array();
4419 $this->mExternalLinks = array();
4420 $this->mHTMLtitle = "" ;
4421 $this->mSubtitle = "" ;
4422 $this->mNewSection = false;
4423 }
4424
4425 function getText() { return $this->mText; }
4426 function &getLanguageLinks() { return $this->mLanguageLinks; }
4427 function getCategoryLinks() { return array_keys( $this->mCategories ); }
4428 function &getCategories() { return $this->mCategories; }
4429 function getCacheTime() { return $this->mCacheTime; }
4430 function getTitleText() { return $this->mTitleText; }
4431 function &getLinks() { return $this->mLinks; }
4432 function &getTemplates() { return $this->mTemplates; }
4433 function &getImages() { return $this->mImages; }
4434 function &getExternalLinks() { return $this->mExternalLinks; }
4435
4436 function containsOldMagic() { return $this->mContainsOldMagic; }
4437 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
4438 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
4439 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
4440 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
4441 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
4442 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
4443
4444 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
4445 function addImage( $name ) { $this->mImages[$name] = 1; }
4446 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
4447 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
4448
4449 function setNewSection( $value ) {
4450 $this->mNewSection = (bool)$value;
4451 }
4452 function getNewSection() {
4453 return (bool)$this->mNewSection;
4454 }
4455
4456 function addLink( $title, $id ) {
4457 $ns = $title->getNamespace();
4458 $dbk = $title->getDBkey();
4459 if ( !isset( $this->mLinks[$ns] ) ) {
4460 $this->mLinks[$ns] = array();
4461 }
4462 $this->mLinks[$ns][$dbk] = $id;
4463 }
4464
4465 function addTemplate( $title, $id ) {
4466 $ns = $title->getNamespace();
4467 $dbk = $title->getDBkey();
4468 if ( !isset( $this->mTemplates[$ns] ) ) {
4469 $this->mTemplates[$ns] = array();
4470 }
4471 $this->mTemplates[$ns][$dbk] = $id;
4472 }
4473
4474 /**
4475 * Return true if this cached output object predates the global or
4476 * per-article cache invalidation timestamps, or if it comes from
4477 * an incompatible older version.
4478 *
4479 * @param string $touched the affected article's last touched timestamp
4480 * @return bool
4481 * @public
4482 */
4483 function expired( $touched ) {
4484 global $wgCacheEpoch;
4485 return $this->getCacheTime() == -1 || // parser says it's uncacheable
4486 $this->getCacheTime() < $touched ||
4487 $this->getCacheTime() <= $wgCacheEpoch ||
4488 !isset( $this->mVersion ) ||
4489 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
4490 }
4491 }
4492
4493 /**
4494 * Set options of the Parser
4495 * @todo document
4496 * @package MediaWiki
4497 */
4498 class ParserOptions
4499 {
4500 # All variables are private
4501 var $mUseTeX; # Use texvc to expand <math> tags
4502 var $mUseDynamicDates; # Use DateFormatter to format dates
4503 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
4504 var $mAllowExternalImages; # Allow external images inline
4505 var $mAllowExternalImagesFrom; # If not, any exception?
4506 var $mSkin; # Reference to the preferred skin
4507 var $mDateFormat; # Date format index
4508 var $mEditSection; # Create "edit section" links
4509 var $mNumberHeadings; # Automatically number headings
4510 var $mAllowSpecialInclusion; # Allow inclusion of special pages
4511 var $mTidy; # Ask for tidy cleanup
4512 var $mInterfaceMessage; # Which lang to call for PLURAL and GRAMMAR
4513
4514 function getUseTeX() { return $this->mUseTeX; }
4515 function getUseDynamicDates() { return $this->mUseDynamicDates; }
4516 function getInterwikiMagic() { return $this->mInterwikiMagic; }
4517 function getAllowExternalImages() { return $this->mAllowExternalImages; }
4518 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
4519 function &getSkin() { return $this->mSkin; }
4520 function getDateFormat() { return $this->mDateFormat; }
4521 function getEditSection() { return $this->mEditSection; }
4522 function getNumberHeadings() { return $this->mNumberHeadings; }
4523 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
4524 function getTidy() { return $this->mTidy; }
4525 function getInterfaceMessage() { return $this->mInterfaceMessage; }
4526
4527 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
4528 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
4529 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
4530 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
4531 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
4532 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
4533 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
4534 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
4535 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
4536 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
4537 function setSkin( &$x ) { $this->mSkin =& $x; }
4538 function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage, $x); }
4539
4540 function ParserOptions() {
4541 global $wgUser;
4542 $this->initialiseFromUser( $wgUser );
4543 }
4544
4545 /**
4546 * Get parser options
4547 * @static
4548 */
4549 function newFromUser( &$user ) {
4550 $popts = new ParserOptions;
4551 $popts->initialiseFromUser( $user );
4552 return $popts;
4553 }
4554
4555 /** Get user options */
4556 function initialiseFromUser( &$userInput ) {
4557 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
4558 global $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
4559 $fname = 'ParserOptions::initialiseFromUser';
4560 wfProfileIn( $fname );
4561 if ( !$userInput ) {
4562 $user = new User;
4563 $user->setLoaded( true );
4564 } else {
4565 $user =& $userInput;
4566 }
4567
4568 $this->mUseTeX = $wgUseTeX;
4569 $this->mUseDynamicDates = $wgUseDynamicDates;
4570 $this->mInterwikiMagic = $wgInterwikiMagic;
4571 $this->mAllowExternalImages = $wgAllowExternalImages;
4572 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
4573 wfProfileIn( $fname.'-skin' );
4574 $this->mSkin =& $user->getSkin();
4575 wfProfileOut( $fname.'-skin' );
4576 $this->mDateFormat = $user->getOption( 'date' );
4577 $this->mEditSection = true;
4578 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4579 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4580 $this->mTidy = false;
4581 $this->mInterfaceMessage = false;
4582 wfProfileOut( $fname );
4583 }
4584 }
4585
4586 /**
4587 * Callback function used by Parser::replaceLinkHolders()
4588 * to substitute link placeholders.
4589 */
4590 function &wfOutputReplaceMatches( $matches ) {
4591 global $wgOutputReplace;
4592 return $wgOutputReplace[$matches[1]];
4593 }
4594
4595 /**
4596 * Return the total number of articles
4597 */
4598 function wfNumberOfArticles() {
4599 global $wgNumberOfArticles;
4600
4601 wfLoadSiteStats();
4602 return $wgNumberOfArticles;
4603 }
4604
4605 /**
4606 * Return the number of files
4607 */
4608 function wfNumberOfFiles() {
4609 $fname = 'wfNumberOfFiles';
4610
4611 wfProfileIn( $fname );
4612 $dbr =& wfGetDB( DB_SLAVE );
4613 $numImages = $dbr->selectField('site_stats', 'ss_images', array(), $fname );
4614 wfProfileOut( $fname );
4615
4616 return $numImages;
4617 }
4618
4619 /**
4620 * Return the number of user accounts
4621 * @return integer
4622 */
4623 function wfNumberOfUsers() {
4624 wfProfileIn( 'wfNumberOfUsers' );
4625 $dbr =& wfGetDB( DB_SLAVE );
4626 $count = $dbr->selectField( 'site_stats', 'ss_users', array(), 'wfNumberOfUsers' );
4627 wfProfileOut( 'wfNumberOfUsers' );
4628 return (int)$count;
4629 }
4630
4631 /**
4632 * Return the total number of pages
4633 * @return integer
4634 */
4635 function wfNumberOfPages() {
4636 wfProfileIn( 'wfNumberOfPages' );
4637 $dbr =& wfGetDB( DB_SLAVE );
4638 $count = $dbr->selectField( 'site_stats', 'ss_total_pages', array(), 'wfNumberOfPages' );
4639 wfProfileOut( 'wfNumberOfPages' );
4640 return (int)$count;
4641 }
4642
4643 /**
4644 * Get various statistics from the database
4645 * @private
4646 */
4647 function wfLoadSiteStats() {
4648 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4649 $fname = 'wfLoadSiteStats';
4650
4651 if ( -1 != $wgNumberOfArticles ) return;
4652 $dbr =& wfGetDB( DB_SLAVE );
4653 $s = $dbr->selectRow( 'site_stats',
4654 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4655 array( 'ss_row_id' => 1 ), $fname
4656 );
4657
4658 if ( $s === false ) {
4659 return;
4660 } else {
4661 $wgTotalViews = $s->ss_total_views;
4662 $wgTotalEdits = $s->ss_total_edits;
4663 $wgNumberOfArticles = $s->ss_good_articles;
4664 }
4665 }
4666
4667 /**
4668 * Escape html tags
4669 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4670 *
4671 * @param $in String: text that might contain HTML tags.
4672 * @return string Escaped string
4673 */
4674 function wfEscapeHTMLTagsOnly( $in ) {
4675 return str_replace(
4676 array( '"', '>', '<' ),
4677 array( '&quot;', '&gt;', '&lt;' ),
4678 $in );
4679 }
4680
4681 ?>