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