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