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