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