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