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