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