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