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