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