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