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