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