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